Initial import

vnext
Paul Schneider 10 years ago
parent 0c865416ca
commit 04804b89a9
279 changed files with 12945 additions and 0 deletions

Binary file not shown.

@ -0,0 +1,21 @@
using System;
using WorkFlowProvider;
using yavscModel.WorkFlow;
namespace ITContent
{
public interface IITContent: IContentProvider
{
int NewProject(string name, string desc, string ownedId);
void AddDevRessource (int prjId, string userName);
int NewTask(int projectId, string name, string desc);
void SetProjectName(int projectId, string name);
void SetProjectDesc(int projectId, string desc);
void SetTaskName(int taskId, string name);
void SetStartDate(int taskId, DateTime d);
void SetEndDate(int taskId, DateTime d);
void SetTaskDesc(int taskId, string desc);
void NewRelease(int projectId, string Version);
}
}

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{88D83FC9-4158-4435-98A6-1F8F7F448B8F}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ITContent</RootNamespace>
<AssemblyName>ITContent</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="IITContent.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\WorkFlowProvider\WorkFlowProvider.csproj">
<Project>{821FF72D-9F4B-4A2C-B95C-7B965291F119}</Project>
<Name>WorkFlowProvider</Name>
</ProjectReference>
<ProjectReference Include="..\yavscModel\yavscModel.csproj">
<Project>{68F5B80A-616E-4C3C-91A0-828AA40000BD}</Project>
<Name>yavscModel</Name>
</ProjectReference>
</ItemGroup>
</Project>

@ -0,0 +1,22 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("ITContent")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Paul Schneider")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("NpgsqlBlogProvider")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("paul")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,35 @@
using System;
using System.Configuration;
using System.Reflection;
using System.Collections.Specialized;
using Npgsql.Web.Blog.Configuration;
namespace Npgsql.Web.Blog
{
public static class BlogHelper
{
public static BlogProvider GetProvider ()
{
BlogProvidersConfigurationSection config = ConfigurationManager.GetSection ("system.web/blog") as BlogProvidersConfigurationSection;
if (config == null)
throw new ConfigurationErrorsException("The configuration bloc for the blog provider was not found");
BlogProviderConfigurationElement celt =
config.Providers.GetElement (config.DefaultProvider);
if (config == null)
throw new ConfigurationErrorsException("The default blog provider was not found");
ConstructorInfo ci = Type.GetType (celt.Type).GetConstructor (Type.EmptyTypes);
BlogProvider bp = ci.Invoke (Type.EmptyTypes) as BlogProvider;
NameValueCollection c = new NameValueCollection ();
c.Add ("name", celt.Name);
c.Add ("type", celt.Type);
c.Add ("connectionStringName", celt.ConnectionStringName);
c.Add ("description", celt.Description);
c.Add ("applicationName", celt.ApplicationName);
bp.Initialize (celt.Name, c);
return bp;
}
}
}

@ -0,0 +1,61 @@
using System;
using Npgsql.Web.Blog.DataModel;
namespace Npgsql.Web.Blog
{
public static class BlogManager
{
public static long RemoveComment(long cmtid)
{
return Provider.RemoveComment (cmtid);
}
public static void Comment (string from, long postid, string content, bool visible)
{
provider.Comment (from, postid, content);
}
static BlogProvider provider;
public static BlogProvider Provider {
get {
if (provider == null)
provider = BlogHelper.GetProvider();
return provider;
}
}
public static BlogEntry GetPost (string username, string title)
{
return Provider.GetPost (username, title );
}
public static BlogEntry GetPost(long postid)
{
return Provider.GetPost (postid);
}
public static void Post(string username, string title, string content, bool visible)
{
Provider.Post(username, title, content, visible );
}
public static void UpdatePost(long postid, string content, bool visible)
{
Provider.UpdatePost(postid, content, visible);
}
public static BlogEntryCollection FindPost (string pattern, FindBlogEntryFlags searchflags, int pageIndex, int pageSize, out int totalRecords)
{
return Provider.FindPost (pattern, searchflags, pageIndex, pageSize, out totalRecords);
}
public static void RemovePost (string username, string title)
{
Provider.RemovePost (username, title);
}
public static BlogEntryCollection LastPosts (int pageIndex, int pageSize, out int totalRecords)
{
return Provider.LastPosts (pageIndex, pageSize, out totalRecords);
}
public static Comment[] GetComments(long postid, bool getHidden=true)
{
return Provider.GetComments (postid,getHidden);
}
}
}

@ -0,0 +1,32 @@
using System;
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Generic;
using Npgsql.Web.Blog.DataModel;
namespace Npgsql.Web.Blog
{
public abstract class BlogProvider: ProviderBase
{
public abstract BlogEntry GetPost (long postid);
public abstract BlogEntry GetPost (string username, string title);
public abstract long GetPostId (string username, string title);
public abstract long Post (string username, string title, string content, bool visible);
public abstract void UpdatePost (long postid, string content, bool visible);
public abstract BlogEntryCollection FindPost (string pattern, FindBlogEntryFlags searchflags,
int pageIndex, int pageSize, out int totalRecords);
public abstract void RemovePost (string username, string title);
public abstract void RemovePost (long postid);
public abstract long RemoveComment (long cmtid);
public abstract BlogEntryCollection LastPosts(int pageIndex, int pageSize, out int totalRecords);
public abstract string BlogTitle (string username);
public abstract long Comment (string from, long postid, string content);
public abstract Comment[] GetComments (long postid, bool getHidden) ;
public abstract bool AutoValidateComment { get; set; }
public abstract void ValidateComment (long cmtid);
public abstract void UpdateComment (long cmtid, string content, bool visible);
}
}

@ -0,0 +1,40 @@
using System;
using System.Configuration;
using System.ComponentModel;
namespace Npgsql.Web.Blog.Configuration
{
public class BlogProviderConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey=true)]
public string Name {
get { return (string)this ["name"]; }
set { this ["name"] = value; }
}
[ConfigurationProperty("type", IsRequired = true, IsKey=false)]
public string Type {
get { return (string)this ["type"]; }
set { this ["type"] = value; }
}
[ConfigurationProperty("connectionStringName")]
public string ConnectionStringName {
get { return (string)this ["connectionStringName"]; }
set { this ["connectionStringName"] = value; }
}
[ConfigurationProperty("description")]
public string Description {
get { return (string)this ["description"]; }
set { this ["description"] = value; }
}
[ConfigurationProperty("applicationName")]
public string ApplicationName {
get { return (string)this ["applicationName"]; }
set { this ["applicationName"] = value; }
}
}
}

@ -0,0 +1,26 @@
using System;
using System.Configuration;
using System.ComponentModel;
namespace Npgsql.Web.Blog.Configuration
{
public class BlogProvidersConfigurationCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement ()
{
return new BlogProviderConfigurationElement();
}
protected override object GetElementKey (ConfigurationElement element)
{
return ((BlogProviderConfigurationElement) element).Name;
}
public BlogProviderConfigurationElement GetElement (string name)
{
return this.BaseGet(name) as BlogProviderConfigurationElement;
}
}
}

@ -0,0 +1,26 @@
using System;
using System.Configuration;
using System.ComponentModel;
namespace Npgsql.Web.Blog.Configuration
{
public class BlogProvidersConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("defaultProvider")]
public string DefaultProvider {
get { return (string)base ["defaultProvider"]; }
set { base ["defaultProvider"] = value; }
}
[ConfigurationProperty("providers")]
[ConfigurationCollection(typeof(BlogProvidersConfigurationCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public BlogProvidersConfigurationCollection Providers{
get { return (BlogProvidersConfigurationCollection) base ["providers"]; }
set { base ["providers"] = value; }
}
}
}

@ -0,0 +1,26 @@
using System;
using System.Configuration;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace Npgsql.Web.Blog.DataModel
{
public class Blog
{
string title;
[StringValidator(MaxLength=512)]
[Required]
[DisplayName("Titre")]
public string Title {
get {
return title;
}
set {
title = value;
}
}
}
}

@ -0,0 +1,91 @@
using System;
using System.Configuration;
using System.Configuration.Provider;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Npgsql.Web.Blog.DataModel
{
public class BlogEntry
{
long id;
[DisplayName("Identifiant numérique de billet")]
public long Id {
get {
return id;
}
set {
id = value;
}
}
string title;
[StringValidator(MaxLength=512)]
[DisplayName("Titre du billet")]
[StringLength(512)]
[RegularExpression("^[^:%&?]*$",ErrorMessage = "Les caratères suivants sont invalides pour un titre: :%&?")]
[Required(ErrorMessage = "S'il vous plait, saisissez un titre")]
public string Title {
get {
return title;
}
set {
title = value;
}
}
string content;
[DisplayName("Corps du billet")]
[Required(ErrorMessage = "S'il vous plait, saisissez un texte.")]
public string Content {
get {
return content;
}
set {
content = value;
}
}
string userName;
[StringValidator(MaxLength=255)]
[DisplayName("Nom de l'auteur")]
public string UserName {
get {
return userName;
}
set {
userName = value;
}
}
public DateTime posted;
[DisplayName("Date de creation")]
public DateTime Posted {
get {
return posted;
}
set {
posted = value;
}
}
public DateTime modified;
[DisplayName("Date de modification")]
public DateTime Modified {
get {
return modified;
}
set {
modified = value;
}
}
public bool Visible { get; set ; }
public string [] Tags { get; set ; }
}
}

@ -0,0 +1,12 @@
using System;
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Generic;
namespace Npgsql.Web.Blog.DataModel
{
public class BlogEntryCollection : List<BlogEntry>
{
}
}

@ -0,0 +1,76 @@
using System;
using System.Configuration;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Npgsql.Web.Blog.DataModel
{
public class Comment
{
long id;
[DisplayName("Identifiant numérique de commentaire")]
public long Id {
get {
return id;
}
set {
id = value;
}
}
long postid;
[DisplayName("Identifiant numérique du billet commenté")]
public long PostId {
get {
return postid;
}
set {
postid = value;
}
}
/// <summary>
/// Gets or sets the author of this comment.
/// </summary>
/// <value>From.</value>
public string From { get; set; }
string content;
[DisplayName("Contenu")]
[Required(ErrorMessage = "S'il vous plait, saisissez un contenu")]
public string CommentText {
get {
return content;
}
set {
content = value;
}
}
public DateTime posted;
[DisplayName("Date de creation")]
public DateTime Posted {
get {
return posted;
}
set {
posted = value;
}
}
public DateTime modified;
[DisplayName("Date de modification")]
public DateTime Modified {
get {
return modified;
}
set {
modified = value;
}
}
public bool Visible { get; set ; }
}
}

@ -0,0 +1,16 @@
using System;
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Generic;
namespace Npgsql.Web.Blog.DataModel
{
public enum FindBlogEntryFlags : byte {
MatchTitle = 1,
MatchContent = 2,
MatchUserName = 4,
MatchInvisible = 8
}
}

@ -0,0 +1,340 @@
using System;
using System.Configuration;
using System.Configuration.Provider;
using Npgsql;
using Npgsql.Web.Blog.DataModel;
using System.Collections.Generic;
namespace Npgsql.Web.Blog
{
public class NpgsqlBlogProvider : BlogProvider
{
string applicationName;
string connectionString;
#region implemented abstract members of BlogProvider
public override long GetPostId (string username, string title)
{
throw new NotImplementedException ();
}
public override Comment[] GetComments (long postid, bool getHidden)
{
List<Comment> cmts = new List<Comment> ();
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "select _id, username, bcontent, modified, posted, visible from comment " +
"where applicationname = @appname and postid = @id" +
((getHidden) ? " and visible = true ":" ") +
"order by posted asc" ;
cmd.Parameters.Add ("@appname", applicationName);
cmd.Parameters.Add ("@id", postid);
cnx.Open ();
using (NpgsqlDataReader rdr = cmd.ExecuteReader()) {
while (rdr.Read ()) {
Comment c = new Comment();
c.CommentText = rdr.GetString (rdr.GetOrdinal ("bcontent"));
c.From = rdr.GetString (rdr.GetOrdinal ("username"));
c.Modified = rdr.GetDateTime (rdr.GetOrdinal ("modified"));
c.Posted = rdr.GetDateTime (rdr.GetOrdinal ("posted"));
c.Visible = rdr.GetBoolean (rdr.GetOrdinal ("visible"));
c.PostId = postid;
c.Id = rdr.GetInt64(rdr.GetOrdinal("_id"));
cmts.Add (c);
}
}
}
return cmts.ToArray();
}
public override void UpdatePost (long postid, string content, bool visible)
{
using (NpgsqlConnection cnx = new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
DateTime now = DateTime.Now;
cmd.CommandText =
"update blog set modified=@now, bcontent=@content, " +
"visible = @visible where _id = @id";
cmd.Parameters.Add ("@now", now);
cmd.Parameters.Add ("@content", content);
cmd.Parameters.Add ("@visible", visible);
cmd.Parameters.Add ("@id", postid);
cnx.Open ();
cmd.ExecuteNonQuery ();
cnx.Close();
}
}
public override void RemovePost (long postid)
{
throw new NotImplementedException ();
}
public override long Comment (string from, long postid, string content)
{
if (from == null)
throw new ArgumentNullException("from");
if (content == null)
throw new ArgumentNullException("content");
bool visible = AutoValidateComment;
using (NpgsqlConnection cnx=
new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "insert into comment (postid,bcontent," +
"modified,posted,visible,username,applicationname)" +
"values (@postid,@bcontent,@modified,@posted," +
"@visible,@username,@appname) returning _id";
cmd.Parameters.Add ("@postid", postid);
cmd.Parameters.Add ("@bcontent", content);
DateTime now = DateTime.Now;
cmd.Parameters.Add ("@modified", now);
cmd.Parameters.Add ("@posted", now);
cmd.Parameters.Add ("@visible", visible);
cmd.Parameters.Add ("@username", from);
cmd.Parameters.Add ("@appname", applicationName);
cnx.Open ();
return (long) cmd.ExecuteScalar();
}
}
public override void ValidateComment (long cmtid)
{
throw new NotImplementedException ();
}
public override void UpdateComment
(long cmtid, string content, bool visible)
{
throw new NotImplementedException ();
}
private bool autoValidateComment = true;
public override bool AutoValidateComment {
get {
return autoValidateComment;
}
set {
autoValidateComment=value;
}
}
public override string BlogTitle
(string username)
{
throw new NotImplementedException ();
}
#endregion
public override void Initialize
(string name, System.Collections.Specialized.NameValueCollection config)
{
string cnxName = config ["connectionStringName"];
connectionString = ConfigurationManager.ConnectionStrings [cnxName].ConnectionString;
config.Remove ("connectionStringName");
applicationName = config ["applicationName"];
config.Remove ("applicationName");
defaultPageSize = int.Parse ( config ["pageLen"] ?? "10") ;
base.Initialize (name, config);
}
#region implemented abstract members of BlogProvider
public override BlogEntry GetPost (long postid)
{
BlogEntry be = null;
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "select username, title, bcontent, modified, posted, visible from blog " +
"where applicationname = @appname and _id = @id";
cmd.Parameters.Add ("@appname", applicationName);
cmd.Parameters.Add ("@id", postid);
cnx.Open ();
using (NpgsqlDataReader rdr = cmd.ExecuteReader()) {
if (rdr.Read ()) {
be = new BlogEntry ();
be.Title = rdr.GetString (rdr.GetOrdinal ("title"));
be.Content = rdr.GetString (rdr.GetOrdinal ("bcontent"));
be.UserName = rdr.GetString (rdr.GetOrdinal ("username"));
be.Modified = rdr.GetDateTime (rdr.GetOrdinal ("modified"));
be.Posted = rdr.GetDateTime (rdr.GetOrdinal ("posted"));
be.Visible = rdr.GetBoolean (rdr.GetOrdinal ("visible"));
be.Id = postid;
}
}
}
return be;
}
public override long RemoveComment (long cmtid)
{
long postid = 0;
using (NpgsqlConnection cnx = new NpgsqlConnection (connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand ()) {
cmd.CommandText = "delete from comment where _id = @id returning postid";
cmd.Parameters.Add ("id", cmtid);
cnx.Open ();
postid = (long) cmd.ExecuteScalar ();
}
return postid;
}
public override BlogEntry GetPost (string username, string title)
{
BlogEntry be = null;
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "select _id,bcontent,modified,posted,visible from blog " +
"where applicationname = @appname and username = @username and title = @title";
cmd.Parameters.Add ("@appname", applicationName);
cmd.Parameters.Add ("@username", username);
cmd.Parameters.Add ("@title", title);
cnx.Open ();
using (NpgsqlDataReader rdr = cmd.ExecuteReader()) {
if (rdr.Read ()) {
be = new BlogEntry ();
be.Title = title;
be.Content = rdr.GetString (rdr.GetOrdinal ("bcontent"));
be.UserName = username;
be.Modified = rdr.GetDateTime (rdr.GetOrdinal ("modified"));
be.Posted = rdr.GetDateTime (rdr.GetOrdinal ("posted"));
be.Visible = rdr.GetBoolean (rdr.GetOrdinal ("visible"));
be.Id = rdr.GetInt64 (rdr.GetOrdinal ("_id"));
}
}
}
return be;
}
public override long Post (string username, string title, string content, bool visible)
{
if (username == null)
throw new ArgumentNullException("username");
if (title == null)
throw new ArgumentNullException("title");
if (content == null)
throw new ArgumentNullException("content");
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "insert into blog (title,bcontent,modified,posted,visible,username,applicationname)" +
"values (@title,@bcontent,@modified,@posted,@visible,@username,@appname) returning _id";
cmd.Parameters.Add ("@title", title);
cmd.Parameters.Add ("@bcontent", content);
DateTime now = DateTime.Now;
cmd.Parameters.Add ("@modified", now);
cmd.Parameters.Add ("@posted", now);
cmd.Parameters.Add ("@visible", visible);
cmd.Parameters.Add ("@username", username);
cmd.Parameters.Add ("@appname", applicationName);
cnx.Open ();
return (long) cmd.ExecuteScalar();
}
}
public override BlogEntryCollection FindPost (string pattern, FindBlogEntryFlags searchflags, int pageIndex, int pageSize, out int totalRecords)
{
BlogEntryCollection c = new BlogEntryCollection ();
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "select title,bcontent,modified,posted,username,visible from blog " +
"where applicationname = @appname";
cmd.Parameters.Add ("@appname", applicationName);
if ((searchflags & FindBlogEntryFlags.MatchContent) > 0) {
cmd.CommandText += " and bcontent like @bcontent";
cmd.Parameters.Add ("@bcontent", pattern);
}
if ((searchflags & FindBlogEntryFlags.MatchTitle) > 0) {
cmd.CommandText += " and title like @title";
cmd.Parameters.Add ("@title", pattern);
}
if ((searchflags & FindBlogEntryFlags.MatchUserName) > 0) {
cmd.CommandText += " and username like @username";
cmd.Parameters.Add ("@username", pattern);
}
if ((searchflags & FindBlogEntryFlags.MatchInvisible) == 0) {
cmd.CommandText += " and visible = true";
}
cmd.CommandText += " order by posted desc";
cnx.Open ();
using (NpgsqlDataReader rdr = cmd.ExecuteReader()) {
totalRecords = 0;
int firstrec = pageIndex * pageSize;
int lastrec = firstrec + pageSize - 1;
while (rdr.Read()) {
if (totalRecords >= firstrec && totalRecords <= lastrec) {
BlogEntry be = new BlogEntry ();
be.Title = rdr.GetString (rdr.GetOrdinal ("title"));
be.Content = rdr.GetString (rdr.GetOrdinal ("bcontent"));
be.UserName = rdr.GetString (rdr.GetOrdinal ("username"));
be.Posted = rdr.GetDateTime (rdr.GetOrdinal ("posted"));
be.Modified = rdr.GetDateTime (rdr.GetOrdinal ("modified"));
be.Visible = rdr.GetBoolean (rdr.GetOrdinal ("visible"));
c.Add (be);
}
totalRecords++;
}
}
}
return c;
}
public override void RemovePost (string username, string title)
{
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "delete from blog where username = @username and applicationname = @appname and title=@title";
cmd.Parameters.Add ("@username",username);
cmd.Parameters.Add ("@appname", applicationName);
cmd.Parameters.Add ("@title",title);
cnx.Open ();
cmd.ExecuteNonQuery ();
cnx.Close();
}
}
int defaultPageSize = 10;
public override BlogEntryCollection LastPosts(int pageIndex, int pageSize, out int totalRecords)
{
BlogEntryCollection c = new BlogEntryCollection ();
using (NpgsqlConnection cnx=new NpgsqlConnection(connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
/*cmd.CommandText = "select blog.* from blog, " +
"(select max(posted) lpost, username " +
"from blog where applicationname = @appname " +
"group by username) as lblog " +
"where blog.posted = lblog.lpost and blog.username = lblog.username " ;
*/
cmd.CommandText = "select * " +
"from blog where applicationname = @appname and visible = true " +
" order by posted desc limit @len" ;
cmd.Parameters.Add ("@appname", applicationName);
cmd.Parameters.Add ("@len", defaultPageSize);
cnx.Open ();
using (NpgsqlDataReader rdr = cmd.ExecuteReader()) {
totalRecords = 0;
int firstrec = pageIndex * pageSize;
int lastrec = firstrec + pageSize - 1;
while (rdr.Read()) {
if (totalRecords >= firstrec && totalRecords <= lastrec) {
BlogEntry be = new BlogEntry ();
be.Title = rdr.GetString (rdr.GetOrdinal ("title"));
be.Content = rdr.GetString (rdr.GetOrdinal ("bcontent"));
be.UserName = rdr.GetString (rdr.GetOrdinal ("username"));
be.Posted = rdr.GetDateTime (rdr.GetOrdinal ("posted"));
be.Modified = rdr.GetDateTime (rdr.GetOrdinal ("modified"));
be.Visible = true; // because of sql code used
c.Add (be);
}
totalRecords++;
}
}
}
return c;
}
#endregion
}
}

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C6E9E91B-97D3-48D9-8AA7-05356929E162}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Npgsql.Web.Blog</RootNamespace>
<AssemblyName>NpgsqlBlogProvider</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<Compile Include="Configuration\BlogProviderConfigurationElement.cs" />
<Compile Include="Configuration\BlogProvidersConfigurationCollection.cs" />
<Compile Include="Configuration\BlogProvidersConfigurationSection.cs" />
<Compile Include="DataModel\BlogEntry.cs" />
<Compile Include="DataModel\BlogEntryCollection.cs" />
<Compile Include="BlogHelper.cs" />
<Compile Include="BlogManager.cs" />
<Compile Include="BlogProvider.cs" />
<Compile Include="NpgsqlBlogProvider.cs" />
<Compile Include="DataModel\FindBlogEntryFlags.cs" />
<Compile Include="AssemblyInfo.cs" />
<Compile Include="DataModel\Blog.cs" />
<Compile Include="DataModel\Comment.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="DataModel\" />
<Folder Include="Sql\" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="Npgsql" />
<Reference Include="System.Configuration" />
<Reference Include="System.ComponentModel.DataAnnotations" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedFlat" ResourceNamePolicy="FileFormatDefault" />
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
<ItemGroup>
<None Include="Sql\BlogTable.sql" />
</ItemGroup>
</Project>

@ -0,0 +1,21 @@
-- Table: blog
-- DROP TABLE blog;
CREATE TABLE blog
(
applicationname character varying(255) NOT NULL,
username character varying(255) NOT NULL,
posted timestamp with time zone NOT NULL,
modified timestamp with time zone NOT NULL,
title character varying(255) NOT NULL,
bcontent text NOT NULL,
CONSTRAINT pk_blog PRIMARY KEY (username , applicationname , title ),
CONSTRAINT bloguser FOREIGN KEY (applicationname, username)
REFERENCES users (applicationname, username) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);

@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("NpgsqlMRPProviders")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("paul")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BBA7175D-7F92-4278-96FC-84C495A2B5A6}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Npgsql.Web</RootNamespace>
<AssemblyName>NpgsqlMRPProviders</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<Compile Include="NpgsqlMembershipProvider.cs" />
<Compile Include="NpgsqlRoleProvider.cs" />
<Compile Include="NpgsqlProfileProvider.cs" />
<Compile Include="AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Web" />
<Reference Include="System.Configuration" />
<Reference Include="Npgsql" />
<Reference Include="System" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq" />
<Reference Include="System.Core" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedFlat" ResourceNamePolicy="FileFormatDefault" />
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
<ItemGroup>
<Folder Include="Sql\" />
</ItemGroup>
<ItemGroup>
<None Include="Sql\UsersTable.sql" />
<None Include="Sql\ProfileData.sql" />
<None Include="Sql\RolesTable.sql" />
<None Include="Sql\UserRoleTable.sql" />
<None Include="Sql\StockSymbols.sql" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,237 @@
using System;
using System.Configuration;
using System.Web.Profile;
using Npgsql;
namespace Npgsql.Web
{
public class NpgsqlProfileProvider: ProfileProvider
{
private string connectionString;
private string applicationName;
public NpgsqlProfileProvider ()
{
}
public override void Initialize (string iname, System.Collections.Specialized.NameValueCollection config)
{
// get the
// - application name
// - connection string name
// - the connection string from its name
string cnxName = config ["connectionStringName"];
connectionString = ConfigurationManager.ConnectionStrings [cnxName].ConnectionString;
config.Remove ("connectionStringName");
applicationName = config ["applicationName"];
config.Remove ("applicationName");
base.Initialize (iname, config);
}
#region implemented abstract members of System.Web.Profile.ProfileProvider
public override int DeleteInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
{
throw new System.NotImplementedException ();
}
public override int DeleteProfiles (string[] usernames)
{
throw new System.NotImplementedException ();
}
public override int DeleteProfiles (ProfileInfoCollection profiles)
{
throw new System.NotImplementedException ();
}
public override ProfileInfoCollection FindInactiveProfilesByUserName (ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords)
{
throw new System.NotImplementedException ();
}
public override ProfileInfoCollection FindProfilesByUserName (ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
if (pageIndex < 0)
throw new ArgumentException ("pageIndex");
if (pageSize < 1)
throw new ArgumentException ("pageSize");
long lowerBound = (long)pageIndex * pageSize;
long upperBound = lowerBound + pageSize - 1;
if (upperBound > Int32.MaxValue)
throw new ArgumentException ("lowerBound + pageSize*pageIndex -1 > Int32.MaxValue");
ProfileInfoCollection c = new ProfileInfoCollection ();
totalRecords = 0;
using (NpgsqlConnection cnx = new NpgsqlConnection (connectionString)) {
using (NpgsqlCommand cmd = cnx.CreateCommand ()) {
cmd.CommandText = "select username, uniqueid, lastactivitydate, lastupdateddate, isanonymous from profiles where username like @username and applicationname = @appname";
cmd.Parameters.Add ("@username", usernameToMatch);
cmd.Parameters.Add ("@appname", applicationName);
cnx.Open ();
using (NpgsqlDataReader r = cmd.ExecuteReader ()) {
if (r.HasRows) {
while (r.Read ()) {
if (totalRecords >= lowerBound && totalRecords <= upperBound) {
object o = r.GetValue (r.GetOrdinal ("isanonymous"));
bool isanon = o is DBNull ? true : (bool) o;
o = r.GetValue (r.GetOrdinal ("lastactivitydate"));
DateTime lact = o is DBNull ? new DateTime() : (DateTime) o;
o = r.GetValue (r.GetOrdinal ("lastupdateddate"));
DateTime lupd = o is DBNull ? new DateTime() : (DateTime) o;
ProfileInfo pi =
new ProfileInfo (
r.GetString (r.GetOrdinal ("username")),
isanon,
lact,
lupd,
0);
c.Add (pi);
totalRecords++;
}
}
}
}
}
}
return c;
}
public override ProfileInfoCollection GetAllInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords)
{
throw new System.NotImplementedException ();
}
public override ProfileInfoCollection GetAllProfiles (ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords)
{
throw new System.NotImplementedException ();
}
public override int GetNumberOfInactiveProfiles (ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
{
throw new System.NotImplementedException ();
}
#endregion
#region implemented abstract members of System.Configuration.SettingsProvider
public override SettingsPropertyValueCollection GetPropertyValues (SettingsContext context, SettingsPropertyCollection collection)
{
SettingsPropertyValueCollection c = new SettingsPropertyValueCollection ();
if (collection == null || collection.Count < 1 || context == null)
return c;
string username = (string)context ["UserName"];
if (String.IsNullOrEmpty (username))
return c;
using (NpgsqlConnection cnx = new NpgsqlConnection (connectionString))
using (NpgsqlCommand cmd = cnx.CreateCommand ()) {
cmd.CommandText = "SELECT * from profiledata,profiles where " +
"profiledata.uniqueid = profiles.uniqueid " +
"and profiles.username = @username " +
"and profiles.applicationname = @appname";
cmd.Parameters.Add ("@username", username);
cmd.Parameters.Add ("@appname", applicationName);
cnx.Open ();
using (NpgsqlDataReader r = cmd.ExecuteReader (
System.Data.CommandBehavior.CloseConnection | System.Data.CommandBehavior.SingleRow)) {
if (r.Read ()) {
foreach (SettingsProperty p in collection) {
SettingsPropertyValue v = new SettingsPropertyValue (p);
int o = r.GetOrdinal (p.Name.ToLower ());
v.PropertyValue = r.GetValue (o);
c.Add (v);
}
} else {
foreach (SettingsProperty p in collection) {
SettingsPropertyValue v = new SettingsPropertyValue (p);
v.PropertyValue = null;
c.Add (v);
}
}
}
}
return c;
}
public override void SetPropertyValues (SettingsContext context, SettingsPropertyValueCollection collection)
{
// get the unique id of the profile
if (collection == null)
return;
long puid = 0;
string username = (string)context ["UserName"];
using (NpgsqlConnection cnx = new NpgsqlConnection (connectionString)) {
cnx.Open ();
using (NpgsqlCommand cmdpi = cnx.CreateCommand ()) {
cmdpi.CommandText = "select count(uniqueid) " +
"from profiles where username = @username " +
"and applicationname = @appname";
cmdpi.Parameters.Add ("@username", username);
cmdpi.Parameters.Add ("@appname", applicationName);
long c = (long)cmdpi.ExecuteScalar ();
if (c == 0) {
cmdpi.CommandText = "insert into profiles (username,applicationname) " +
"values ( @username, @appname ) " +
"returning uniqueid";
puid = (long)cmdpi.ExecuteScalar ();
// TODO spec: profiledata insertion <=> profile insertion
// => BAD DESIGN
//
using (NpgsqlCommand cmdpdins = cnx.CreateCommand ()) {
cmdpdins.CommandText = "insert into profiledata (uniqueid) values (@puid)";
cmdpdins.Parameters.Add ("@puid", puid);
cmdpdins.ExecuteNonQuery ();
}
} else {
cmdpi.CommandText = "select uniqueid from profiles where username = @username " +
"and applicationname = @appname";
puid = (long)cmdpi.ExecuteScalar ();
}
}
foreach (SettingsPropertyValue s in collection) {
if (s.UsingDefaultValue) {
//TODO Drop the property in the profile
} else {
// update the property value
// TODO update to null values (included to avoid Not Implemented columns in profiledata
if (s.PropertyValue != null) {
using (NpgsqlCommand cmd = cnx.CreateCommand ()) {
cmd.CommandText = string.Format (
"update profiledata " +
"set {0} = @val " +
"where uniqueid = @puid ",
s.Name
);
cmd.Parameters.Add ("@puid", puid);
cmd.Parameters.Add ("@val", s.PropertyValue);
cmd.ExecuteNonQuery ();
}
}
}
}
}
}
public override string ApplicationName {
get {
return applicationName;
}
set {
applicationName = value;
}
}
#endregion
}
}

@ -0,0 +1,364 @@
using System;
using System.Web.Security;
using System.Configuration.Provider;
using System.Configuration;
using Npgsql;
using System.Collections.Generic;
/*
*
CREATE TABLE roles
(
rolename character varying(255) NOT NULL,
applicationname character varying(255) NOT NULL,
comment character varying(255) NOT NULL,
CONSTRAINT roles_pkey PRIMARY KEY (rolename , applicationname )
)
WITH (
OIDS=FALSE
);
CREATE TABLE usersroles
(
applicationname character varying(255) NOT NULL,
rolename character varying(255) NOT NULL,
username character varying(255) NOT NULL,
CONSTRAINT attrroles_pkey PRIMARY KEY (applicationname , rolename , username ),
CONSTRAINT usersroles_fk_role FOREIGN KEY (applicationname, rolename)
REFERENCES roles (applicationname, rolename) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT usersroles_fk_user FOREIGN KEY (applicationname, username)
REFERENCES users (applicationname, username) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);
*/
using System.Linq;
namespace Npgsql.Web
{
public class NpgsqlRoleProvider: RoleProvider
{
protected string name = "NpgsqlRoleProvider";
protected string connectionStringName = "pgProvider";
protected string applicationName = "/";
protected string connectionString = string.Empty;
public override void Initialize (string iname, System.Collections.Specialized.NameValueCollection config)
{
try {
name = iname ?? config ["name"];
connectionStringName = config ["connectionStringName"] ?? connectionStringName;
applicationName = config ["applicationName"] ?? applicationName;
if (applicationName.Length > 250)
throw new ProviderException ("The maximum length for an application name is 250 characters.");
var cs = ConfigurationManager.ConnectionStrings [connectionStringName];
if (cs == null || string.IsNullOrEmpty (cs.ConnectionString)) {
throw new ProviderException (
string.Format ("The role provider connection string, '{0}', is not defined.", connectionStringName));
}
connectionString = ConfigurationManager.ConnectionStrings [connectionStringName].ConnectionString;
if (string.IsNullOrEmpty (connectionString))
throw new ConfigurationErrorsException (
string.Format (
"The connection string for the given name ({0})" +
"must be specified in the <connectionStrings>" +
"configuration bloc. Aborting.", connectionStringName)
);
} catch (Exception ex) {
var message = "Error initializing the role configuration settings";
throw new ProviderException (message, ex);
}
}
public override void AddUsersToRoles (string[] usernames, string[] roleNames)
{
if (usernames.Any (x => x == null) || roleNames.Any (x => x == null)) {
throw new ArgumentNullException ();
}
if (usernames.Any (x => x.Trim () == string.Empty) || (roleNames.Any (x => x.Trim () == string.Empty))) {
throw new ArgumentException ("One or more of the supplied usernames or role names are empty.");
}
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "insert into usersroles (applicationname, username, rolename) values (@appname,@user,@role)";
comm.Parameters.Add ("appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
NpgsqlParameter pu = comm.Parameters.Add ("user", NpgsqlTypes.NpgsqlDbType.Varchar, 250);
NpgsqlParameter pr = comm.Parameters.Add ("role", NpgsqlTypes.NpgsqlDbType.Varchar, 250);
foreach (string u in usernames) {
pu.Value = u;
foreach (string r in roleNames) {
pr.Value = r;
comm.ExecuteNonQuery ();
}
}
}
}
}
public override string ApplicationName {
get {
return applicationName;
}
set {
applicationName = value;
}
}
public override void CreateRole (string roleName)
{
if (roleName == null)
throw new ArgumentNullException ();
if (roleName.Trim () == string.Empty)
throw new ArgumentException ("A role name cannot be empty.");
if (roleName.Contains (","))
throw new ArgumentException ("A role name cannot contain commas. Blame Microsoft for that rule!");
if (roleName.Length > 250)
throw new ArgumentException ("The maximum length for a Role name is 250 characters.");
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "insert into roles (rolename, applicationname, comment) values (@rolename, @appname, @comment)";
comm.Parameters.Add ("@rolename", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = roleName;
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
comm.Parameters.Add ("@comment", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = roleName;
comm.ExecuteNonQuery ();
}
}
}
public override bool DeleteRole (string roleName, bool throwOnPopulatedRole)
{
if (roleName == null)
throw new ArgumentNullException ();
if (roleName.Trim () == string.Empty)
throw new ArgumentException ("The specified role name cannot be empty.");
if (throwOnPopulatedRole)
if (FindUsersInRole (roleName, "").Count () > 0)
throw new ProviderException (
string.Format ("The role {0} is populated, we cannot delete it.", roleName));
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "delete from roles where rolename = @rolename and applicationname = @appname";
comm.Parameters.Add ("@rolename", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = roleName;
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
comm.Parameters.Add ("@comment", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = roleName;
comm.ExecuteNonQuery ();
}
}
return true;
}
public override string[] FindUsersInRole (string roleName, string usernameToMatch)
{
return GetUsersInRole (roleName, usernameToMatch);
}
protected string[] GetUsersInRole (string rolename, string usernameToMatch)
{
if (rolename == null)
throw new ArgumentNullException ();
if (rolename == string.Empty)
throw new ProviderException ("Cannot look for blank role names.");
usernameToMatch = usernameToMatch ?? string.Empty;
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "select username from usersroles where applicationname = @appname " +
"and rolename = @rolename and username like @username";
comm.Parameters.Add ("@rolename", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = rolename;
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
comm.Parameters.Add ("@username", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = usernameToMatch;
using (var reader = comm.ExecuteReader()) {
var r = new List<string> ();
var usernameColumn = reader.GetOrdinal ("username");
while (reader.Read()) {
r.Add (reader.GetString (usernameColumn));
}
return r.ToArray ();
}
}
}
}
public override string[] GetAllRoles ()
{
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "select rolename from roles where applicationname = @appname";
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
using (var reader = comm.ExecuteReader()) {
var r = new List<string> ();
var rolenameColumn = reader.GetOrdinal ("rolename");
while (reader.Read()) {
r.Add (reader.GetString (rolenameColumn));
}
return r.ToArray ();
}
}
}
}
public override string[] GetRolesForUser (string username)
{
if (username == null)
throw new ArgumentNullException ();
if (username.Trim () == string.Empty)
throw new ArgumentException ("The specified username cannot be blank.");
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "select rolename from usersroles where applicationname = @appname and username = @username";
comm.Parameters.Add ("@username", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = username;
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
using (var reader = comm.ExecuteReader()) {
var r = new List<string> ();
var rolenameColumn = reader.GetOrdinal ("rolename");
while (reader.Read()) {
r.Add (reader.GetString (rolenameColumn));
}
return r.ToArray ();
}
}
}
}
public override string[] GetUsersInRole (string roleName)
{
if (string.IsNullOrEmpty (roleName))
throw new ArgumentException ("The specified role name cannot be blank or null");
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
//
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "select username from usersroles where applicationname = @appname " +
"and rolename = @rolename";
comm.Parameters.Add ("@rolename", NpgsqlTypes.NpgsqlDbType.Varchar, 255).Value = roleName;
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 255).Value = applicationName;
using (var reader = comm.ExecuteReader()) {
var r = new List<string> ();
var usernameColumn = reader.GetOrdinal ("username");
while (reader.Read()) {
r.Add (reader.GetString (usernameColumn));
}
return r.ToArray ();
}
}
}
}
public override bool IsUserInRole (string username, string roleName)
{
if (username == null || roleName == null)
throw new ArgumentNullException ();
if (username.Trim () == string.Empty)
throw new ArgumentException ("The specified username cannot be blank.");
if (roleName.Trim () == string.Empty)
throw new ArgumentException ("The specified role name cannot be blank.");
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
//
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "select count(*)>0 from usersroles where applicationname = @appname " +
"and username = @username and rolename = @rolename";
comm.Parameters.Add ("@username", username);
comm.Parameters.Add ("@rolename", roleName);
comm.Parameters.Add ("@appname", applicationName);
var retval = (bool)comm.ExecuteScalar ();
return retval;
}
}
}
public override void RemoveUsersFromRoles (string[] usernames, string[] roleNames)
{
if (usernames.Any (x => x == null) || roleNames.Any (x => x == null)) {
throw new ArgumentNullException ();
}
if (usernames.Any (x => x.Trim () == string.Empty) || (roleNames.Any (x => x.Trim () == string.Empty))) {
throw new ArgumentException ("One or more of the supplied usernames or role names are empty.");
}
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = conn.CreateCommand()) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "delete from usersroles where applicationname = @appname and " +
"username = @username and rolename = @rolename";
NpgsqlParameter pu = comm.Parameters.Add ("@username", NpgsqlTypes.NpgsqlDbType.Varchar, 250);
NpgsqlParameter pr = comm.Parameters.Add ("@rolename", NpgsqlTypes.NpgsqlDbType.Varchar, 250);
comm.Parameters.Add ("@appname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
foreach (string rolename in roleNames) {
pr.Value = rolename;
foreach (string username in usernames) {
pu.Value = username;
comm.ExecuteNonQuery ();
}
}
}
}
}
public override bool RoleExists (string roleName)
{
using (var conn = new NpgsqlConnection(connectionString)) {
conn.Open ();
using (var comm = new NpgsqlCommand("role_exists", conn)) {
comm.CommandType = System.Data.CommandType.Text;
comm.CommandText = "select Count(*)>0 from roles where applicationname = @applicationname and rolename = @rolename";
comm.Parameters.Add ("@rolename", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = roleName;
comm.Parameters.Add ("@applicationname", NpgsqlTypes.NpgsqlDbType.Varchar, 250).Value = applicationName;
var retval = (bool)comm.ExecuteScalar ();
return retval;
}
}
}
public override string Name {
get {
return name;
}
}
public override string Description {
get {
return "PostgreSQL ASP.Net Role Provider class";
}
}
}
}

@ -0,0 +1,28 @@
-- Table: profiledata
-- DROP TABLE profiledata;
CREATE TABLE profiledata
(
uniqueid integer,
zipcode character varying(10),
cityandstate character varying(255),
avatar bytea,
CONSTRAINT fkprofiles2 FOREIGN KEY (uniqueid)
REFERENCES profiles (uniqueid) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);
-- Index: fki_fkprofiles2
-- DROP INDEX fki_fkprofiles2;
CREATE INDEX fki_fkprofiles2
ON profiledata
USING btree
(uniqueid );

@ -0,0 +1,18 @@
-- Table: roles
-- DROP TABLE roles;
CREATE TABLE roles
(
rolename character varying(255) NOT NULL,
applicationname character varying(255) NOT NULL,
comment character varying(255) NOT NULL,
CONSTRAINT roles_pkey PRIMARY KEY (rolename , applicationname )
)
WITH (
OIDS=FALSE
);
COMMENT ON TABLE roles
IS 'Web application roles';

@ -0,0 +1,16 @@
-- Table: stocksymbols
-- DROP TABLE stocksymbols;
CREATE TABLE stocksymbols
(
uniqueid integer,
stocksymbol character varying(10),
CONSTRAINT fkprofiles1 FOREIGN KEY (uniqueid)
REFERENCES profiles (uniqueid) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);

@ -0,0 +1,21 @@
-- Table: usersroles
-- DROP TABLE usersroles;
CREATE TABLE usersroles
(
applicationname character varying(255) NOT NULL,
rolename character varying(255) NOT NULL,
username character varying(255) NOT NULL,
CONSTRAINT attrroles_pkey PRIMARY KEY (applicationname , rolename , username ),
CONSTRAINT usersroles_fk_role FOREIGN KEY (applicationname, rolename)
REFERENCES roles (applicationname, rolename) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT usersroles_fk_user FOREIGN KEY (applicationname, username)
REFERENCES users (applicationname, username) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);

@ -0,0 +1,19 @@
-- Table: profiles
-- DROP TABLE profiles;
CREATE TABLE profiles
(
uniqueid bigserial NOT NULL,
username character varying(255) NOT NULL,
applicationname character varying(255) NOT NULL,
isanonymous boolean,
lastactivitydate timestamp with time zone,
lastupdateddate timestamp with time zone,
CONSTRAINT profiles_pkey PRIMARY KEY (uniqueid ),
CONSTRAINT pkprofiles UNIQUE (username , applicationname )
)
WITH (
OIDS=FALSE
);

@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("SalesCatalog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("paul")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,45 @@
using System;
using System.Configuration;
using System.Reflection;
using System.Collections.Specialized;
using SalesCatalog.Configuration;
namespace SalesCatalog
{
/// <summary>
/// Catalog helper.
/// Used by the catalog manager to get the catalog provider from the configuration.
/// </summary>
public static class CatalogHelper
{
public static CatalogProvider GetProvider ()
{
CatalogProvidersConfigurationSection config = ConfigurationManager.GetSection ("system.web/catalog") as CatalogProvidersConfigurationSection;
if (config == null)
throw new ConfigurationErrorsException("The configuration bloc for the catalog provider was not found");
CatalogProviderConfigurationElement celt =
config.Providers.GetElement (config.DefaultProvider);
if (celt == null)
throw new ConfigurationErrorsException("The default catalog provider was not found");
Type catprtype = Type.GetType (celt.Type);
if (catprtype == null)
throw new Exception (
string.Format("The catalog provider type ({0}) could not be found",celt.Type));
ConstructorInfo ci = catprtype.GetConstructor (Type.EmptyTypes);
if (ci==null)
throw new Exception (
string.Format("The catalog provider type ({0}) doesn't contain public constructor with empty parameter list",celt.Type));
CatalogProvider cp = ci.Invoke (Type.EmptyTypes) as CatalogProvider;
NameValueCollection c = new NameValueCollection ();
c.Add ("name", celt.Name);
c.Add ("type", celt.Type);
c.Add ("connection", celt.Connection);
c.Add ("description", celt.Description);
c.Add ("applicationName", celt.ApplicationName);
cp.Initialize (celt.Name, c);
return cp;
}
}
}

@ -0,0 +1,19 @@
using System;
using SalesCatalog.Model;
namespace SalesCatalog
{
/// <summary>
/// Catalog manager.
/// Use this class to retreive the catalog or its elements
/// </summary>
public static class CatalogManager
{
public static Catalog GetCatalog ()
{
CatalogProvider p = CatalogHelper.GetProvider ();
return p.GetCatalog ();
}
}
}

@ -0,0 +1,16 @@
using System;
using System.Configuration.Provider;
using SalesCatalog.Model;
namespace SalesCatalog
{
/// <summary>
/// Catalog provider.<br/>
/// Abstract class, inherited to implement a catalog provider.
/// </summary>
public abstract class CatalogProvider: ProviderBase
{
public abstract Catalog GetCatalog ();
}
}

@ -0,0 +1,39 @@
using System;
using System.Configuration;
namespace SalesCatalog.Configuration
{
public class CatalogProviderConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey=true)]
public string Name {
get { return (string)this ["name"]; }
set { this ["name"] = value; }
}
[ConfigurationProperty("type", IsRequired = true)]
public string Type {
get { return (string)this ["type"]; }
set { this ["type"] = value; }
}
[ConfigurationProperty("connection")]
public string Connection {
get { return (string)this ["connection"]; }
set { this ["connection"] = value; }
}
[ConfigurationProperty("description")]
public string Description {
get { return (string)this ["description"]; }
set { this ["description"] = value; }
}
[ConfigurationProperty("applicationName")]
public string ApplicationName {
get { return (string)this ["applicationName"]; }
set { this ["applicationName"] = value; }
}
}
}

@ -0,0 +1,26 @@
using System;
using System.Configuration;
using System.ComponentModel;
namespace SalesCatalog.Configuration
{
public class CatalogProvidersConfigurationCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement ()
{
return new CatalogProviderConfigurationElement();
}
protected override object GetElementKey (ConfigurationElement element)
{
return ((CatalogProviderConfigurationElement) element).Name;
}
public CatalogProviderConfigurationElement GetElement (string name)
{
return this.BaseGet(name) as CatalogProviderConfigurationElement;
}
}
}

@ -0,0 +1,26 @@
using System;
using System.Configuration;
using System.ComponentModel;
namespace SalesCatalog.Configuration
{
public class CatalogProvidersConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("defaultProvider")]
public string DefaultProvider {
get { return (string)base ["defaultProvider"]; }
set { base ["defaultProvider"] = value; }
}
[ConfigurationProperty("providers")]
[ConfigurationCollection(typeof(CatalogProvidersConfigurationCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public CatalogProvidersConfigurationCollection Providers{
get { return (CatalogProvidersConfigurationCollection) base ["providers"]; }
set { base ["providers"] = value; }
}
}
}

@ -0,0 +1,37 @@
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
namespace SalesCatalog.Model
{
public class Brand
{
public Brand ()
{
}
[Required]
public string Name { get; set; }
public string Slogan { get; set; }
public ProductImage Logo { get; set; }
public ProductCategory[] Categories { get; set; }
/// <summary>
/// Gets or sets the default form.
/// </summary>
/// <value>The default form.</value>
public SaleForm DefaultForm { get; set; }
public ProductCategory GetProductCategory(string reference)
{
return Array.Find<ProductCategory>(Categories, c => c.Reference == reference);
}
public ProductCategory GetProductCategoryByName(string catName)
{
return Array.Find<ProductCategory>(Categories, c => c.Name == catName);
}
}
}

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
namespace SalesCatalog.Model
{
/// <summary>
/// Catalog.
/// </summary>
public class Catalog {
/// <summary>
/// Gets or sets the brands.
/// </summary>
/// <value>The brands.</value>
public Brand[] Brands { get; set; }
public Brand GetBrand(string brandName)
{
return Array.Find<Brand>(Brands, b => b.Name == brandName);
}
public Brand AddBrand(string brandName,string slogan=null, ProductImage logo=null)
{
Brand[] oldbrs = (Brand[]) Brands.Clone ();
int oldl = Brands.Length;
Array.Resize<Brand>(ref oldbrs,oldl+1);
Brand b = new Brand ();
b.Name=brandName;
b.Slogan = slogan;
b.Logo = logo;
oldbrs [oldl] = b;
Brands=oldbrs;
return b;
}
public bool RemoveBrand(string brandName)
{
Brand b = this.GetBrand (brandName);
if (b == null)
return false;
//assert(Brands.Length>0);
List<Brand> nb = new List<Brand> (Brands);
nb.Remove (b);
Brands = nb.ToArray ();
return true;
}
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}

@ -0,0 +1,18 @@
using System;
namespace SalesCatalog.Model
{
public class CheckBox : FormInput
{
public CheckBox ()
{
}
public bool Value { get; set; }
public override string ToHtml ()
{
return string.Format ("<input type=\"checkbox\" id=\"{0}\" name=\"{1}\" {2}/>", Id,Name,Value?"checked":"");
}
}
}

@ -0,0 +1,9 @@
using System;
namespace SalesCatalog.Model
{
public abstract class Currency: Unit
{
}
}

@ -0,0 +1,34 @@
using System;
namespace SalesCatalog.Model
{
public class Euro : Currency
{
public Euro ()
{
}
public override string Name {
get {
return "Euro";
}
}
public override string Description {
get {
return "European currency";
}
}
public override bool MayConvertTo (Unit other)
{
return other.GetType().IsSubclassOf(typeof (Currency));
}
public override object ConvertTo (Unit dest, object value)
{
throw new NotImplementedException();
}
}
}

@ -0,0 +1,18 @@
using System;
namespace SalesCatalog.Model
{
public class FilesInput : FormInput
{
public FilesInput ()
{
}
public override string ToHtml ()
{
return string.Format ("<input type=\"file\" id=\"{0}\" name=\"{0}\"/>", Id);
}
}
}

@ -0,0 +1,10 @@
using System;
namespace SalesCatalog.Model
{
public abstract class FormElement
{
public abstract string ToHtml ();
}
}

@ -0,0 +1,19 @@
using System;
namespace SalesCatalog.Model
{
public abstract class FormInput: FormElement
{
/// <summary>
/// Gets or sets the identifier, unique in its Form.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public string Id { get; set; }
private string name=null;
public string Name { get { return name == null ? Id : name; } set { name = value; } }
}
}

@ -0,0 +1,18 @@
using System;
namespace SalesCatalog.Model
{
public class Label:FormElement
{
public Label ()
{
}
string Text { get; set; }
string For { get; set ; }
public override string ToHtml ()
{
return string.Format ("<label for=\"{0}\">{1}</label>", For, Text);
}
}
}

@ -0,0 +1,15 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace SalesCatalog.Model
{
public class Link:Label
{
public Link ()
{
}
[Required]
public string Ref { get; set; }
}
}

@ -0,0 +1,13 @@
using System;
namespace SalesCatalog.Model
{
public class Note:Text
{
public override string ToHtml ()
{
return string.Format("<quote>{0}</quote>",Val);
}
}
}

@ -0,0 +1,19 @@
using System;
namespace SalesCatalog.Model
{
public class Option : FormElement
{
public Option ()
{
}
public string Value { get; set; }
public string Text { get; set; }
public override string ToHtml ()
{
return string.Format ("<option value=\"{0}\">{1}</option>\n",Value,Text);
}
}
}

@ -0,0 +1,15 @@
using System;
namespace SalesCatalog.Model
{
public class Period
{
public Period ()
{
}
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}

@ -0,0 +1,27 @@
using System;
namespace SalesCatalog.Model
{
public class PhysicalProduct : Product
{
public PhysicalProduct ()
{
}
public Price UnitaryPrice { get; set; }
#region implemented abstract members of SalesCatalog.Model.Product
public override string[] GetSalesConditions ()
{
return new string [] { string.Format(
"Prix unitaire : {0} {1}",
UnitaryPrice.Quantity.ToString(),
UnitaryPrice.Unit.Name) };
}
#endregion
public override string ToString ()
{
return string.Format ("[PhysicalProduct: UnitaryPrice={0}]", UnitaryPrice);
}
}
}

@ -0,0 +1,36 @@
using System;
namespace SalesCatalog.Model
{
public class Price: Scalar
{
public Price ()
{
}
decimal quantity;
#region implemented abstract members of SalesCatalog.Value
public override object Quantity {
get {
return quantity;
}
set {
quantity = (decimal) value;
}
}
Currency curr;
public override SalesCatalog.Model.Unit Unit {
get {
return curr;
}
set {
curr = (Currency)value;
}
}
#endregion
}
}

@ -0,0 +1,37 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace SalesCatalog.Model
{
/// <summary>
/// Product.
/// Crucial object in the catalog,
/// being at each origin of form display
/// its properties may be used to fill some form input values or other form element.
/// <c>in text values, within {} ex: {Name} : {Price} ({stockStatus}) ($description) </c>.
/// </summary>
public abstract class Product
{
/// <summary>
/// Gets or sets the product name.
/// </summary>
/// <value>The name.</value>
[Required]
[StringLength(1024)]
public string Name { get; set; }
/// <summary>
/// Gets or sets the product description.
/// </summary>
/// <value>The description.</value>
public string Description { get; set; }
public ProductImage[] Images { get; set; }
public SaleForm CommandForm { get; set; }
[Required]
[StringLength(255)]
public string Reference { get; set; }
public Period CommandValidityDates { get; set; }
public abstract string[] GetSalesConditions();
}
}

@ -0,0 +1,23 @@
using System;
namespace SalesCatalog.Model
{
public class ProductCategory
{
public ProductCategory ()
{
}
public string Name { get; set; }
public string Reference { get; set; }
public Product[] Products { get; set; }
public Product GetProductByName (string productName)
{
return Array.Find<Product> (Products, p => p.Name == productName);
}
public Product GetProduct (string reference)
{
return Array.Find<Product> (Products, p => p.Reference == reference);
}
}
}

@ -0,0 +1,23 @@
using System;
namespace SalesCatalog.Model
{
public class ProductImage: FormElement
{
#region implemented abstract members of FormElement
public override string ToHtml ()
{
return string.Format ("<img src=\"\" alt=\"\"/>", Src, Alt);
}
#endregion
public ProductImage ()
{
}
public string Src { get; set; }
public string Alt { get; set; }
}
}

@ -0,0 +1,17 @@
using System;
namespace SalesCatalog.Model
{
public class RadioButton:FormInput
{
public RadioButton ()
{
}
public string Choice { get; set; }
public override string ToHtml ()
{
return string.Format ("<input type=\"radio\" id=\"{0}\" name=\"{1}\" value=\"{2}\"/><label for=\"{0}\">{2}</label>", Id,Name,Choice);
}
}
}

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
namespace SalesCatalog.Model
{
public class SaleForm
{
public SaleForm ()
{
}
public string Action {
get;
set;
}
public FormElement[] Items { get; set; }
}
}

@ -0,0 +1,14 @@
using System;
namespace SalesCatalog.Model
{
public abstract class Scalar
{
public Scalar ()
{
}
public abstract object Quantity { get; set; }
public abstract Unit Unit{ get; set; }
}
}

@ -0,0 +1,20 @@
using System;
using System.Text;
using System.Web.Mvc;
namespace SalesCatalog.Model
{
public class SelectInput: FormInput
{
public Option[] Items;
public int SelectedIndex;
public override string ToHtml ()
{
StringBuilder sb = new StringBuilder ();
foreach (Option opt in Items)
sb.Append (opt.ToHtml());
return string.Format ("<select id=\"{0}\" name=\"{1}\">{2}</select>\n", Id,Name,sb.ToString());
}
}
}

@ -0,0 +1,23 @@
using System;
namespace SalesCatalog.Model
{
public class SelectItem
{
public SelectItem(string t)
{
Value = t;
}
public string Value { get; set; }
public static implicit operator string(SelectItem t)
{
return t.Value;
}
public static implicit operator SelectItem(string t)
{
return new SelectItem(t);
}
}
}

@ -0,0 +1,28 @@
using System;
namespace SalesCatalog.Model
{
public class Service : Product
{
public Service ()
{
}
public Price HourPrice { get; set; }
#region implemented abstract members of SalesCatalog.Model.Product
public override string [] GetSalesConditions ()
{
return new string [] { string.Format(
"Prix horaire de la prestation : {0} {1}",
HourPrice.Quantity.ToString(),
HourPrice.Unit.Name) } ;
}
#endregion
public override string ToString ()
{
return string.Format ("[Service: HourPrice={0}]", HourPrice);
}
}
}

@ -0,0 +1,11 @@
using System;
namespace SalesCatalog.Model
{
public enum StockStatus
{
NoStock,
InStock
}
}

@ -0,0 +1,18 @@
using System;
namespace SalesCatalog.Model
{
public class Text: FormElement
{
public string Val {
get;
set;
}
public override string ToHtml ()
{
return Val;
}
}
}

@ -0,0 +1,46 @@
using System;
namespace SalesCatalog.Model
{
public class TextInput:FormInput
{
public TextInput ()
{
}
public TextInput (string txt)
{
text = txt;
}
string text = null;
public static implicit operator string(TextInput t)
{
return t.text;
}
public static implicit operator TextInput(string t)
{
return new TextInput(t);
}
public string DefaultValue {
get {
return text;
}
set {
text = (string) value;
}
}
private bool multiline = false;
public bool MultiLine { get { return multiline; } set { multiline = value; } }
public override string ToHtml ()
{
return MultiLine?
string.Format ("<textarea id=\"{0}\" name=\"{1}\">{2}</textarea>", Id,Name,DefaultValue)
: string.Format ("<input type=\"text\" id=\"{0}\" name=\"{1}\" value=\"{2}\"/>", Id,Name,DefaultValue);
}
}
}

@ -0,0 +1,13 @@
using System;
namespace SalesCatalog.Model
{
public abstract class Unit
{
public abstract string Name { get; }
public abstract string Description { get; }
public abstract object ConvertTo (Unit dest, object value);
public abstract bool MayConvertTo (Unit other);
}
}

@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{90BF2234-7252-4CD5-B2A4-17501B19279B}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>SalesCatalog</RootNamespace>
<AssemblyName>SalesCatalog</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="nunit.framework, Version=2.6.0.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<Private>False</Private>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Configuration\CatalogProviderConfigurationElement.cs" />
<Compile Include="Configuration\CatalogProvidersConfigurationSection.cs" />
<Compile Include="Configuration\CatalogProvidersConfigurationCollection.cs" />
<Compile Include="CatalogManager.cs" />
<Compile Include="Model\CheckBox.cs" />
<Compile Include="Model\Currency.cs" />
<Compile Include="Model\Euro.cs" />
<Compile Include="Model\FilesInput.cs" />
<Compile Include="Model\FormElement.cs" />
<Compile Include="Model\FormInput.cs" />
<Compile Include="Model\Label.cs" />
<Compile Include="Model\Link.cs" />
<Compile Include="Model\Price.cs" />
<Compile Include="Model\ProductCategory.cs" />
<Compile Include="Model\RadioButton.cs" />
<Compile Include="Model\SelectInput.cs" />
<Compile Include="Model\TextInput.cs" />
<Compile Include="Model\Unit.cs" />
<Compile Include="Model\Brand.cs" />
<Compile Include="CatalogProvider.cs" />
<Compile Include="XmlImplementation\XmlCatalog.cs" />
<Compile Include="CatalogHelper.cs" />
<Compile Include="Tests\TestCatalogInit.cs" />
<Compile Include="Model\Product.cs" />
<Compile Include="Model\Period.cs" />
<Compile Include="Model\Service.cs" />
<Compile Include="Model\PhysicalProduct.cs" />
<Compile Include="Model\Catalog.cs" />
<Compile Include="XmlImplementation\XmlCatalogProvider.cs" />
<Compile Include="Model\Text.cs" />
<Compile Include="Model\SelectItem.cs" />
<Compile Include="Model\StockStatus.cs" />
<Compile Include="Model\Scalar.cs" />
<Compile Include="Tests\TestBrands.cs" />
<Compile Include="Model\SaleForm.cs" />
<Compile Include="Model\ProductImage.cs" />
<Compile Include="Model\Option.cs" />
<Compile Include="Model\Note.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedFlat" ResourceNamePolicy="FileFormatDefault" />
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
<ItemGroup>
<None Include="catalog.xsd" />
</ItemGroup>
<ItemGroup>
<Folder Include="Model\" />
<Folder Include="XmlImplementation\" />
<Folder Include="Tests\" />
</ItemGroup>
</Project>

@ -0,0 +1,31 @@
using NUnit.Framework;
using System;
using SalesCatalog.Model;
namespace SalesCatalog.Tests
{
[TestFixture ()]
public class TestBrands
{
[Test ()]
public void TestCaseAddRemoveBrand ()
{
Catalog c = new Catalog ();
c.Brands = new Brand[0];
Brand b=c.AddBrand ("coko");
if (c.Brands.Length != 1)
throw new Exception ("Pas ajouté");
if (b == null)
throw new Exception ("Renvoyé null");
if (b.Name != "coko")
throw new Exception ("Pas le bon nom");
if (c.Brands [0] != b)
throw new Exception ("err index 0");
if (c.GetBrand ("coko") != b)
throw new Exception ("err get by name");
if (!c.RemoveBrand ("coko"))
throw new Exception ("Pas supprimé");
}
}
}

@ -0,0 +1,106 @@
using System;
using NUnit.Framework;
using SalesCatalog.XmlImplementation;
using SalesCatalog.Model;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
namespace SalesCatalog.Tests
{
[TestFixture()]
public class TestCatalogInit
{
[Test()]
public void TestSerDeserCat ()
{
Catalog cat = new XmlCatalog ();
Brand b = new Brand ();
b.Logo = new ProductImage ();
b.Logo.Src = "/images/dev.png";
b.Logo.Alt = "Dev";
b.Name = "Developpement à la carte";
b.Slogan = "Votre logiciel, efficace, sûr, et sur mesure";
ProductCategory si = new ProductCategory ();
si.Name = "Systèmes d'information et sites Web";
ProductCategory progiciel = new ProductCategory ();
progiciel.Name = "Progiciels";
b.Categories = new ProductCategory[]{ si, progiciel };
Service simaint = new Service ();
simaint.Name = "Maintenance logicielle";
simaint.Description = "Correction des bugs, évolution";
Service sidev = new Service ();
sidev.Name = "Développement logiciel";
sidev.Description = "Votre intranet, votre site Web, sur mesure, " +
"développé en cycles courts, et en étroite collaboration avec vous";
Service aubb = new Service ();
aubb.Name = "Audit de sécurité en black box";
aubb.Description = "Je recherche les failles de sécurité de votre SI ou site Web, depuis l'exterieur de " +
"votre système, sans avoir eu connaissance d'aucun élément sur l'architécture de votre " +
"système";
Service auwb = new Service ();
auwb.Name = "Audit de sécurité en white box";
auwb.Description = "Je me déplace chez vous, pour travailler à partir de votre code source, " +
"et isoler ses failles de sécurités";
si.Products = new Product[] { simaint, sidev, aubb, auwb };
Service maint = new Service ();
maint.Name = "Maintenance logicielle";
maint.Description = "Correction des bugs, évolution";
Service dev = new Service ();
dev.Name = "Développement logiciel";
dev.Description = "Votre progiciel, sur mesure, " +
"développé en cycles courts, et en étroite collaboration avec vous";
progiciel.Products = new Product[] { maint, dev };
SaleForm f = new SaleForm ();
f.Action = "/testAction";
TextInput ticat = new TextInput ("Choose a Title");
ticat.Id = "title" ;
ticat.MultiLine = true;
SelectInput selSize = new SelectInput ();
selSize.Id="size";
Option o1 = new Option ();
o1.Value = "1m"; o1.Text = "1 mois";
Option o2 = new Option ();
o2.Value = "2m"; o2.Text = "2 mois";
Option o3 = new Option ();
o3.Value = "6m"; o3.Text = "6 mois";
selSize.Items = new Option [] { o1, o2, o3 };
var txt1 = new SalesCatalog.Model.Text ();
var txt2 = new SalesCatalog.Model.Text ();
txt1.Val="Choose a title : ";
txt2.Val = "[br]Choose the size : ";
f.Items = new FormElement[] {txt1,ticat,txt2,selSize};
b.DefaultForm = f;
cat.Brands = new Brand[] { b };
b.Categories = new ProductCategory[] { si, progiciel };
XmlSerializer ser =
new XmlSerializer
(typeof(XmlCatalog),
new Type[]{typeof(Service),
typeof(PhysicalProduct),
typeof(Euro),
typeof(TextInput),
typeof(SalesCatalog.Model.Text),
typeof(TextInput),
typeof(SelectInput)
});
FileInfo fi = new FileInfo ("Catalog.xml");
if (fi.Exists)
fi.Delete ();
using (FileStream ws = fi.OpenWrite()) {
ser.Serialize (ws, cat);
}
using (FileStream rs = fi.OpenRead()) {
using (XmlTextReader rdr = new XmlTextReader(rs)) {
XmlCatalog copy = (XmlCatalog)ser.Deserialize (rdr);
if (copy.Brands == null) throw new Exception("Null brand array!");
if (copy.Brands.Length != cat.Brands.Length) throw new Exception("Not the same count of brands");
if (copy.Brands[0].DefaultForm.Action != cat.Brands[0].DefaultForm.Action) throw new Exception("not the same default form");
// ...
}
}
}
}
}

@ -0,0 +1,15 @@
using System;
using SalesCatalog.Model;
using System.Xml.Serialization;
namespace SalesCatalog.XmlImplementation
{
[XmlRoot]
public class XmlCatalog : Catalog
{
public XmlCatalog ()
{
}
}
}

@ -0,0 +1,55 @@
using System;
using System.Xml.Serialization;
using SalesCatalog.Model;
using System.Configuration;
using System.IO;
using System.Xml;
namespace SalesCatalog.XmlImplementation
{
public class XmlCatalogProvider: CatalogProvider
{
#region implemented abstract members of SalesCatalog.CatalogProvider
public override Catalog GetCatalog ()
{
// Assert fileName != null
FileInfo fi = new FileInfo (fileName);
if (fi.LastWriteTime > lastModification)
LoadCatalog ();
return catInstance;
}
protected XmlCatalog catInstance = null;
protected DateTime lastModification;
protected string fileName = null;
#endregion
public override void Initialize (string name, System.Collections.Specialized.NameValueCollection config)
{
fileName = config ["connection"];
LoadCatalog ();
}
private void LoadCatalog ()
{
FileInfo fi = new FileInfo (fileName);
if (!fi.Exists)
throw new Exception (
string.Format ("Le fichier Xml decrivant le catalogue n'existe pas ({0})", fi.FullName));
XmlSerializer xsr = new XmlSerializer (typeof(XmlCatalog),new Type[]{
typeof(Service),
typeof(PhysicalProduct),
typeof(Euro),
typeof(Text),
typeof(TextInput),
typeof(SelectInput)});
using (FileStream fs = fi.OpenRead()) {
catInstance = (XmlCatalog) xsr.Deserialize (fs);
}
fileName = fi.FullName;
lastModification = fi.LastWriteTime;
}
}
}

@ -0,0 +1,151 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Catalog" nillable="true" type="Catalog" />
<xs:complexType name="Catalog">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Brands" type="ArrayOfBrand" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ArrayOfBrand">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="Brand" nillable="true" type="Brand" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="Brand">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="Slogan" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="Url" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="Categories" type="ArrayOfProductCategory" />
<xs:element minOccurs="0" maxOccurs="1" name="DefaultForm" type="ArrayOfFormElement" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ArrayOfProductCategory">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="ProductCategory" nillable="true" type="ProductCategory" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ProductCategory">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Products" type="ArrayOfProduct" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ArrayOfProduct">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="Product" nillable="true" type="Product" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="Product" />
<xs:complexType name="ArrayOfFormElement">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="FormElement" nillable="true" type="FormElement" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="FormElement" />
<xs:element name="Brand" nillable="true" type="Brand" />
<xs:element name="Product" nillable="true" type="Product" />
<xs:element name="Currency" nillable="true" type="Currency" />
<xs:complexType name="Currency">
<xs:complexContent mixed="false">
<xs:extension base="Unit" />
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Unit" />
<xs:element name="ArrayOfFormElement" nillable="true" type="ArrayOfFormElement" />
<xs:element name="FormInput" nillable="true" type="FormInput" />
<xs:complexType name="FormInput">
<xs:complexContent mixed="false">
<xs:extension base="FormElement">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Id" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="Value" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:element name="TextInput" nillable="true" type="TextInput" />
<xs:complexType name="TextInput">
<xs:complexContent mixed="false">
<xs:extension base="FormElement" />
</xs:complexContent>
</xs:complexType>
<xs:element name="SelectInput" nillable="true" type="SelectInput" />
<xs:complexType name="SelectInput">
<xs:complexContent mixed="false">
<xs:extension base="FormElement" />
</xs:complexContent>
</xs:complexType>
<xs:element name="Label" nillable="true" type="Label" />
<xs:complexType name="Label">
<xs:complexContent mixed="false">
<xs:extension base="FormElement" />
</xs:complexContent>
</xs:complexType>
<xs:element name="Comment" nillable="true" type="Comment" />
<xs:complexType name="Comment">
<xs:complexContent mixed="false">
<xs:extension base="FormElement" />
</xs:complexContent>
</xs:complexType>
<xs:element name="CheckBox" nillable="true" type="CheckBox" />
<xs:complexType name="CheckBox">
<xs:complexContent mixed="false">
<xs:extension base="FormInput" />
</xs:complexContent>
</xs:complexType>
<xs:element name="RadioButton" nillable="true" type="RadioButton" />
<xs:complexType name="RadioButton">
<xs:complexContent mixed="false">
<xs:extension base="FormInput">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Choice" type="xs:string" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:element name="Link" nillable="true" type="Link" />
<xs:complexType name="Link">
<xs:complexContent mixed="false">
<xs:extension base="FormElement" />
</xs:complexContent>
</xs:complexType>
<xs:element name="FilesInput" nillable="true" type="FilesInput" />
<xs:complexType name="FilesInput">
<xs:complexContent mixed="false">
<xs:extension base="FormInput" />
</xs:complexContent>
</xs:complexType>
<xs:element name="FormElement" nillable="true" type="FormElement" />
<xs:element name="Unit" nillable="true" type="Unit" />
<xs:element name="Value" nillable="true" type="Value" />
<xs:complexType name="Value">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Quantity" />
<xs:element minOccurs="0" maxOccurs="1" name="Unit" type="Unit" />
</xs:sequence>
</xs:complexType>
<xs:element name="Image" nillable="true" type="Image" />
<xs:complexType name="Image">
<xs:complexContent mixed="false">
<xs:extension base="FormElement">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Src" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="Alt" type="xs:string" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:element name="ProductCategory" nillable="true" type="ProductCategory" />
<xs:element name="Price" nillable="true" type="Price" />
<xs:complexType name="Price">
<xs:complexContent mixed="false">
<xs:extension base="Value" />
</xs:complexContent>
</xs:complexType>
<xs:element name="Euro" nillable="true" type="Euro" />
<xs:complexType name="Euro">
<xs:complexContent mixed="false">
<xs:extension base="Currency" />
</xs:complexContent>
</xs:complexType>
</xs:schema>

@ -0,0 +1,23 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web.UI;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("WebControls")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Paul Schneider")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: TagPrefix("Yavsc.WebControls", "yavsc")]

@ -0,0 +1,116 @@
using System;
using System.Web;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace Yavsc.WebControls
{
[
AspNetHostingPermission (SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission (SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
ParseChildren (true, "Action"),
DefaultProperty ("Action"),
ToolboxData ("<{0}:ResultPages runat=\"server\"> </{0}:ResultPages>")
]
public class ResultPages: WebControl
{
public ResultPages ()
{
}
[Bindable (true)]
[DefaultValue(10)]
public int ResultsPerPage {
get {
return (int)( ViewState["ResultsPerPage"]==null?10:ViewState["ResultsPerPage"]);
}
set {
ViewState["ResultsPerPage"]=value;
}
}
[Bindable (true)]
[DefaultValue(0)]
public int ResultCount {
get {
return (int)( ViewState["ResultCount"]==null?0:ViewState["ResultCount"]);
}
set {
ViewState["ResultCount"] = value;
}
}
[Bindable (true)]
[DefaultValue("Pages:")]
[Localizable(true)]
public string Text {
get {
string s = (string)ViewState["Text"];
return (s == null) ? "Pages:" : s;
}
set {
ViewState["Text"] = value;
}
}
[Bindable (true)]
[DefaultValue("")]
public string Action {
get {
string s = (string)ViewState["Action"];
return (s == null) ? String.Empty : s;
}
set {
ViewState["Action"] = value;
}
}
[Bindable (true)]
[DefaultValue(0)]
public int CurrentPage {
get {
int i = (int)(ViewState["CurrentPage"]==null?0:ViewState["CurrentPage"]);
return i;
}
set {
ViewState["CurrentPage"] = value;
}
}
protected override void RenderContents (HtmlTextWriter writer)
{
if (ResultCount > 0) {
writer.WriteEncodedText (Text);
int pageCount = ((ResultCount-1) / ResultsPerPage) + 1;
for (int pi = (CurrentPage < 5) ? 0 : CurrentPage - 5; pi < pageCount && pi < CurrentPage + 5; pi++) {
if (CurrentPage == pi)
writer.RenderBeginTag ("b");
else {
writer.AddAttribute (HtmlTextWriterAttribute.Href,
string.Format (Action, pi));
writer.RenderBeginTag ("a");
}
writer.Write (pi);
writer.RenderEndTag ();
writer.Write ("&nbsp;");
}
writer.Write ("("+ResultCount.ToString()+" resultat(s))");
} else {
writer.Write ("(Pas de resultat)");
}
}
}
}

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{59E1DF7B-FFA0-4DEB-B5F3-76EBD98D5356}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>WebControls</RootNamespace>
<AssemblyName>Yavsc.WebControls</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<Private>False</Private>
</Reference>
<Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<Private>False</Private>
</Reference>
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Abstractions" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ResultPages.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,148 @@
using System;
using Npgsql;
using NpgsqlTypes;
using System.Configuration;
using System.Collections.Specialized;
using yavscModel.WorkFlow;
namespace WorkFlowProvider
{
public class NpgsqlContentProvider: IContentProvider
{
public string Order (IWFCommand c)
{
throw new NotImplementedException ();
}
public IContent Get (string orderId)
{
throw new NotImplementedException ();
}
public void AddDevRessource (int prjId, string userName)
{
throw new NotImplementedException ();
}
public void AddPrjRessource(int prjId, string owner)
{
}
public void NewRelease (int projectId, string Version)
{
throw new NotImplementedException ();
}
string applicationName=null;
string cnxstr = null;
public NpgsqlContentProvider ()
{
Initialize("NpgsqlYavscContentProvider",ConfigurationManager.AppSettings);
}
public void Initialize (string name, NameValueCollection config)
{
cnxstr = ConfigurationManager.ConnectionStrings [config ["connectionStringName"]].ConnectionString;
applicationName = config["applicationName"] ?? "/";
}
NpgsqlConnection CreateConnection ()
{
return new NpgsqlConnection (cnxstr);
}
#region IDisposable implementation
public void Dispose ()
{
}
#endregion
#region IContentProvider implementation
public int NewTask (int projectId, string name, string desc)
{
throw new System.NotImplementedException ();
}
public void SetProjectName (int projectId, string name)
{
throw new System.NotImplementedException ();
}
public void SetProjectDesc (int projectId, string desc)
{
throw new System.NotImplementedException ();
}
public void SetTaskName (int taskId, string name)
{
throw new System.NotImplementedException ();
}
public void SetStartDate (int taskId, DateTime d)
{
throw new System.NotImplementedException ();
}
public void SetEndDate (int taskId, DateTime d)
{
throw new System.NotImplementedException ();
}
public void SetTaskDesc (int taskId, string desc)
{
throw new System.NotImplementedException ();
}
public void RemoveProject (int prjId)
{
using (var cnx = CreateConnection()) {
cnx.Open ();
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "delete from projets where id = @id";
cmd.Parameters.Add ("@id", prjId);
cmd.ExecuteNonQuery();
}
cnx.Close ();
}
}
public void RemoveTask (int taskId)
{
throw new System.NotImplementedException ();
}
public void SetManager (int projectId, string user)
{
throw new System.NotImplementedException ();
}
public void RemoveUser (string user)
{
throw new System.NotImplementedException ();
}
public int NewProject (string name, string desc, string ownerId)
{
int id = 0;
using (var cnx = CreateConnection()) {
cnx.Open ();
using (NpgsqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandText = "insert into projets (name,managerid,ApplicatonName,prdesc) values (@name,@mid,@appname,@pdesc)";
cmd.Parameters.Add ("@name", name);
cmd.Parameters.Add ("@mid", ownerId);
cmd.Parameters.Add ("@appname", applicationName);
cmd.Parameters.Add ("@desc", desc);
id = (int)cmd.ExecuteScalar ();
}
cnx.Close ();
}
return id;
}
#endregion
}
}

@ -0,0 +1,22 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("WorkFlowProvider")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Paul Schneider")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,18 @@
using System;
using yavscModel.WorkFlow;
namespace WorkFlowProvider
{
public static class WFManager
{
public static IContentProvider GetContentProviderFWC ()
{
string clsName = System.Configuration.ConfigurationManager.AppSettings ["WorkflowContentProviderClass"];
if (clsName == null)
throw new Exception ("No content provider specified in the configuration file (Application parameter \"WorkflowContentProviderClass\")");
System.Reflection.ConstructorInfo ci = Type.GetType (clsName).GetConstructor (System.Type.EmptyTypes);
return (IContentProvider) ci.Invoke (System.Type.EmptyTypes);
}
}
}

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{821FF72D-9F4B-4A2C-B95C-7B965291F119}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>WorkFlowProvider</RootNamespace>
<AssemblyName>WorkFlowProvider</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="Npgsql" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="NpgsqlContentProvider.cs" />
<Compile Include="WFManager.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\yavscModel\yavscModel.csproj">
<Project>{68F5B80A-616E-4C3C-91A0-828AA40000BD}</Project>
<Name>yavscModel</Name>
</ProjectReference>
</ItemGroup>
</Project>

@ -0,0 +1,74 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Web", "web\Web.csproj", "{77044C92-D2F1-45BD-80DD-AA25B311B027}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NpgsqlMRPProviders", "NpgsqlMRPProviders\NpgsqlMRPProviders.csproj", "{BBA7175D-7F92-4278-96FC-84C495A2B5A6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NpgsqlBlogProvider", "NpgsqlBlogProvider\NpgsqlBlogProvider.csproj", "{C6E9E91B-97D3-48D9-8AA7-05356929E162}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SalesCatalog", "SalesCatalog\SalesCatalog.csproj", "{90BF2234-7252-4CD5-B2A4-17501B19279B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "yavscModel", "yavscModel\yavscModel.csproj", "{68F5B80A-616E-4C3C-91A0-828AA40000BD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowProvider", "WorkFlowProvider\WorkFlowProvider.csproj", "{821FF72D-9F4B-4A2C-B95C-7B965291F119}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YavscClient", "yavscclient\YavscClient.csproj", "{EEFCECE6-3B7F-4BBE-B7AF-69377AF3CF39}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebControls", "WebControls\WebControls.csproj", "{59E1DF7B-FFA0-4DEB-B5F3-76EBD98D5356}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "vscadm", "vscadm\vscadm.csproj", "{6C5E1490-E141-4ADA-84E5-6D65523D6B73}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ITContent", "ITContent\ITContent.csproj", "{88D83FC9-4158-4435-98A6-1F8F7F448B8F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{59E1DF7B-FFA0-4DEB-B5F3-76EBD98D5356}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{59E1DF7B-FFA0-4DEB-B5F3-76EBD98D5356}.Debug|Any CPU.Build.0 = Debug|Any CPU
{59E1DF7B-FFA0-4DEB-B5F3-76EBD98D5356}.Release|Any CPU.ActiveCfg = Release|Any CPU
{59E1DF7B-FFA0-4DEB-B5F3-76EBD98D5356}.Release|Any CPU.Build.0 = Release|Any CPU
{68F5B80A-616E-4C3C-91A0-828AA40000BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{68F5B80A-616E-4C3C-91A0-828AA40000BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{68F5B80A-616E-4C3C-91A0-828AA40000BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{68F5B80A-616E-4C3C-91A0-828AA40000BD}.Release|Any CPU.Build.0 = Release|Any CPU
{6C5E1490-E141-4ADA-84E5-6D65523D6B73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C5E1490-E141-4ADA-84E5-6D65523D6B73}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C5E1490-E141-4ADA-84E5-6D65523D6B73}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C5E1490-E141-4ADA-84E5-6D65523D6B73}.Release|Any CPU.Build.0 = Release|Any CPU
{77044C92-D2F1-45BD-80DD-AA25B311B027}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{77044C92-D2F1-45BD-80DD-AA25B311B027}.Debug|Any CPU.Build.0 = Debug|Any CPU
{77044C92-D2F1-45BD-80DD-AA25B311B027}.Release|Any CPU.ActiveCfg = Release|Any CPU
{77044C92-D2F1-45BD-80DD-AA25B311B027}.Release|Any CPU.Build.0 = Release|Any CPU
{821FF72D-9F4B-4A2C-B95C-7B965291F119}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{821FF72D-9F4B-4A2C-B95C-7B965291F119}.Debug|Any CPU.Build.0 = Debug|Any CPU
{821FF72D-9F4B-4A2C-B95C-7B965291F119}.Release|Any CPU.ActiveCfg = Release|Any CPU
{821FF72D-9F4B-4A2C-B95C-7B965291F119}.Release|Any CPU.Build.0 = Release|Any CPU
{88D83FC9-4158-4435-98A6-1F8F7F448B8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{88D83FC9-4158-4435-98A6-1F8F7F448B8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{88D83FC9-4158-4435-98A6-1F8F7F448B8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{88D83FC9-4158-4435-98A6-1F8F7F448B8F}.Release|Any CPU.Build.0 = Release|Any CPU
{90BF2234-7252-4CD5-B2A4-17501B19279B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{90BF2234-7252-4CD5-B2A4-17501B19279B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{90BF2234-7252-4CD5-B2A4-17501B19279B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{90BF2234-7252-4CD5-B2A4-17501B19279B}.Release|Any CPU.Build.0 = Release|Any CPU
{BBA7175D-7F92-4278-96FC-84C495A2B5A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BBA7175D-7F92-4278-96FC-84C495A2B5A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BBA7175D-7F92-4278-96FC-84C495A2B5A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BBA7175D-7F92-4278-96FC-84C495A2B5A6}.Release|Any CPU.Build.0 = Release|Any CPU
{C6E9E91B-97D3-48D9-8AA7-05356929E162}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C6E9E91B-97D3-48D9-8AA7-05356929E162}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6E9E91B-97D3-48D9-8AA7-05356929E162}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6E9E91B-97D3-48D9-8AA7-05356929E162}.Release|Any CPU.Build.0 = Release|Any CPU
{EEFCECE6-3B7F-4BBE-B7AF-69377AF3CF39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEFCECE6-3B7F-4BBE-B7AF-69377AF3CF39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEFCECE6-3B7F-4BBE-B7AF-69377AF3CF39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEFCECE6-3B7F-4BBE-B7AF-69377AF3CF39}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = web\Web.csproj
EndGlobalSection
EndGlobal

@ -0,0 +1 @@
git archive --format=tar --prefix=yavsc-1.1/ 1.1 | bzip2 > yavsc-1.1.tar.bz2

Binary file not shown.

@ -0,0 +1,15 @@
using System;
using System.IO;
using System.Threading;
namespace vscadm
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
}
}
}

@ -0,0 +1,22 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("vscadm")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Paul Schneider")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6C5E1490-E141-4ADA-84E5-6D65523D6B73}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>vscadm</RootNamespace>
<AssemblyName>vscadm</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Messaging" />
<Reference Include="System.Core" />
<Reference Include="System.Configuration" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,81 @@
using System;
using System.Diagnostics;
using System.IO;
using yavscModel.Admin;
using Npgsql.Web.Blog;
namespace Yavsc.Admin
{
public class DataManager
{
DataAccess da;
public DataManager (DataAccess datac)
{
da = datac;
}
public Export CreateBackup ()
{
Environment.SetEnvironmentVariable("PGPASSWORD", da.Password);
Export e = new Export ();
string fileName = da.BackupPrefix + "-" + DateTime.Now.ToString ("yyyyMMdd");
FileInfo ofi = new FileInfo (fileName);
e.FileName = ofi.FullName;
Exec ("pg_dump", string.Format (
"-wb -Z3 -f {0} -Fd -h {1} -U {2} -p {3} {4}",
fileName, da.Host, da.Dbuser, da.Port, da.Dbname ),e);
return e;
}
private void Exec(string name, string args, TaskOutput output)
{
ProcessStartInfo Pinfo =
new ProcessStartInfo (name,args);
Pinfo.RedirectStandardError = true;
Pinfo.RedirectStandardOutput = true;
Pinfo.CreateNoWindow = true;
Pinfo.UseShellExecute = false;
using (Process p = new Process ()) {
p.EnableRaisingEvents = true;
p.StartInfo = Pinfo;
p.Start ();
p.WaitForExit ();
output.Error = p.StandardError.ReadToEnd ();
output.Message = p.StandardOutput.ReadToEnd ();
output.ExitCode = p.ExitCode;
p.Close ();
}
}
public TaskOutput Restore (string fileName, bool dataOnly)
{
Environment.SetEnvironmentVariable("PGPASSWORD", da.Password);
var t = new TaskOutput ();
Exec ("pg_restore", (dataOnly?"-a ":"")+string.Format (
"-1 -w -Fd -O -h {0} -U {1} -p {2} -d {3} {4}",
da.Host, da.Dbuser, da.Port, da.Dbname, fileName ),t);
return t;
}
public TaskOutput CreateDb ()
{
return Restore ("freshinstall", false);
}
public Export TagBackup (string filename, string [] tags)
{
/* FileInfo fi = new FileInfo (filename);
using (FileStream s = fi.OpenWrite ()) {
} */
throw new NotImplementedException ();
}
public TaskOutput TagRestore (string fileName)
{
Environment.SetEnvironmentVariable ("PGPASSWORD", da.Password);
var t = new TaskOutput ();
Exec ("pg_restore", string.Format (
"-a -w -Fd -O -h {0} -U {1} -p {2} -d {3} {4}",
da.Host, da.Dbuser, da.Port, da.Dbname, fileName ),t);
return t;
}
}
}

@ -0,0 +1,14 @@
using System;
using System.ComponentModel;
namespace Yavsc.Admin
{
public class Export: TaskOutput
{
public Export ()
{
}
public string FileName { get; set; }
}
}

@ -0,0 +1,12 @@
using System;
using System.ComponentModel;
namespace Yavsc.Admin
{
public class TaskOutput {
public string Message { get; set; }
public string Error { get; set; }
public int ExitCode { get; set; }
}
}

@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Yavsc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("paul schneider")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.2.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

@ -0,0 +1,17 @@
using System;
using SalesCatalog.Model;
using System.Collections.Generic;
namespace Yavsc.Basket
{
public class Basket
{
public Basket ()
{
}
public void Add(Product p)
{
}
}
}

@ -0,0 +1,80 @@
using System;
using System.Web;
using SalesCatalog;
using SalesCatalog.Model;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Mvc.Html;
namespace Yavsc.CatExts
{
public static class WebCatalogExtensions
{
public static string CommandForm(this HtmlHelper<PhysicalProduct> helper, Product pos,string atc="Add to backet") {
StringBuilder sb = new StringBuilder ();
sb.Append (helper.ValidationSummary ());
TagBuilder ft = new TagBuilder ("form");
ft.Attributes.Add("action","/FrontOffice/Command");
ft.Attributes.Add("method","post");
ft.Attributes.Add("enctype","multipart/form-data");
TagBuilder fieldset = new TagBuilder ("fieldset");
TagBuilder legend = new TagBuilder ("legend");
legend.SetInnerText (pos.Name);
TagBuilder para = new TagBuilder ("p");
StringBuilder sbfc = new StringBuilder ();
if (pos.CommandForm != null)
foreach (FormElement e in pos.CommandForm.Items) {
sbfc.Append (e.ToHtml ());
sbfc.Append ("<br/>\n");
}
sbfc.Append (
string.Format(
"<input type=\"submit\" value=\"{0}\"/><br/>\n",
atc
));
sbfc.Append (helper.Hidden ("ref", pos.Reference));
para.InnerHtml = sbfc.ToString ();
fieldset.InnerHtml = legend.ToString ()+"\n"+para.ToString ();
ft.InnerHtml = fieldset.ToString ();
sb.Append (ft.ToString ());
return sb.ToString ();
}
public static string CommandForm(this HtmlHelper<Service> helper, Product pos,string atc="Add to backet") {
StringBuilder sb = new StringBuilder ();
sb.Append (helper.ValidationSummary ());
TagBuilder ft = new TagBuilder ("form");
ft.Attributes.Add("action","/FrontOffice/Command");
ft.Attributes.Add("method","post");
ft.Attributes.Add("enctype","multipart/form-data");
TagBuilder fieldset = new TagBuilder ("fieldset");
TagBuilder legend = new TagBuilder ("legend");
legend.SetInnerText (pos.Name);
TagBuilder para = new TagBuilder ("p");
StringBuilder sbfc = new StringBuilder ();
if (pos.CommandForm != null)
foreach (FormElement e in pos.CommandForm.Items) {
sbfc.Append (e.ToHtml ());
sbfc.Append ("<br/>\n");
}
sbfc.Append (
string.Format(
"<input type=\"submit\" value=\"{0}\"/><br/>\n",atc));
sbfc.Append (helper.Hidden ("ref", pos.Reference));
para.InnerHtml = sbfc.ToString ();
fieldset.InnerHtml = legend.ToString ()+"\n"+para.ToString ();
ft.InnerHtml = fieldset.ToString ();
sb.Append (ft.ToString ());
return sb.ToString ();
}
}
}

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<XmlCatalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Brands>
<Brand>
<Name>shdsi</Name>
<Slogan>Votre logiciel, efficace, sûr, et sur mesure</Slogan>
<Logo>
<Src>/images/logoDev.png</Src>
<Alt></Alt>
</Logo>
<Categories>
<ProductCategory>
<Name>Systèmes d'information et sites Web</Name>
<Reference>ntic</Reference>
<Products>
<Product xsi:type="Service">
<Name>Développement</Name>
<Description>Votre Extranet, Intranet,
site Web, sur mesure, élégant et efficace, au look racé, accessible,
et développé en cycles courts</Description>
<Reference>nticdev</Reference>
</Product>
<Product xsi:type="Service">
<Name>Maintenance</Name>
<Description>Correction des anomalies, réalisation des évolutions, prévision des besoins</Description>
<Reference>nticmaint</Reference>
</Product>
</Products>
</ProductCategory>
</Categories>
<DefaultForm>
<Action>/Commande</Action>
<Items>
<FormElement xsi:type="Text">
<Val>Entrez un commentaire :</Val>
</FormElement>
<FormElement xsi:type="TextInput">
<Id>comment</Id>
<Value xsi:type="xsd:string">Commentaire</Value>
</FormElement>
<FormElement xsi:type="Text">
<Val>Choisissez le type d'intervention souhaité: </Val>
</FormElement>
<FormElement xsi:type="SelectInput">
<Id>ad</Id>
<Items>
<string>à distance</string>
<string>sur site</string>
</Items>
<SelectedIndex>0</SelectedIndex>
</FormElement>
</Items>
</DefaultForm>
</Brand>
</Brands>
</XmlCatalog>

@ -0,0 +1,369 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Profile;
using System.Web.Security;
using Yavsc;
using yavscModel.RolesAndMembers;
using Yavsc.Helpers;
namespace Yavsc.Controllers
{
public class AccountController : Controller
{
private static string registrationMessage =
WebConfigurationManager.AppSettings ["RegistrationMessage"];
string avatarDir = "~/avatars";
public string AvatarDir {
get { return avatarDir; }
set { avatarDir = value; }
}
public ActionResult Index ()
{
return View ();
}
public ActionResult Login (string returnUrl)
{
ViewData ["returnUrl"] = returnUrl;
return View ();
}
[Authorize]
public ActionResult Profile(Profile model)
{
ViewData ["UserName"] = Membership.GetUser ().UserName;
model.FromProfileBase(HttpContext.Profile);
return View (model);
}
// TODO [ValidateAntiForgeryToken]
public ActionResult DoLogin (LoginModel model, string returnUrl)
{
if (ModelState.IsValid) {
if (Membership.ValidateUser (model.UserName, model.Password)) {
FormsAuthentication.SetAuthCookie (model.UserName, model.RememberMe);
if (returnUrl != null)
return Redirect (returnUrl);
else return View ("Index");
} else {
ModelState.AddModelError ("UserName", "The user name or password provided is incorrect.");
}
}
ViewData ["returnUrl"] = returnUrl;
// If we got this far, something failed, redisplay form
return View ("Login",model);
}
public ActionResult Register (RegisterViewModel model, string returnUrl)
{
ViewData["returnUrl"] = returnUrl;
if (Request.RequestType == "GET") {
foreach (string k in ModelState.Keys)
ModelState [k].Errors.Clear ();
return View (model);
}
if (ModelState.IsValid) {
if (model.ConfirmPassword != model.Password)
{
ModelState.AddModelError("ConfirmPassword","Veuillez confirmer votre mot de passe");
return View (model);
}
MembershipCreateStatus mcs;
var user = Membership.CreateUser (
model.UserName,
model.Password,
model.Email,
null,
null,
false,
out mcs);
switch (mcs) {
case MembershipCreateStatus.DuplicateEmail:
ModelState.AddModelError("Email", "Cette adresse e-mail correspond " +
"à un compte utilisateur existant");
return View (model);
case MembershipCreateStatus.DuplicateUserName:
ModelState.AddModelError("UserName", "Ce nom d'utilisateur est " +
"déjà enregistré");
return View (model);
case MembershipCreateStatus.Success:
FileInfo fi = new FileInfo (
Server.MapPath(registrationMessage));
if (!fi.Exists) {
ViewData["Error"] = "Erreur inattendue (pas de corps de message à envoyer)";
return View (model);
}
using (StreamReader sr = fi.OpenText()) {
string body = sr.ReadToEnd();
body = body.Replace("<%SiteName%>",YavscHelpers.SiteName);
body = body.Replace("<%UserName%>",user.UserName);
body = body.Replace("<%UserActivatonUrl%>",
string.Format("<{0}://{1}/Account/Validate/{2}?key={3}",
Request.Url.Scheme,
Request.Url.Authority,
user.UserName,
user.ProviderUserKey.ToString()));
using (MailMessage msg = new MailMessage(
HomeController.Admail,user.Email,
string.Format("Validation de votre compte {0}",YavscHelpers.SiteName),
body))
{
using (SmtpClient sc = new SmtpClient())
{
sc.Send (msg);
}
}
ViewData ["username"] = user.UserName;
ViewData ["email"] = user.Email;
return View ("RegistrationPending");
}
default:
ViewData["Error"] = "Une erreur inattendue s'est produite" +
"a l'enregistrement de votre compte utilisateur" +
string.Format("({0}).",mcs.ToString()) +
"Veuillez pardonner la gêne" +
"occasionnée";
return View (model);
}
}
return View (model);
}
public ActionResult ChangePasswordSuccess ()
{
return View ();
}
[HttpGet]
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult ChangePassword (ChangePasswordModel model)
{
if (ModelState.IsValid) {
// ChangePassword will throw an exception rather
// than return false in certain failure scenarios.
bool changePasswordSucceeded;
try {
var users = Membership.FindUsersByName (model.Username);
if (users.Count > 0) {
MembershipUser user = Membership.GetUser (model.Username,true);
changePasswordSucceeded = user.ChangePassword (model.OldPassword, model.NewPassword);
} else {
changePasswordSucceeded = false;
}
} catch (Exception) {
changePasswordSucceeded = false;
}
if (changePasswordSucceeded) {
return RedirectToAction ("ChangePasswordSuccess");
} else {
ModelState.AddModelError ("Password", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
return View (model);
}
[Authorize()]
public ActionResult UserList ()
{
MembershipUserCollection c = Membership.GetAllUsers ();
return View (c);
}
private const string adminRoleName = "Admin";
[Authorize()]
public ActionResult Admin (NewAdminModel model)
{
string currentUser = Membership.GetUser ().UserName;
if (ModelState.IsValid) {
Roles.AddUserToRole (model.UserName, adminRoleName);
ViewData ["Message"] = model.UserName + " was added to the role '" + adminRoleName + "'";
} else {
if (!Roles.RoleExists (adminRoleName)) {
Roles.CreateRole (adminRoleName);
string.Format ("The role '{0}' has just been created. ",
adminRoleName);
}
string [] admins = Roles.GetUsersInRole (adminRoleName);
if (admins.Length > 0) {
if (! admins.Contains (Membership.GetUser ().UserName)) {
ModelState.Remove("UserName");
ModelState.AddModelError("UserName", "You're not administrator!");
return View ("Index");
}
} else {
Roles.AddUserToRole (currentUser, adminRoleName);
admins = new string[] { currentUser };
ViewData ["Message"] += string.Format (
"There was no user in the 'Admin' role. You ({0}) was just added as the firt user in the 'Admin' role. ", currentUser);
}
List<SelectListItem> users = new List<SelectListItem> ();
foreach (MembershipUser u in Membership.GetAllUsers ()) {
var i = new SelectListItem ();
i.Text = string.Format ("{0} <{1}>", u.UserName, u.Email);
i.Value = u.UserName;
users.Add (i);
}
ViewData ["useritems"] = users;
ViewData ["admins"] = admins;
}
return View (model);
}
[Authorize()]
public ActionResult RoleList ()
{
return View (Roles.GetAllRoles ());
}
[Authorize(Roles="Admin")]
public ActionResult RemoveFromRole(string username, string rolename, string returnUrl)
{
Roles.RemoveUserFromRole(username,rolename);
return Redirect(returnUrl);
}
[Authorize(Roles="Admin")]
public ActionResult RemoveUser (string username, string submitbutton)
{
if (submitbutton == "Supprimer") {
Membership.DeleteUser (username);
ViewData["Message"]=
string.Format("utilisateur \"{0}\" supprimé",username);
}
return RedirectToAction("UserList");
}
[Authorize]
[HttpPost]
//public ActionResult UpdateProfile(HttpPostedFileBase Avatar, string Address, string CityAndState, string ZipCode, string Country, string WebSite)
public ActionResult UpdateProfile(Profile model, HttpPostedFileBase AvatarFile)
{
string username = Membership.GetUser ().UserName;
if (AvatarFile != null) {
if (AvatarFile.ContentType == "image/png") {
// byte[] img = new byte[AvatarFile.ContentLength];
// AvatarFile.InputStream.Read (img, 0, AvatarFile.ContentLength);
// model.Avatar = img;
string avdir=Server.MapPath (AvatarDir);
string avpath=Path.Combine(avdir,username+".png");
AvatarFile.SaveAs (avpath);
} else
ModelState.AddModelError ("Avatar",
string.Format ("Image type {0} is not supported (suported formats : {1})",
AvatarFile.ContentType, "image/png")
);
}
if (ModelState.IsValid) {
HttpContext.Profile.SetPropertyValue (
"Address", model.Address);
HttpContext.Profile.SetPropertyValue (
"BlogTitle", model.BlogTitle);
HttpContext.Profile.SetPropertyValue (
"BlogVisible", model.BlogVisible);
HttpContext.Profile.SetPropertyValue (
"CityAndState", model.CityAndState);
HttpContext.Profile.SetPropertyValue (
"Country", model.Country);
HttpContext.Profile.SetPropertyValue (
"WebSite", model.WebSite);
}
// HttpContext.Profile.SetPropertyValue("Avatar",Avatar);
return RedirectToAction ("Profile");
}
[Authorize(Roles="Admin")]
public ActionResult RemoveRole (string rolename, string submitbutton)
{
if (submitbutton == "Supprimer")
{
Roles.DeleteRole(rolename);
}
return RedirectToAction("RoleList");
}
[Authorize(Roles="Admin")]
public ActionResult RemoveRoleQuery(string rolename)
{
ViewData["roletoremove"] = rolename;
return View ();
}
[Authorize(Roles="Admin")]
public ActionResult RemoveUserQuery(string username)
{
ViewData["usertoremove"] = username;
return UserList();
}
[Authorize]
public ActionResult Logout (string returnUrl)
{
FormsAuthentication.SignOut();
return Redirect(returnUrl);
}
[Authorize(Roles="Admin")]
public ActionResult AddRole ()
{
return View ();
}
[Authorize(Roles="Admin")]
public ActionResult DoAddRole (string rolename)
{
Roles.CreateRole(rolename);
ViewData["Message"] = "Rôle créé : "+rolename;
return View ();
}
public ActionResult Validate (string id, string key)
{
MembershipUser u = Membership.GetUser (id, false);
if (u == null) {
ViewData ["Error"] =
string.Format ("Cet utilisateur n'existe pas ({0})", id);
}
else
if (u.ProviderUserKey.ToString () == key) {
u.IsApproved = true;
Membership.UpdateUser(u);
ViewData["Message"] =
string.Format ("La création de votre compte ({0}) est validée.", id);
}
else ViewData["Error"] = "La clé utilisée pour valider ce compte est incorrecte";
return View ();
}
}
}

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Yavsc.Admin;
using yavscModel.Admin;
namespace Yavsc.Controllers
{
public class BackOfficeController : Controller
{
[Authorize(Roles="Admin")]
public ActionResult Index(DataAccess model)
{
return View (model);
}
[Authorize(Roles="Admin")]
public ActionResult Backups(DataAccess model)
{
return View (model);
}
[Authorize(Roles="Admin")]
public ActionResult CreateBackup(DataAccess datac)
{
if (datac != null) {
if (ModelState.IsValid) {
if (string.IsNullOrEmpty (datac.Password))
ModelState.AddModelError ("Password", "Invalid passord");
DataManager ex = new DataManager (datac);
Export e = ex.CreateBackup ();
if (e.ExitCode > 0)
ModelState.AddModelError ("Password", "Operation Failed");
return View ("BackupCreated", e);
}
} else {
datac = new DataAccess ();
}
return View (datac);
}
[Authorize(Roles="Admin")]
public ActionResult CreateUserBackup(DataAccess datac,string username)
{
throw new NotImplementedException();
}
[Authorize(Roles="Admin")]
public ActionResult Restore(DataAccess datac,string backupName,bool dataOnly=true)
{
ViewData ["BackupName"] = backupName;
if (ModelState.IsValid) {
DataManager mgr = new DataManager (datac);
ViewData ["BackupName"] = backupName;
ViewData ["DataOnly"] = dataOnly;
TaskOutput t = mgr.Restore (backupName,dataOnly);
return View ("Restored", t);
}
return View (datac);
}
}
}

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Yavsc.Controllers
{
public class BasketController : Controller
{
public ActionResult Index()
{
return View ();
}
public ActionResult Details(int id)
{
return View ();
}
public ActionResult Create()
{
var user = Membership.GetUser ();
var username = (user != null)?user.UserName:Request.AnonymousID;
// get an existing basket
return View ();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try {
return RedirectToAction ("Index");
} catch {
return View ();
}
}
public ActionResult Edit(int id)
{
return View ();
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try {
return RedirectToAction ("Index");
} catch {
return View ();
}
}
public ActionResult Delete(int id)
{
return View ();
}
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try {
return RedirectToAction ("Index");
} catch {
return View ();
}
}
}
}

@ -0,0 +1,269 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Profile;
using System.Web.Security;
using CodeKicker.BBCode;
using Npgsql.Web.Blog;
using Npgsql.Web.Blog.DataModel;
using Yavsc;
using yavscModel;
namespace Yavsc.Controllers
{
public class BlogsController : Controller
{
string defaultAvatarMimetype;
private string sitename =
WebConfigurationManager.AppSettings ["Name"];
string avatarDir = "~/avatars";
public string AvatarDir {
get { return avatarDir; }
set { avatarDir = value; }
}
public BlogsController ()
{
string[] defaultAvatarSpec = ConfigurationManager.AppSettings.Get ("DefaultAvatar").Split (';');
if (defaultAvatarSpec.Length != 2)
throw new ConfigurationErrorsException ("the DefaultAvatar spec should be found as <fileName>;<mime-type> ");
defaultAvatar = defaultAvatarSpec [0];
defaultAvatarMimetype = defaultAvatarSpec [1];
}
public ActionResult Index (string user = null, string title = null, int pageIndex=0, int pageSize=10)
{
if (string.IsNullOrEmpty (user)) {
ViewData ["Message"] = "Blogs";
return BlogList (pageIndex, pageSize);
} else {
MembershipUser u = Membership.GetUser (user, false);
if (u == null) {
ModelState.AddModelError ("UserName",
string.Format ("Utilisateur inconu : {0}", user));
return BlogList ();
} else {
if (string.IsNullOrEmpty (title))
return UserPosts (user, pageIndex, pageSize);
return UserPost (user, title);
}
}
}
public ActionResult BlogList (int pageIndex = 0, int pageSize = 10)
{
ViewData ["SiteName"] = sitename;
int totalRecords;
BlogEntryCollection bs = BlogManager.LastPosts (pageIndex, pageSize, out totalRecords);
ViewData ["RecordCount"] = totalRecords;
ViewData ["PageSize"] = pageSize;
ViewData ["PageIndex"] = pageIndex;
return View ("Index", bs);
}
[HttpGet]
public ActionResult UserPosts (string user, int pageIndex = 0, int pageSize = 10)
{
int tr;
MembershipUser u = Membership.GetUser ();
FindBlogEntryFlags sf = FindBlogEntryFlags.MatchUserName;
ViewData ["SiteName"] = sitename;
ViewData ["BlogUser"] = user;
if (u != null)
if (u.UserName == user)
sf |= FindBlogEntryFlags.MatchInvisible;
BlogEntryCollection c = BlogManager.FindPost (user, sf, pageIndex, pageSize, out tr);
ViewData ["BlogTitle"] = BlogTitle (user);
ViewData ["PageIndex"] = pageIndex;
ViewData ["PageSize"] = pageSize;
ViewData ["RecordCount"] = tr;
return View ("UserPosts", c);
}
[Authorize]
public ActionResult RemoveComment(long cmtid)
{
long postid = BlogManager.RemoveComment (cmtid);
return UserPost (postid);
}
private ActionResult UserPost (long id)
{
ViewData ["PostId"] = id;
BlogEntry e = BlogManager.GetPost (id);
return UserPost (e);
}
private ActionResult UserPost (BlogEntry e)
{
if (e == null)
return View ("TitleNotFound");
MembershipUser u = Membership.GetUser ();
if (u != null)
ViewData ["UserName"] = u.UserName;
if (!e.Visible) {
if (u==null)
return View ("TitleNotFound");
else if (u.UserName!=e.UserName)
return View ("TitleNotFound");
}
ViewData ["BlogTitle"] = BlogTitle (e.UserName);
ViewData ["Comments"] = BlogManager.GetComments (e.Id);
return View ("UserPost", e);
}
public ActionResult UserPost (string user, string title)
{
ViewData ["BlogUser"] = user;
ViewData ["PostTitle"] = title;
int postid = 0;
if (string.IsNullOrEmpty (title)) {
if (int.TryParse (user, out postid)) {
return UserPost (BlogManager.GetPost (postid));
}
}
return UserPost (BlogManager.GetPost (user, title));
}
[Authorize]
public ActionResult Post (string user, string title)
{
ViewData ["SiteName"] = sitename;
string un = Membership.GetUser ().UserName;
if (String.IsNullOrEmpty (user))
user = un;
if (un != user)
ViewData ["Message"] = string.Format ("Vous n'êtes pas {0}!", user);
ViewData ["UserName"] = un;
return View (new BlogEditEntryModel { Title = title });
}
[Authorize]
public ActionResult ValidatePost (BlogEditEntryModel model)
{
string username = Membership.GetUser ().UserName;
ViewData ["SiteName"] = sitename;
ViewData ["BlogUser"] = username;
if (ModelState.IsValid) {
if (!model.Preview) {
BlogManager.Post (username, model.Title, model.Content, model.Visible);
return UserPost (username, model.Title);
}
}
return View ("Post", model);
}
[Authorize]
public ActionResult ValidateEdit (BlogEditEntryModel model)
{
ViewData ["SiteName"] = sitename;
ViewData ["BlogUser"] = Membership.GetUser ().UserName;
if (ModelState.IsValid) {
if (!model.Preview) {
BlogManager.UpdatePost (model.Id, model.Content, model.Visible);
return UserPost (model);
}
}
return View ("Edit", model);
}
[Authorize]
public ActionResult Edit (BlogEditEntryModel model)
{
if (model != null) {
string user = Membership.GetUser ().UserName;
ViewData ["BlogTitle"] = this.BlogTitle (user);
ViewData ["UserName"] = user;
if (model.UserName == null) {
model.UserName = user;
BlogEntry e = BlogManager.GetPost (model.UserName, model.Title);
if (e == null) {
return View ("TitleNotFound");
} else {
model = new BlogEditEntryModel (e);
ModelState.Clear ();
this.TryValidateModel (model);
}
} else if (model.UserName != user) {
return View ("TitleNotFound");
}
}
return View (model);
}
private string BlogTitle (string user)
{
return string.Format ("{0}'s blog", user);
}
public ActionResult Comment (BlogEditCommentModel model) {
string username = Membership.GetUser ().UserName;
ViewData ["SiteName"] = sitename;
if (ModelState.IsValid) {
if (!model.Preview) {
BlogManager.Comment(username, model.PostId, model.CommentText, model.Visible);
return UserPost (model.PostId);
}
}
return View (model);
}
string defaultAvatar;
[AcceptVerbs (HttpVerbs.Get)]
public ActionResult Avatar (string user)
{
string avpath = Path.Combine (
Server.MapPath (AvatarDir), user + ".png");
FileInfo fia = new FileInfo (avpath);
if (!fia.Exists)
fia = new FileInfo (Server.MapPath (defaultAvatar));
return File (fia.OpenRead (), defaultAvatarMimetype);
}
[Authorize]
public ActionResult Remove (string user, string title, string returnUrl)
{
if (!Roles.IsUserInRole ("Admin")) {
string rguser = Membership.GetUser ().UserName;
if (rguser != user) {
ModelState.AddModelError (
"Title", string.Format (
"Vous n'avez pas de droits sur le Blog de {0}",
user));
return Return (returnUrl);
}
}
BlogEntry e = BlogManager.GetPost (user, title);
if (e == null) {
ModelState.AddModelError (
"Title",
string.Format (
"Aucun post portant le titre \"{0}\" pour l'utilisateur {1}",
title, user));
return Return (returnUrl);
}
BlogManager.RemovePost (user, title);
return Return (returnUrl);
}
private ActionResult Return (string returnUrl)
{
if (!string.IsNullOrEmpty (returnUrl))
return Redirect (returnUrl);
else
return RedirectToAction ("Index");
}
}
}

@ -0,0 +1,21 @@
using System;
using Yavsc;
using SalesCatalog;
using SalesCatalog.Model;
using System.Web.Mvc;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using Yavsc.Controllers;
namespace Yavsc.Controllers
{
public class Commande
{
public Commande(FormCollection collection)
{
}
}
}

@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Web.Security;
using FileSystem;
using System.Text.RegularExpressions;
namespace Yavsc.Controllers
{
public class FileSystemController : Controller
{
private static string usersDir ="users";
public static string UsersDir {
get {
return usersDir;
}
}
[Authorize]
public ActionResult Index()
{
string user = Membership.GetUser ().UserName;
ViewData ["UserName"] = user;
DirectoryInfo di = new DirectoryInfo (
Path.Combine(
UsersDir,
user));
if (!di.Exists)
di.Create ();
return View (new FileInfoCollection( di.GetFiles()));
}
public ActionResult Details(string id)
{
foreach (char x in Path.GetInvalidPathChars()) {
if (id.Contains (x)) {
ViewData ["Message"] =
string.Format (
"Something went wrong following the following path : {0} (\"{1}\")",
id,x);
return RedirectToAction ("Index");
}
}
string fpath = Path.Combine (BaseDir, id);
ViewData["Content"] = Url.Content (fpath);
FileInfo fi = new FileInfo (fpath);
return View (fi);
}
public ActionResult Create()
{
return View ();
}
[HttpPost]
[Authorize]
public ActionResult Create(FormCollection collection)
{
try {
string fnre = "[A-Za-z0-9~\\-.]+";
HttpFileCollectionBase hfc = Request.Files;
for (int i=0; i<hfc.Count; i++)
{
if (!Regex.Match(hfc[i].FileName,fnre).Success)
{
ViewData ["Message"] += string.Format("<p>File name '{0}' refused</p>",hfc[i].FileName);
ModelState.AddModelError(
"AFile",
string.Format(
"The file name {0} dosn't match an acceptable file name {1}",
hfc[i].FileName,fnre))
;
return View();
}
}
for (int i=0; i<hfc.Count; i++)
{
// TODO Limit with hfc[h].ContentLength
hfc[i].SaveAs(Path.Combine(BaseDir,hfc[i].FileName));
ViewData ["Message"] += string.Format("<p>File name '{0}' saved</p>",hfc[i].FileName);
}
return RedirectToAction ("Index","FileSystem");
} catch (Exception e) {
ViewData ["Message"] = "Exception:"+e.Message;
return View ();
}
}
public static string BaseDir { get { return Path.Combine (UsersDir, Membership.GetUser ().UserName); } }
public ActionResult Edit(int id)
{
return View ();
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try {
return RedirectToAction ("Index");
} catch {
return View ();
}
}
public ActionResult Delete(int id)
{
return View ();
}
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try {
return RedirectToAction ("Index");
} catch {
return View ();
}
}
}
}

@ -0,0 +1,85 @@
using System;
using Yavsc;
using SalesCatalog;
using SalesCatalog.Model;
using System.Web.Routing;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Web.Http;
using System.Net.Http;
using System.Web;
using System.Linq;
using System.IO;
using System.Net;
namespace Yavsc.ApiControllers
{
public class FrontOfficeController : ApiController
{
[AcceptVerbs("GET")]
public Catalog Catalog ()
{
return CatalogManager.GetCatalog ();
}
[AcceptVerbs("GET")]
public ProductCategory GetProductCategorie (string brandName, string prodCategorie)
{
return CatalogManager.GetCatalog ().GetBrand (brandName).GetProductCategory (prodCategorie)
;
}
[AcceptVerbs("POST")]
public string Command()
{
return null;
}
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string username = HttpContext.Current.User.Identity.Name;
int nbf = 0;
foreach(string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string filePath = HttpContext.Current.Server.MapPath("~/users/"+username+"/"+ postedFile.FileName);
postedFile.SaveAs(filePath);
nbf++;
}
result = Request.CreateResponse <string>(HttpStatusCode.Created,
string.Format("Received {0} files",nbf));
}
else
{
result = Request.CreateResponse <string>(HttpStatusCode.BadRequest,"No file received");
}
return result;
}
[HttpPost]
public string ProfileImagePost(HttpPostedFile profileImage)
{
string[] extensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
if (!extensions.Any(x => x.Equals(Path.GetExtension(profileImage.FileName.ToLower()), StringComparison.OrdinalIgnoreCase)))
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest));
}
// string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
// Other code goes here
// profileImage.SaveAs ();
return "/path/to/image.png";
}
}
}

@ -0,0 +1,128 @@
using System;
using Yavsc;
using SalesCatalog;
using SalesCatalog.Model;
using System.Web.Mvc;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using Yavsc.Controllers;
using System.Collections.Generic;
namespace Yavsc.Controllers
{
public class FrontOfficeController : Controller
{
[AcceptVerbs("GET")]
public ActionResult Catalog ()
{
return View (
CatalogManager.GetCatalog ()
);
}
/// <summary>
/// Catalog this instance.
/// </summary>
[AcceptVerbs("GET")]
public ActionResult Brand (string id)
{
Catalog c = CatalogManager.GetCatalog ();
ViewData ["BrandName"] = id;
return View ( c.GetBrand (id) );
}
/// <summary>
/// get the product category
/// </summary>
/// <returns>The category.</returns>
/// <param name="bn">Bn.</param>
/// <param name="pc">Pc.</param>
[AcceptVerbs("GET")]
public ActionResult ProductCategory (string id, string pc)
{
ViewData ["BrandName"] = id;
return View (
CatalogManager.GetCatalog ().GetBrand (id).GetProductCategory (pc)
);
}
[AcceptVerbs("GET")]
public ActionResult Product (string id, string pc, string pref)
{
Product p = null;
ViewData ["BrandName"] = id;
ViewData ["ProdCatRef"] = pc;
ViewData ["ProdRef"] = pref;
Catalog cat = CatalogManager.GetCatalog ();
if (cat == null) {
ViewData ["Message"] = "Catalog introuvable";
ViewData ["RefType"] = "Catalog";
return View ("ReferenceNotFound");
}
Brand b = cat.GetBrand (id);
if (b == null) {
ViewData ["RefType"] = "Brand";
return View ("ReferenceNotFound");
}
ProductCategory pcat = b.GetProductCategory (pc);
if (pcat == null) {
ViewData ["RefType"] = "ProductCategory";
return View ("ReferenceNotFound");
}
ViewData ["ProdCatName"] = pcat.Name;
p = pcat.GetProduct (pref);
if (p.CommandForm==null)
p.CommandForm = b.DefaultForm;
return View ((p is Service)?"Service":"Product", p);
}
public ActionResult Command()
{
return View ();
}
[HttpPost]
[Authorize]
public ActionResult Command(FormCollection collection)
{
try {
// get files from the request
string fnre = "[A-Za-z0-9~\\-.]+";
HttpFileCollectionBase hfc = Request.Files;
foreach (String h in hfc.AllKeys)
{
if (!Regex.Match(hfc[h].FileName,fnre).Success)
{
ViewData ["Message"] = "File name refused";
ModelState.AddModelError(
h,
string.Format(
"The file name {0} dosn't match an acceptable file name {1}",
hfc[h].FileName,fnre))
;
return View(collection);
}
}
foreach (String h in hfc.AllKeys)
{
// TODO Limit with hfc[h].ContentLength
hfc[h].SaveAs(Path.Combine(FileSystemController.BaseDir,hfc[h].FileName));
}
if (Session["Basket"]==null)
Session["Basket"]=new List<Commande>();
List<Commande> basket = Session["Basket"] as List<Commande>;
// Add specified product command to the basket,
basket.Add(new Commande(collection));
return View (collection);
} catch (Exception e) {
ViewData ["Message"] = "Exception:"+e.Message;
return View (collection);
}
}
}
}

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Yavsc;
namespace Yavsc.Controllers
{
public class HomeController : Controller
{
// Site name
private static string name = null;
/// <summary>
/// Gets or sets the site name.
/// </summary>
/// <value>The name.</value>
[Obsolete("Use YavscHelpers.SiteName insteed.")]
public static string Name {
get {
if (name == null)
name = WebConfigurationManager.AppSettings ["Name"];
return name;
}
}
// Administrator email
private static string admail =
WebConfigurationManager.AppSettings ["AdminEmail"];
/// <summary>
/// Gets the Administrator email.
/// </summary>
/// <value>The admail.</value>
public static string Admail {
get {
return admail;
}
}
private static string owneremail = null;
/// <summary>
/// Gets or sets the owner email.
/// </summary>
/// <value>The owner email.</value>
public static string OwnerEmail {
get {
if (owneremail == null)
owneremail = WebConfigurationManager.AppSettings.Get ("OwnerEMail");
return owneremail;
}
set {
owneremail = value;
}
}
public ActionResult Index ()
{
InitCatalog ();
ViewData ["Message"] = string.Format(T.GetString("Welcome")+"({0})",GetType ().Assembly.FullName);
return View ();
}
public void InitCatalog() {
CultureInfo culture = null;
string defaultCulture = "fr";
if (Request.UserLanguages.Length > 0) {
try {
culture = new CultureInfo (Request.UserLanguages [0]);
}
catch (Exception e) {
ViewData ["Message"] = e.ToString ();
culture = CultureInfo.CreateSpecificCulture(defaultCulture);
}
}
else culture = CultureInfo.CreateSpecificCulture(defaultCulture);
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
string lcd = Server.MapPath ("./locale");
Mono.Unix.Catalog.Init("i8n1", lcd );
}
public ActionResult AOEMail (string reason, string body)
{
// requires valid owner and admin email?
using (System.Net.Mail.MailMessage msg = new MailMessage(owneremail,admail,"Poke : "+reason,body))
{
using (System.Net.Mail.SmtpClient sc = new SmtpClient())
{
sc.Send (msg);
return View ();
}
}
}
}
}

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Net.Mail;
using Yavsc;
using System.Globalization;
namespace Yavsc
{
public class T
{
public static string GetString(string msgid)
{
return Mono.Unix.Catalog.GetString (msgid);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…