Saturday, December 6, 2014

Is Perfect Square for BigInteger

For testing if an integer is a perfect square


   private bool IsPerfectSquare(BigInteger n)
   {
        
        var sqrt =  (BigInteger)Math.Round(Math.Exp(BigInteger.Log(n) / 2));
 return (sqrt * sqrt) == n;
    }
I took it from http://msdn.microsoft.com/en-us/library/dd268263(v=vs.110).aspx

Thursday, September 11, 2014

An Advantage of Using Current SynchronizationContext over Control.BeginInvoke

SynchronizationContext vs Control.BeginInvoke


Windows Forms and WPF framework do not allow modifications to UI elements and controls from a non-UI thread. So if a task thread wants to display a result on the UI or change a control to indicate state of some sort it has to somehow communicate with the UI thread and the UI thread should take care of displaying the UI updates, carry out the desired change to UI controls, etc.

There are two to accomplish this:

  • Capturing the SynchronizationContext as in the code snippet below which is assumed to part of a method in child class of the System.Windows.Form class:
      Task.Factory.StartNew(() =>
      {
        // update UI here
      }, this.cancelToken.Token
       , TaskCreationOptions.None
       , TaskScheduler.FromCurrentSynchronizationContext()
     );
    

  • Using Control.BeginInvok as in the code snippet below which also assumes to be with a child class of the the System.Windows.Form class:
    Task.Factory.StartNew(() =>
    {
        DoSomeWrok();
        Action updateUIDelegate = () =>{ UpdateUI();}; 
        /* ^^ a way of creating a delegate to be passed to BeginInvoke */
        this.BeginInvoke(updateUIDelegate); //will be execute on the UI thread.
        /* ^ this refers to the Form instance */
    }, this.cancelToken.Token
    );
    

    Notice in the above code we did not need to capture the current SynchronizationContext.

One Reason to Prefer Capturing Current SynchronizationContext:


Control.BeginInvok is not available in WPF. So if you are creating classes to be used in both Windows Forms and WPF then using SynchronizationContext is the portable way. Here is more from http://blogs.msdn.com/b/pfxteam/archive/2012/06/15/executioncontext-vs-synchronizationcontext.aspx:
We now have two different APIs for achieving the same basic operation, so how do I write my component to be agnostic of the UI framework?  By using SynchronizationContext.  SynchronizationContext provides a virtual Post method; this method simply takes a delegate and runs it wherever, whenever, and however the SynchronizationContext implementation deems fit.  Windows Forms provides the WindowsFormSynchronizationContext type which overrides Post to call Control.BeginInvoke.  WPF provides the DispatcherSynchronizationContext type which overrides Post to call Dispatcher.BeginInvoke.  And so on.  As such, I can now code my component to use SynchronizationContext instead of tying it to a specific framework.
I was curios how WindowsFormsSynchronizationContext mentioned in the article mentioned above implemented the Post method so I took a look at the code (reflected):


public override void Post(SendOrPostCallback d, object state)
{
 if (this.controlToSendTo != null)
 {
  this.controlToSendTo.BeginInvoke(d, new object[]
  {
   state
  });
 }
}

Tuesday, September 9, 2014

Rendering Partial View from C#

Rendering Partial View from Inside a Controller Action in C#:

Sometimes I find a need to a rendered HTML string from inside an action (a response to AJAX call for example).

The RenderPartialView function below assumes it's a member method of a class derived from the System.Web.Mvc.Controller class.

Function description: Renders the partial view and returns the generated Html. I think it's easier than returning the raw data and having jQuery generates the HTML. Params: partialViewFullPath - The path and extension to the partial view. for example, ~/Views/Controller/ViewName.cshtml    model - Almost always we expect a model Returns: HTML string generated by the the MVC framework itself.

   
public string RenderPartialView(string partialViewFullPath, object model){
    /* to avoid null ref exception when unit testing */
    if (HttpContext == null || HttpContext.Request == null)
    {
        return string.Empty;
    }
    if (string.IsNullOrEmpty(partialViewFullPath))
    {
        throw new ArgumentException("partialViewName");
    }
    ViewDataDictionary viewData = new ViewDataDictionary(model);
    var razorView = new RazorView(this.ControllerContext, partialViewFullPath
    , null, false, new string[] { "cshtml" });
    var sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using (HtmlTextWriter tw = new HtmlTextWriter(sw))
        {
            ViewContext viewContext = new ViewContext(this.ControllerContext
                            ,razorView,viewData, this.TempData, tw);
            razorView.Render(viewContext, tw);
        }
    }
    return sb.ToString();
}


The RenderPartialView function can be called as the following example code shows

        
[HttpPost]
public ActionResult SomeAction(int id)
{
    ///...
    var result = new AjaxReturnObjectModel();
    result.Success = true;
    result.Html = RenderPartialView("~/Views/Controller/PartialView.cshtml", model);
    return Json(result, JsonRequestBehavior.DenyGet);
}

Hope this helps.

Thursday, May 22, 2014

SQLite: How to Enforce Foreign Key Constraints

Enabling SQLite Foreign Keys:

SQLite lets create foreign keys but will not enforce them upon insertion or deletion. I spent sometime playing with this and it turns out that there are two ways to make SQLite enforce the foreign key constraint:

1) And the this is the easiest way. In the connection string you can specify that foreign keys should be enforce like so (tested using System.Data.SQLite ADO.NET driver):
<add name="ConnectionName" connectionString="Data Source=dbname.db;Version=3;New=True;Foreign Keys=True;" providerName="System.Data.SQLite"/>
2) For every connection you can turn on the foreign_keys pragama using the command
PRAGMA foreign_keys = ON; as documented here http://www.sqlite.org/foreignkeys.html#fk_enable

So with the second approach one can do something similar to the following pseudocode:

SQLiteConnection cn = new SQLiteConnection(...);
SQLiteCommend cmd = new SQLiteCommand(cn);
cn.Open();
cmd.CommandText = "PRAGMA foreign_keys = ON;"
cmd.ExecuteNonQuery(); /* so far we ensured that foreign keys constraints will be enforced */
cmd.CommandText = /* some SQL code here */
cmd.Execute ...

I prefer approach 1).



Friday, January 31, 2014

Passing Func When you Meant Expression

Queries are Very Slow

While working on a proof of concept project, I noticed my queries took longer than expected to run. The repository class uses an Entity Framework (Code First) DbContext. The function in the repository class in question had a signature that looked like:

public IEnumerable<entity> Find(Func<Entity, bool> whereExpression,int take,int skip){
return this.dbContext.Entities.Where(whereExpression).Skip(skip).Take(take);
}

The idea is I will let the client of the repository pass any expression that will return a boolean value to filter the entities collection.

I noticed the generated SQL was something like

select column1, .... columnn from dbo.table where <some_condition>
I did expect the output query to specify a limit to the query at the end (this was PostgreSQL). So I expected:
select column1, .... columnn from dbo.table where <some_condition> limit n;
I ran the same code against Microsoft SQL Server 2012 and the generated SQL had not top keyword to limit the number of returned rows.

What was Happening?

Basically the where operation and the take calls were not happening on the database server, they were being executed on the client-side, the C# console app in my case. The entire table (thousands of rows) of Entities was brought to the client and loaded in memory after the filtering and limiting took place. Very expensive and that explained why the query was much slower than I expected. 

Why was the Entire Table Loaded to Memory?

I just needed the top n rows so why the entire table loaded in memory? After browsing the documentation I came to the following understanding and conclusion. In LINQ if you enumerate a query it will cause the runtime to execute it to get the result. Enumerating a query is typically done via calls to function such as ToList(), or via a foreach expression. So which call in my two-line function was causing the Entities property to be executed and enumerated. Entities is of type DbSet which implements both IEnumerable and IQueryable and both interfaces have a Where method http://msdn.microsoft.com/en-us/library/gg696460(v=vs.113).aspx. Which implementation of where to call is determined by the type of the argument. Notice that IEnumerable's where looks like 
Whereas IQueryable's where looks like 

I noticed that when I called my Find function with Func<T,bool> as the type of the whereExpression variable, the Entities set was enumerated and loaded to memory as soon as the Where method is called. When I however pass an Expression (and not just a delegate) the following happened:
  • I got my limit statement (or top statement in T-SQL) in the generated SQL code
  • Therefore not all instances of Entity was loaded in memory
  • The query was faster as a result.
So the new signature of my Find function is 

public IEnumerable<entity> Find(Expression<func>Entity,bool>> whereExpression,int take,int skip)

Summary

There is a difference between passing a delegate Func or an Expression. Here is a good answer to the difference http://stackoverflow.com/a/3123181. Applying either a delegate or an expression has an effect on LINQ to Entities queries.