Wednesday, November 4, 2015

Disable bundling in MVC

I was searching for a while to disable bundling in MVC in debug mode to be able to debug the files quickly and I ended up on these posts in google search, it is definitely interesting to know these customizations.

http://blog.kurtschindler.net/disabling-bundling-and-minification-in-asp-net-4-5mvc-4/

https://gist.github.com/zaus/7436601

http://stackoverflow.com/questions/20397452/custom-bundle-in-mvc-4-is-not-rendered

There might be many more articles on the web, but this was just a quick search..

Tuesday, October 20, 2015

Count number of selectors in a css file

IE9 allows only 4095 css selectors, hence we need to know number of css selectors in a file

http://stackoverflow.com/questions/5228459/count-number-of-selectors-in-a-css-file

Also, there are some very good tools like Dust-Me Data (firefox) or CSS Remove and Combine (Chrome) which give a statistics about number of used and unused selectors.


Monday, October 19, 2015

Custom Linq Provider: Enabling a Data Source for LINQ Querying

These are msdn articles explaining the steps in detail about building a custom linq query provider, but be prepared to run through a highly complex framework before reading them.

https://msdn.microsoft.com/en-us/library/bb882640.aspx
http://blogs.msdn.com/b/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx

http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx

This a really helful source  code of sample project which implements few custom linq providers for different data source types sql ce, mysql, access, sqllite, etc.

http://iqtoolkit.codeplex.com/

The source code above works with sql 2005, however current sql versions do not support .mdf file attachments through code, hence after migrating the Northwind database to SQL 2014 version, I had to change DbEntityProvider.From method as below

if (provider == null)
            {
                var clower = connectionString.ToLower();
                // try sniffing connection to figure out provider
                if (clower.Contains(".mdb") || clower.Contains(".accdb"))
                {
                    provider = "IQToolkit.Data.Access";
                }
                else if (clower.Contains(".sdf"))
                {
                    provider = "IQToolkit.Data.SqlServerCe";
                }
                else if (clower.Contains(".sl3") || clower.Contains(".db3"))
                {
                    provider = "IQToolkit.Data.SQLite";
                }
                else if (clower.Contains(".mdf"))
                {
                    provider = "IQToolkit.Data.SqlClient";
                }
                else
                {
                    //throw new InvalidOperationException(string.Format("Query provider not specified and cannot be inferred."));
                    provider = "IQToolkit.Data.SqlServer";
                }

And SqlServerQueryProvider class like:

public static string GetConnectionString(string connectionString)
        {
            //return string.Format(@"Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=true;AttachDbFilename='{0}'", databaseFile);
            //return string.Format(@"Data Source=.\QLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=true;AttachDbFilename='{0}'", databaseFile);
            return connectionString;
        }

Also I had to pass the actual connection string to  DbEntityProvider.From method like:

var provider = DbEntityProvider.From("Data Source=<SQL Server Name>;Initial Catalog=Northwind;Integrated Security=True", "Test.NorthwindWithAttributes");

Thursday, October 1, 2015

Entity Framework Default database values

Entity framework can be modified to have a default value in database as opposed to in EDMX file using the downloaded code in this blog. Good article really!

http://www.codeproject.com/Articles/89191/Entity-Framework-EDMX-Modifier-Correct-Default-V

Productivity Tools

This is an interesting article about drawbacks productivity tools, but part which I liked most is where the author directs us to technologies which possibly will be very important in the future.

http://blog.ploeh.dk/2013/02/04/BewareofProductivityTools/

Thursday, September 24, 2015

ORM mappers

There are a few ORM mappers available other than the Enitty Framework, however I have tested none of them yet.

http://stackoverflow.com/questions/47239/how-can-i-generate-database-tables-from-c-sharp-classes

https://github.com/StackExchange/dapper-dot-net

http://mybatis.github.io/mybatis-3/dynamic-sql.html

http://www.codeproject.com/Articles/27830/SQL-Class-Shell-Generator

I have modified the class in stackoverflow post #1 as below

public class TableClass
    {
        static int AliasIndex = 0;
        private List<ColumnInfo> _columnInfo = new List<ColumnInfo>();
        private string _className = String.Empty;
        private string _tableAlias = String.Empty;
        private string _fkColumnName = String.Empty;

        private Dictionary<Type, String> dataMapper
        {
            get
            {
                // Add the rest of your CLR Types to SQL Types mapping here
                Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();
                dataMapper.Add(typeof(int), "BIGINT");
                dataMapper.Add(typeof(string), "NVARCHAR(MAX)");
                dataMapper.Add(typeof(bool), "BIT");
                dataMapper.Add(typeof(DateTime), "DATETIME");
                dataMapper.Add(typeof(float), "FLOAT");
                dataMapper.Add(typeof(decimal), "DECIMAL(18,0)");
                dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER");

                return dataMapper;
            }
        }

        public List<ColumnInfo> Fields
        {
            get { return this._columnInfo; }
            set { this._columnInfo = value; }
        }

        public string ClassName
        {
            get { return this._className; }
            set { this._className = value; }
        }

        public TableClass(Type t)
        {
            this._className = t.Name;
            AliasIndex++;
            _tableAlias = this.ClassName + AliasIndex;
            foreach (FieldInfo p in t.GetFields())
            {
                ColumnInfo field = null;
                if (dataMapper.ContainsKey(p.FieldType))
                {
                    field = new ColumnInfo
                    {
                        Key = p.Name,
                        SystemType = p.FieldType,
                        IsForeignKey = false
                    };
                }
                else
                {
                    field = new ColumnInfo
                    {
                        Key = p.Name + "ID",
                        SystemType = p.FieldType,
                        IsForeignKey = true,
                        Table = new TableClass(p.FieldType.UnderlyingSystemType)
                    };

                }
                this.Fields.Add(field);
            }
        }

        public TableClass(Type t, string ForeignKeyColumnName)
            : this(t)
        {
            this._fkColumnName = ForeignKeyColumnName;
        }

        public string CreateTableScript()
        {
            StringBuilder script = new StringBuilder();
            StringBuilder scriptsToAppend = new StringBuilder();

            script.AppendLine("CREATE TABLE " + this.ClassName);
            script.AppendLine("(");
            List<string> fields = new List<string>();
            fields.Add("\t ID UNIQUEIDENTIFIER");

            foreach (ColumnInfo col in this._columnInfo)
            {
                if (!col.IsForeignKey)
                {
                    fields.Add("\t " + col.Key + " " + dataMapper[col.SystemType]);
                }
                else
                {
                    fields.Add("\t " + col.Key + "ID UNIQUEIDENTIFIER");
                    TableClass tc = col.Table;
                    scriptsToAppend.Append(tc.CreateTableScript());
                    scriptsToAppend.AppendLine(string.Empty);
                    // We have a FK Relationship!
                    scriptsToAppend.Append("GO");
                    scriptsToAppend.AppendLine(string.Empty);
                    scriptsToAppend.Append("ALTER TABLE " + this.ClassName + " WITH NOCHECK");
                    scriptsToAppend.AppendLine(string.Empty);
                    scriptsToAppend.Append("ADD CONSTRAINT FK_" + tc.ClassName + "_" + this.ClassName + " FOREIGN KEY (" + col.Key + "ID) REFERENCES " + tc.ClassName + "(ID)");
                    scriptsToAppend.AppendLine(string.Empty);
                    scriptsToAppend.Append("GO");
                    scriptsToAppend.AppendLine(string.Empty);
                }
            }
            script.Append(string.Join(", ", fields));
            script.Append(Environment.NewLine);
            script.AppendLine(")");
            script.Append(scriptsToAppend.ToString());
            return script.ToString();
        }

        public string GetSelectColumnsScript()
        {

            StringBuilder script = new StringBuilder();
            List<TableClass> ChildTables = new List<TableClass>();
            List<string> fields = new List<string>();
            fields.Add("\t " + _tableAlias + ".ID");
            foreach (ColumnInfo col in _columnInfo)
            {
                if (!col.IsForeignKey)
                {
                    fields.Add("\t " + _tableAlias + "." + col.Key);
                }
                else
                {
                    TableClass tc = col.Table;
                    script.Append(tc.GetSelectColumnsScript());
                    script.Append(Environment.NewLine);
                }
            }
            script.Append(string.Join(", ", fields));
            script.Append(Environment.NewLine);
            return script.ToString();
        }

        public string CreateSelectScript()
        {
            StringBuilder script = new StringBuilder();
            List<string> fields = new List<string>();
            script.Append("SELECT ");
            script.Append(Environment.NewLine);
            script.AppendLine(this.GetSelectColumnsScript());
            script.AppendLine("FROM " + this.ClassName + " AS " + _tableAlias);
            foreach (ColumnInfo col in _columnInfo)
            {
                if (col.IsForeignKey)
                {
                    TableClass tc = col.Table;
                    script.Append("INNER JOIN " + tc.ClassName + " AS " + tc._tableAlias);
                    script.Append("    ON " + _tableAlias + "." + tc.ClassName + "ID = " + tc._tableAlias + ".ID");
                    script.Append(Environment.NewLine);
                }
            }
            return script.ToString();
        }
    }
 

Sqlformatter.cs
protected void AddAlias(AliasedExpression aliasEx)
        {
            string name;
            if (!this.aliases.TryGetValue(aliasEx.Alias, out name))
            {
                name = ((IQToolkit.Data.Common.TableExpression)(aliasEx)).Name + this.aliases.Count;
                this.aliases.Add(aliasEx.Alias, name);
            }
        }
protected virtual void AddAliases(Expression expr)
             if (ax != null)
            {
                this.AddAlias(ax);
            }
 

Tuesday, September 15, 2015

Creating class properties dynamically

The class below is exacly what I was looking for when I realised that I had to code too many classes in an Entity Framework project which uses dependency injection.

https://weblog.west-wind.com/posts/2012/Feb/08/Creating-a-dynamic-extensible-C-Expando-Object

Also, the blog below explains implementation of dynamic property accessor

http://omegacoder.com/?p=650 

Regex Email validation in c# dot net core

 Use this regex /^_?[a-zA-Z0-9]([a-zA-Z0-9]*[._+-])*[a-zA-Z0-9_]+@(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))*\.[A-...