Tuesday, December 15, 2015

IE 9 Compatibility

While searching for ways to ensure IE 9 compatibility in HTML pages, some articles suggest that

Just having <!DOCTYPE html> at the very top of the page with nothing preceding it should be enough to make IE9 use standards mode.

While this is true, I found out that even after having the document type declared as above, few pages in my MVC application were not being rendered properly. While searching more I came across this post

http://stackoverflow.com/questions/27571231/x-ua-compatible-not-working-in-ie-9-for-intranet-sites

Which says that console.log puts IE in quirks mode inspite of doctype and meta tags referring to IE 9. And commenting out all console.log statements really has fixed this issue for me.


Thursday, December 10, 2015

Javascript multithreading

It is interesting to know that multithreading is supported in javascript, though it has to source a different file it is still a relief for very cpu intesive UI operations

This is a demo code for the webworker

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<br><br>

<script>
var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
    }
}

function stopWorker() {
    w.terminate();
    w = undefined;
}
</script>

</body>
</html>
 
and the demo_worker.js contains
 
var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();
 

Thursday, November 26, 2015

C# Expression in Dynamic Linq Queries

Currently dynamic linq operators created using System.Linq.Expressions.Expression object do not support sql "IN" operator, there is a way to implement it however, just add a simple expression building tree like in the example here:

pe = Expression.Parameter(typeof(myClient), "clt"); PropertyInfo propertyInfo = typeof(myClient).GetProperty("PropertyFieldName"); MemberExpression m = Expression.MakeMemberAccess(pe, propertyInfo); ConstantExpression c = Expression.Constant("SearchFrase", typeof(string)); MethodInfo mi = typeof(string).GetMethod("Contains", new Type[] { typeof(string) }); e1 = exp.Expression.Call(m, mi, c);


Reference: 

http://stackoverflow.com/questions/6907103/how-to-create-a-dynamic-contains-or-like-expression-to-be-used-with-linq-again



Friday, November 13, 2015

Default boolean value in Entity Framework

To set a default value to bit column in EF edit the migration file manaully and add defaultvaluesql parameter like

AddColumn("Jobs", "IsAdvertisingRequired", c => c.Boolean(nullable: false, defaultValueSql: "0"));
 
 Reference: http://stackoverflow.com/questions/5567567/default-bool-to-false-when-null-in-database-with-entity-framework-4-1-code-first

ORM performance

The article below explains some scenarios where Linq-2-SQL can be slower than expected and a easy fix for them.

http://samsaffron.com/archive/2011/03/30/How+I+learned+to+stop+worrying+and+write+my+own+ORM

Also was attracted by the idea of single file ORM

https://github.com/FransBouma/Massive

Thursday, November 12, 2015

Re Linq Provider - could be great fun to implement

While linq is definitely a powerful framework to query against databases, it is also somewhat complex to understand and use (and even more difficult if we are writing custom providers).

Writing a custom Re Linq provider seems to be a little simpler process, however there are very few help articles at the moment. I have found one very useful article on this topic and hence just keeping a note to myself..

http://fairwaytech.com/2013/03/writing-a-custom-linq-provider-with-re-linq/

Monday, November 9, 2015

Creating Northwind sample database on SQL 2014

A while ago there was a situation where I needed the northwind database on SQL 2014 instance, which is originally available in SQL 2000 script format at

https://www.microsoft.com/en-us/download/details.aspx?id=23654

But the sp_dboptions system sp has been deprecated in SQL 2012 onwards so I needed to replace the following lines

--exec sp_dboption 'Northwind','trunc. log on chkpt.','true'
--exec sp_dboption 'Northwind','select into/bulkcopy','true'

with

ALTER DATABASE Northwind SET RECOVERY SIMPLE 
ALTER DATABASE Northwind SET RECOVERY BULK_LOGGED

And it works like a charm :)

More reference about the new commands can be found at http://beyondrelational.com/modules/2/blogs/28/Posts/15429/replacement-for-system-stored-procedure-spdboption-in-sql-server-2012-denali.aspx

Friday, November 6, 2015

Very good tool to copy HTML snippets

It was always a tedious task to copy HTML along with stylesheet to another page, but with this extension this is as simple as a click, however I would have liked to see an option to add HTML inline.


https://chrome.google.com/webstore/detail/snappysnippet/blfngdefapoapkcdibbdkigpeaffgcil



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 

Tuesday, August 25, 2015

Knockout custom bindings and value accessors

Custom bindings in knockout enable us to specify custom knockout parameters in data-bind attribute. They are quite useful to implement custom functionality across the site. Here are more references to these attributes

http://knockoutjs.com/documentation/custom-bindings.html
http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html

Friday, August 14, 2015

ANTLR4 installation in a visual studio project

ANTLR is a very interesting parser for writing custom compilers. After fumbling a bit on my own to install it in the dev, finally I could get it done after following steps in the post below. Though the post makes it very easy to install, understading how to write a compiler is significantly more complex.

https://groups.google.com/forum/#!topic/antlr-discussion/Gh_P6IiDrKU

To help us there are some good antlr projects available to download, one mentioned below is quite interesting

https://github.com/ChristianWulf/CSharpGrammar 

Debugging in Linq

The post below explains some tools which are quite handy when debuggin LINQ to Entity statements, but I have used DBContext instead of ObjectContext connection

http://blog.falafel.com/debugging-in-linq-hell/

Also, to make internal classes visible to Linq Pad use an assembly attribute.
 



[assembly: InternalsVisibleTo("LINQPadQuery")]


http://stackoverflow.com/questions/14354157/make-internal-classes-visible-to-others-assemblies

but if they are signed, this won't work

http://forum.linqpad.net/discussion/747/internalsvisibleto-on-datacontext-in-signed-assembly


Also, there is an extention in visual studio to connect to linqpad

https://github.com/nbasakuragi/LINQBridgeVs 

Secure micro services using jwt and ocelot

  Secure Microservices Using JWT With Ocelot in .NET Core (code-maze.com)