Click here to Skip to main content
12,697,076 members (26,362 online)
Click here to Skip to main content

Stats

16.5K views
961 downloads
21 bookmarked
Posted

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.bak
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
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
__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
Scripts
ServerCapri.svc
Views
Capri
Home
Shared
__TemplateIcon.ico
favicon.ico
ProjectName.Windows
Controls
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
SignumFramework2ClientServer.zip
__TemplateIcon.ico
WizardProjectName
Test
Properties
WizardProjectName
Isolated
Properties
SignumFramework.pfx
TraceAndTestImpact.testsettings
SignumFramework2Setup.msi
.gitignore
README.md
Southwind.vssscc
Southwind
Southwind.Entities
Properties
Southwind.Load
Properties
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
Scripts
ServerSouthwind.svc
Views
Home
Shared
Southwind
favicon.ico
Southwind.Windows
Controls
Properties
Southwind.bak
#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Collections.Specialized;
using Signum.Utilities;
using Signum.Entities.DynamicQuery;
using Signum.Web.Properties;
using Signum.Engine.DynamicQuery;
using Signum.Entities;
using System.Web;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using System.Text.RegularExpressions;
using Signum.Engine;
#endregion

namespace Signum.Web
{
    public class FindOptionsModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            FindOptions fo = new FindOptions();

            NameValueCollection parameters = controllerContext.HttpContext.Request.Params;

            if (parameters.AllKeys.Any(name => !name.HasText()))
                throw new Exception("Incorrect URL: " + controllerContext.HttpContext.Request.Url.ToString());

            string webQueryName = "";
            object rawValue = bindingContext.ValueProvider.GetValue("webQueryName").TryCC(vp => vp.RawValue);
            if (rawValue.GetType() == typeof(string[]))
                webQueryName = ((string[])rawValue)[0];
            else 
                webQueryName = (string)rawValue;

            if (!webQueryName.HasText())
                throw new InvalidOperationException("webQueryName not provided");

            fo.QueryName = Navigator.ResolveQueryName(webQueryName);

            QueryDescription queryDescription = DynamicQueryManager.Current.QueryDescription(fo.QueryName);

            fo.FilterOptions = ExtractFilterOptions(controllerContext.HttpContext, queryDescription);
            fo.OrderOptions = ExtractOrderOptions(controllerContext.HttpContext, queryDescription);
            fo.ColumnOptions = ExtractColumnsOptions(controllerContext.HttpContext, queryDescription);

            if (parameters.AllKeys.Contains("allowMultiple"))
            {
                bool aux;
                if (bool.TryParse(parameters["allowMultiple"], out aux))
                    fo.AllowMultiple = aux;
            }

            if (parameters.AllKeys.Contains("async"))
            {
                bool aux;
                if (bool.TryParse(parameters["async"], out aux))
                    fo.Async = aux;
            }

            if (parameters.AllKeys.Contains("filterMode"))
            {
                FilterMode mode = parameters["filterMode"].ToEnum<FilterMode>();
                if (mode == FilterMode.AlwaysHidden || mode == FilterMode.OnlyResults)
                {
                    if (controllerContext.HttpContext.Request.QueryString.AllKeys.Contains("filterMode"))
                        throw new InvalidOperationException("QueryString cannot contain FilterMode set to Always Hidden or Only Results");
                }
                fo.FilterMode = mode;
            }

            if (parameters.AllKeys.Contains("columnMode"))
                fo.ColumnOptionsMode = parameters["columnMode"].ToEnum<ColumnOptionsMode>();

            if (parameters.AllKeys.Contains("create"))
                fo.Create = bool.Parse(parameters["create"]);

            if (parameters.AllKeys.Contains("view"))
                fo.View = bool.Parse(parameters["view"]);

            if (parameters.AllKeys.Contains("top"))
            {
                int aux;
                if (int.TryParse(parameters["top"], out aux))
                    fo.Top = aux;
            }

            if (parameters.AllKeys.Contains("searchOnLoad"))
                fo.SearchOnLoad = bool.Parse(parameters["searchOnLoad"]);

            return fo;
        }

        //name1,operation1,value1;name2,operation2,value2; being values CSV encoded
        static Regex filterRegex = new Regex(
            "(?<token>[^;,]+),(?<op>[^;,]+),(?<value>'(?:[^']+|'')*'|[^;,]*);".Replace('\'', '"'),
            RegexOptions.Multiline | RegexOptions.ExplicitCapture);

        public static List<FilterOption> ExtractFilterOptions(HttpContextBase httpContext, QueryDescription queryDescription)
        {
            List<FilterOption> result = new List<FilterOption>();

            NameValueCollection parameters = httpContext.Request.Params;
            
            string field = parameters["filters"];

            if (!field.HasText())
                return result;

            var matches = filterRegex.Matches(field).Cast<Match>();

            return matches.Select(m =>
            {
                string name = m.Groups["token"].Value;
                var token = QueryUtils.Parse(name, queryDescription);
                return new FilterOption
                {
                    ColumnName = name,
                    Token = token,
                    Operation = EnumExtensions.ToEnum<FilterOperation>(m.Groups["op"].Value),
                    Value = Convert(DecodeValue(m.Groups["value"].Value), token.Type),
                    //Frozen = frozen,
                };
            }).ToList();
        }

        //order1,-order2; minus symbol indicating descending
        static Regex orderRegex = new Regex(
            "(?<token>-?[^;,]+);".Replace('\'', '"'),
            RegexOptions.Multiline | RegexOptions.ExplicitCapture);

        public static List<OrderOption> ExtractOrderOptions(HttpContextBase httpContext, QueryDescription queryDescription)
        {
            List<OrderOption> result = new List<OrderOption>();

            NameValueCollection parameters = httpContext.Request.Params;
            string field = parameters["orders"];
            
            if (!field.HasText())
                return result;

            var matches = orderRegex.Matches(field).Cast<Match>();

            return matches.Select(m =>
            {
                var tokenCapture = m.Groups["token"].Value;
                OrderType orderType = tokenCapture.StartsWith("-") ? OrderType.Descending : OrderType.Ascending;
                string token = orderType == OrderType.Ascending ? tokenCapture : tokenCapture.Substring(1, tokenCapture.Length - 1);
                return new OrderOption
                {
                    Token = QueryUtils.Parse(token, queryDescription),
                    OrderType = orderType
                };
            }).ToList();
        }

        //columnName1,displayName1;columnName2,displayName2; being displayNames CSV encoded
        static Regex columnRegex = new Regex(
            "(?<token>[^;,]+)(,(?<name>'(?:[^']+|'')*'|[^;,]*))?;".Replace('\'', '"'),
            RegexOptions.Multiline | RegexOptions.ExplicitCapture);

        public static List<ColumnOption> ExtractColumnsOptions(HttpContextBase httpContext, QueryDescription queryDescription)
        {
            List<ColumnOption> result = new List<ColumnOption>();

            NameValueCollection parameters = httpContext.Request.Params;
            string field = parameters["columns"];
            
            if (!field.HasText())
                return result;

            var matches = columnRegex.Matches(field).Cast<Match>();

            return matches.Select(m =>
            {
                var colName = m.Groups["token"].Value;
                var displayCapture = m.Groups["name"].Captures;
                return new ColumnOption
                {
                    ColumnName = colName,
                    DisplayName = displayCapture.Count > 0 ? DecodeValue(m.Groups["name"].Value) : colName
                };
            }).ToList();
        }

        static string DecodeValue(string s)
        {
            if (s.StartsWith("\""))
            {
                if (!s.EndsWith("\""))
                    throw new FormatException("Value starts by quotes but not ends with quotes".Formato(s));

                return s.Substring(1, s.Length - 2).Replace("\"\"", "\"");
            }
            else
            {
                return s;
            }
        }

        internal static object Convert(string value, Type type)
        {
            if (type.UnNullify() == typeof(bool))
            {
                string[] vals = ((string)value).Split(',');
                return (vals[0] == "true" || vals[0] == "True");
            }
            if (type.UnNullify() == typeof(DateTime))
            {
                if (value.HasText())
                    return DateTime.Parse(value).FromUserInterface();
                return null;
            }
            if (type.UnNullify().IsLite())
                return TypeLogic.ParseLite(Reflector.ExtractLite(type), value);

            return ReflectionTools.Parse(value, 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...

You may also be interested in...

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