Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Signum Framework Tutorials Part 2 – Southwind Logic

, 15 Nov 2012 LGPL3
In this part, we will focus on writing business logic, LINQ queries and explain inheritance
Northwind.zip
Northwind.bak
SignumFramework2.0-src.zip
signumframework-signumframework-c6436e1
.gitignore
Local.testsettings
README.md
Signum.Engine
ClassDiagram1.cd
Connection
DynamicQuery
Engine
Linq
ExpressionVisitor
Meta
Properties
Schema
Schema.cd
SchemaBuilder
SignumFramework.pfx
Signum.Entities
Attributes.cd
Basics
ClassDiagram1.cd
Diagram.cd
DynamicQuery
Tokens
Patterns
Properties
Reflection
Services
SignumFramework.pfx
Signum.Framework.vsmdi
Signum.Test
ClassDiagram1.cd
LinqProvider
Properties
Settings.settings
Signum.Utilities
DataStructures
IntervalDictionaries
ExpressionTrees
Properties
Reflection
SignumFramework.pfx
Synchronization
Signum.Web
ButtonBar
ControllerAttributes
Facades
HtmlHelpers
JSRenderer
LineHelpers
Lines
Mappings
PortableAreas
Repositories
Properties
Signum
Content
Controllers
Images
asc.gif
calendar.png
desc.gif
lineButtons.gif
sign_error.gif
Models
Scripts
Views
Widgets
SignumFramework.pfx
TypeContext
Widgets
Signum.Windows
Basics
Controls
ColorUtils
Converters
DynamicQuery
EntityControls
Facades
Fluent
Images
admin.png
alert.png
calendar.png
cancel.png
close.png
entity.png
find.png
forbidden.png
newColumn.png
newFilter.png
note.png
ok.png
pin.png
reload.png
save.png
star.png
Localization
MarkupExtensions
Properties
SignumFramework.pfx
Themes
Utilities
Widgets
SignumFrameworkSetup
SignumFrameworkSetup.vdproj
logo.ico
signumFramework2.0.jpg
Snippets
DroidSansMono.ttf
RazorSingleFileGenerator.vsix
Signum.Fonts.vssettings
T4template
entity.snippet
entityWithName.snippet
expressionMethod.snippet
expressionMethodQuery.snippet
expressionProperty.snippet
field.snippet
fieldCreacion.snippet
fieldEuro.snippet
fieldInicioFin.snippet
fieldString.snippet
fiff.snippet
propiedad.snippet
tran.snippet
Template
EntityControlTemplate
MyTemplate.vstemplate
SignumEntityControl.zip
__TemplateIcon.ico
Template
MyTemplate.vstemplate
ProjectName.Entities
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
ProjectName.Load
MyTemplate.vstemplate
Properties
Settings.settings
__TemplateIcon.ico
ProjectName.Logic
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
ProjectName.Web
Code
Content
smoothness
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Controllers
Global.asax
MyTemplate.vstemplate
Properties
Settings.settings
Scripts
ServerCapri.svc
Views
Capri
Home
Shared
__TemplateIcon.ico
favicon.ico
ProjectName.Windows
Controls
MyTemplate.vstemplate
Properties
Settings.settings
__TemplateIcon.ico
SignumFramework2ClientServer.zip
__TemplateIcon.ico
WizardProjectName
Test
Properties
Settings.settings
WizardProjectName
Isolated
Properties
SignumFramework.pfx
TraceAndTestImpact.testsettings
SignumFramework2Setup.zip
SignumFramework2Setup.msi
Southwind-Part2-Logic.zip
.gitignore
README.md
Southwind.vssscc
Southwind
Southwind.Entities
Properties
Southwind.Load
Properties
Settings.settings
Southwind.Logic
Properties
Southwind.Web
Code
Content
smoothness
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Controllers
Global.asax
Properties
Settings.settings
Scripts
ServerSouthwind.svc
Views
Home
Shared
Southwind
favicon.ico
Southwind.Windows
Controls
Properties
Settings.settings
Southwind.zip
Southwind.bak
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Collections.ObjectModel;
using System.Reflection;
using System.CodeDom;
using Microsoft.CSharp;
using System.IO;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using Signum.Utilities.DataStructures;

namespace Signum.Utilities.ExpressionTrees
{
    public static class CSharpRenderer
    {
        public static string GenerateCSharpCode(this Expression expression, string[] importedNamespaces)
        {
            return new CSharpTreeVisitor { ImportedNamespaces = importedNamespaces }.VisitReal(expression);
        }

        public static string GenerateCSharpCode(this Expression expression)
        {
            return new CSharpTreeVisitor().VisitReal(expression);
        }

        /// <summary>
        /// Dummy method to collapse un collection o object initializer in one single line
        /// </summary>
        public static T Collapse<T>(this T obj)
        {
            return obj;
        }

        /// <summary>
        /// Allows to write string litterals in an expression tree, be carefull with parenthesis
        /// </summary>
        public static T Literal<T>(string literal)
        {
            return default(T);
        }

        static Dictionary<TypeCode, string> basicTypes = new Dictionary<TypeCode, string>
        {
            { TypeCode.Boolean, "bool"}, 
            { TypeCode.Byte, "byte"}, 
            { TypeCode.Char, "char"}, 
            { TypeCode.Decimal, "decimal"}, 
            { TypeCode.Double, "double"},  
            { TypeCode.Int16, "short"}, 
            { TypeCode.Int32, "int"}, 
            { TypeCode.Int64, "long"}, 
            { TypeCode.SByte, "sbyte"}, 
            { TypeCode.Single, "float"},
            { TypeCode.String, "string"},
            { TypeCode.UInt16, "ushort"},
            { TypeCode.UInt32, "uint"},
            { TypeCode.UInt64, "ulong"},
        };


        public static string ParameterName(this ParameterInfo pi)
        {
            return "{0} {1}".Formato(pi.ParameterType.TypeName(), pi.Name);
        }

        public static string PropertyName(this PropertyInfo pi)
        {
            return "{0} {1}".Formato(pi.PropertyType.TypeName(), pi.Name);
        }

        public static string FieldName(this FieldInfo pi)
        {
            return "{0} {1}".Formato(pi.FieldType.TypeName(), pi.Name);
        }

        public static string MethodName(this MethodInfo method)
        {
            if (method.IsGenericMethod)
                return "{0}<{1}>".Formato(method.Name.Split('`')[0], method.GetGenericArguments().ToString(t => TypeName(t), ","));

            return method.Name;
        }

        public static string MethodSignature(this MethodInfo method)
        {
            return "{0} {1}({2})".Formato(
                method.ReturnType.TypeName(),
                method.MethodName(),
                method.GetParameters().ToString(p => p.ParameterName(), ", "));
        }

        public static string MemberName(this MemberInfo mi)
        {
            return new Switch<MemberInfo, string>(mi)
                .Case<PropertyInfo>(p => p.PropertyName())
                .Case<FieldInfo>(p => p.FieldName())
                .Case<MethodInfo>(p => p.MethodName())
                .Default("??"); 
        }

        public static string TypeName(this Type type)
        {
            if (type == typeof(object))
                return "object";

            if (type.IsEnum)
                return type.Name; 

            string result = basicTypes.TryGetC(Type.GetTypeCode(type));
            if (result != null)
                return result;

            if (type.IsArray)
                return "{0}[{1}]".Formato(type.GetElementType().TypeName(), new string(',', type.GetArrayRank() - 1));

            Type ut = Nullable.GetUnderlyingType(type);
            if (ut != null)
                return "{0}?".Formato(ut.TypeName());

            if (type.IsGenericType)
            {
                if (type.IsGenericTypeDefinition)
                    return "{0}<{1}>".Formato(type.Name.Split('`')[0], type.GetGenericArguments().ToString(_ => "", ","));

                return "{0}<{1}>".Formato(type.Name.Split('`')[0], type.GetGenericArguments().ToString(t => TypeName(t), ","));

            }

            return type.Name;
        }

        public static string CleanIdentifiers(this string str)
        {
            return str
                .Replace("<>f__AnonymousType", "α")
                .Replace("<>h__TransparentIdentifier", "τ");
        }

        static CSharpCodeProvider provider = new CSharpCodeProvider();
        static CodeGeneratorOptions options = new CodeGeneratorOptions(); 
        
        public static string Value(object valor, Type type, string[] importedNamespaces)
        {
             StringBuilder sb = new StringBuilder();
             using (StringWriter w = new StringWriter(sb))
             {
                 provider.GenerateCodeFromExpression(GetRightExpressionForValue(valor, type, importedNamespaces), w, options);
                 return w.ToString();
             }
        }

        public static CodeExpression GetRightExpressionForValue(object value, Type type, string[] importedNamespaces)
        {
            if (value is DBNull || value == null)
            {
                return new CodePrimitiveExpression(null);
            }

            if (type == typeof(decimal))
            {
                return new CodePrimitiveExpression(value);
            }
       
            if ((type == typeof(string)) && (value is string))
            {
                return new CodePrimitiveExpression((string)value);
            }
            if (type.IsPrimitive)
            {
                if (type != value.GetType())
                {
                    TypeConverter converter = TypeDescriptor.GetConverter(type);
                    if (converter.CanConvertFrom(value.GetType()))
                    {
                        return new CodePrimitiveExpression(converter.ConvertFrom(value));
                    }
                }
                return new CodePrimitiveExpression(value);
            }
            if (type.IsArray)
            {
                Array array = (Array)value;
                CodeArrayCreateExpression expression = new CodeArrayCreateExpression();
                expression.CreateType = TypeReference(type.GetElementType(), importedNamespaces);
                if (array != null)
                {
                    foreach (object obj2 in array)
                    {
                        expression.Initializers.Add(GetRightExpressionForValue(obj2, type.GetElementType(), importedNamespaces));
                    }
                }
                return expression;
            }
            TypeConverter converter2 = null;
            converter2 = TypeDescriptor.GetConverter(type);
            if (type.IsEnum && (value is string))
            {
                value = converter2.ConvertFromString(value.ToString());
            }
            if (converter2 != null)
            {
                InstanceDescriptor descriptor = null;
                if (converter2.CanConvertTo(typeof(InstanceDescriptor)))
                {
                    descriptor = (InstanceDescriptor)converter2.ConvertTo(value, typeof(InstanceDescriptor));
                }
                if (descriptor != null)
                {
                    if (descriptor.MemberInfo is FieldInfo)
                    {
                        return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(TypeReference( descriptor.MemberInfo.DeclaringType, importedNamespaces)), descriptor.MemberInfo.Name);
                    }
                    if (descriptor.MemberInfo is PropertyInfo)
                    {
                        return new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(TypeReference(descriptor.MemberInfo.DeclaringType, importedNamespaces)), descriptor.MemberInfo.Name);
                    }
                    object[] objArray = new object[descriptor.Arguments.Count];
                    descriptor.Arguments.CopyTo(objArray, 0);
                    CodeExpression[] expressionArray = new CodeExpression[objArray.Length];
                    if (descriptor.MemberInfo is MethodInfo)
                    {
                        ParameterInfo[] parameters = ((MethodInfo)descriptor.MemberInfo).GetParameters();
                        for (int i = 0; i < objArray.Length; i++)
                        {
                            expressionArray[i] = GetRightExpressionForValue(objArray[i], parameters[i].ParameterType, importedNamespaces);
                        }
                        CodeMethodInvokeExpression expression4 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(descriptor.MemberInfo.DeclaringType.FullName), descriptor.MemberInfo.Name, new CodeExpression[0]);
                        foreach (CodeExpression expression5 in expressionArray)
                        {
                            expression4.Parameters.Add(expression5);
                        }
                        return expression4;
                    }
                    if (descriptor.MemberInfo is ConstructorInfo)
                    {
                        ParameterInfo[] infoArray2 = ((ConstructorInfo)descriptor.MemberInfo).GetParameters();
                        for (int j = 0; j < objArray.Length; j++)
                        {
                            expressionArray[j] = GetRightExpressionForValue(objArray[j], infoArray2[j].ParameterType, importedNamespaces);
                        }
                        CodeObjectCreateExpression expression6 = new CodeObjectCreateExpression(descriptor.MemberInfo.DeclaringType.FullName, new CodeExpression[0]);
                        foreach (CodeExpression expression7 in expressionArray)
                        {
                            expression6.Parameters.Add(expression7);
                        }
                        return expression6;
                    }
                }
            }
            return null;
        }

        public static CodeTypeReference TypeReference(Type type, string[] importedNamespaces)
        {
            if (!type.IsGenericType && !type.IsArray && importedNamespaces != null && importedNamespaces.Contains(type.Namespace))
                return new CodeTypeReference(type.Name);
            else
                return new CodeTypeReference(type); ;
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

Olmo del Corral
Software Developer (Senior) Signum Software
Spain Spain
I'm Computer Scientist, one of the founders of Signum Software, and the lead developer behind Signum Framework.
 
www.signumframework.com
 
I love programming in C#, Linq, Compilers, Algorithms, Functional Programming, Computer Graphics, Maths...

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 15 Nov 2012
Article Copyright 2011 by Olmo del Corral
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid