Thursday, June 20, 2013

Predicates- small but beautiful

 
A predicate is a function that returns true or false & a predicate delegate is a reference to a predicate.
So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.
 
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     List list = new List { 1, 2, 3 };

     Predicate predicate = new Predicate(greaterThanTwo);

     List newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
     return arg > 2;
    }
}
Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     List list = new List { 1, 2, 3 };

     List newList = list.FindAll(i => i > 2);
    }
}
 
OR use the plane old inline Function delegate:
 
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List list = new List { 1, 2, 3 };

        List newList = list.FindAll(delegate(int arg)
                           {
                               return arg> 2;
                           });
    }
}

Friday, March 29, 2013

Signing Third Party Dll's

Faced a problem today where I was not able to refer a third party dll (MessageGearsSDK.dll) into my project.
Problem was simple- My project dll is signed but MessageGearsSDK.dll is unsigned (Shame on them to release a non-signed dll for redistribution).

Binged a lot and then slapped myself when I found that the solution was also so simple (shame on me for not able to think it by myself) -

Use Ildasm to create .il file and then recreate the dll by signing it with my own key :-)

ildasm /all /out=MessageGearsSDK.il MessageGearsSDK.dll
ilasm /dll /key=xxxx.snk MessageGearsSDK.il

For more information and some exceptions (like, you cannot do this for a assembly which uses a un-managed code or uses delay signing), please refer following link-

http://buffered.io/posts/net-fu-signing-an-unsigned-assembly-without-delay-signing/

Tuesday, February 19, 2013

Sliding expiration explained

Sliding expiration was always a confusion to me unless I decided to dig inside the code.
This is what happening inside

Declaring Type:
System.Web.Security.FormsAuthentication
public static FormsAuthenticationTicket RenewTicketIfOld(FormsAuthenticationTicket tOld)
{
    if (tOld == null)
    {
        return null;
    }
    DateTime utcNow = DateTime.UtcNow;
    TimeSpan span = (TimeSpan) (utcNow - tOld.IssueDateUtc);
    TimeSpan span2 = (TimeSpan) (tOld.ExpirationUtc - utcNow);
    if (span2 > span) <--------So it will renew only after mid of the total timeout minutes
    {
        return tOld;
    }
    TimeSpan span3 = (TimeSpan) (tOld.ExpirationUtc - tOld.IssueDateUtc);
    DateTime expirationUtc = utcNow + span3;
    return FormsAuthenticationTicket.FromUtc(tOld.Version, tOld.Name, utcNow, expirationUtc, tOld.IsPersistent, tOld.UserData, tOld.CookiePath);
}
Above function get called by OnAuthenticate of System.Web.Security.FormsAuthenticationModule

{
…...
          if (FormsAuthentication.SlidingExpiration)
                {
                    ticket = FormsAuthentication.RenewTicketIfOld(tOld);
                }
…….
}


This implementation makes some sense because Authentication ticket's Expiration property doesn't allow it to set, so we need to create new authentication ticket.
But for me, I have to problem using slidingExpiration-
It messed up my 'about to timeout' popup (I have a SPA) at browser (although I can fix it now after understanding this logic)
It's hard to tell the QA guy that if you ideal for 16 minutes (in a timeout of 30 minutes), you will be logged-out . And all this is because ticket is not renewed when you sent your get/post at 14th minute :-(

Looks like I can’t win that battle (with QA and business) so I need to let go slidingExpiration (by setting it to false) and manually renew (recreate) the ticket for each request :-(

Wish they had allowed expiration property of FormAuthenticationTicket so that I need not to recreate the whole ticket again and again…

Friday, September 17, 2010

Continuous deployment on Steroids

Although I don't agree to very idea of commit to production, but still lots to learn from this article-

http://timothyfitz.wordpress.com/2009/02/10/continuous-deployment-at-imvu-doing-the-impossible-fifty-times-a-day/

I still vouch for Idea of Workflow based commit to production.

Wednesday, July 21, 2010

One elegant way to log the time it took to process a request in ASP.NET

Global.asax and the HttpApplication class

Posted by scott on Saturday, January 24, 2004

The Global class derived from HttpApplication has many uses, including managing application and request state.
The global.asax file setup by Visual Studio.NET gives every web application a Global class derived from HttpApplication. The class contains event handlers such as Application_Start and Session_Start.

There is a tendency to think each web application will have a single instance of Global. Indeed, in most frameworks an object representing the “application” is a singleton – only one exists. Also, we know the ASP.NET runtime calls Application_Start only once when the application starts. All of these clues seem to imply there would be only one instance of a Global object in our application, but these clues are actually misleading.

The ASP.NET runtime maintains a pool of HttpApplication objects. When an incoming request arrives, the runtime takes an HttpApplication object from the pool to pair with the request. The object remains associated with the request, and only that request, until the request processing is complete. When the request is finished the runtime may return the object to the pool, and later pull it out to service another request later – but only one request at a time is associated with an HttpApplication object.


Application State versus Request State
The Application object (of type HttpApplicationState) is what we generally think of when we need to store information global to the application. The Application object is a convenient place to store information such as a database connection string.



private void Page_Load(object sender, System.EventArgs e)
{
string connectionString =
Application["ConnectionString"].ToString();
. . . .
}


You can also make your own static variables in the HttpApplication class to carry application state. For example, the above information could also be stored like this:


public class Global : System.Web.HttpApplication
{
public static
readonly string ConnectionString = "connection information";

. . .
}


You can access the member from anywhere in your ASP.NET code like so:



string connectionString = Global.ConnectionString;


It is important to make the string a static member (you could also make a static property accessor) if you want the member to be global for the application.

If you instead use member (non-static) variables, you can use these for request state. For instance, the following code will print out the number of milliseconds used to process a request in the output window of the debugger.



public class Global : System.Web.HttpApplication
{

protected DateTime beginRequestTime;

protected void Application_BeginRequest(Object sender, EventArgs e)
{
beginRequestTime = DateTime.Now;
}

protected void Application_EndRequest(Object sender, EventArgs e)
{
string messageFormat = "Elapsed request time (ms) = {0}";
TimeSpan diffTime = DateTime.Now - beginRequestTime;
Trace.WriteLine(
String.Format(
messageFormat, diffTime.TotalMilliseconds
)
);
}
. . .
}


Now, returning to the question of application state. Which is better: storing object references in the Application object, or making static member variables and properties in the Global class? Both approaches have pros and cons.

Keeping global data in static members of the Global class gives you strong typing. Unlike the Application object, you will not need to typecast or convert values. It is the difference between the following two sections:



DataSet cachedData = (DataSet)Application[“MyDataSet”];
string myString = Application[“MyString”].ToString();

DataSet cachedData = Global.MyDataSet;
string = Global.MyString;


Strong typing gives you cleaner, more robust code. In performance critical situations it can also save the overhead of running conversions. If you are storing value types, such as integers, strong typing avoids the overhead of boxing and unboxing the value into an object (see references). Also, as mentioned in a previous article, the Application object also has some small overhead due to locking. If you initialize your global data only once and never modify or write to the data, you can avoid the locking overhead with static members on the Global class. If you take this approach, I recommend using accessor properties with only get methods to make sure the data is read only.

If you read as well as write static members of the Global class, remember to be thread safe. The Application object already provides thread safety through a course grained reader / writer lock.

The safest place to initialize the global data is during the Application_Start event.Even though there are multiple instances of the Global object around, the runtime only invokes Application_Start on the first instance of Global it creates. An ideal time to initialize request state is during Application_BeginRequest. Request state variables generally do not require thread safety, as each object services only one request at a time.



by K. Scott Allen (scott @ OdeToCode.com)

Friday, January 15, 2010

Google Outlook Calendar Sync on Windows 2003

After lots of efforts I managed to install Google outlook calendar sync on my Windows 2003 server. By default it supports installation to Windows XP and Windows Vista only.
Solution was damn simple -
Right click on GoogleCalendarSync_Installer.exe and go to properties, then go to Compatability tab, check the 'Run this program in compatibilty mode for;' flag and choose windows XP, click ok and try run again..... Boom it worked :-))))
Something new for me to learn and store on this pagefile.

Tuesday, January 5, 2010

Things to Remember

TypeForwardTo attribute (Use to divert the search for a class from one Assembly to other Assembly without Recompiling the Caller application)
-->For this attribute to work, You cannot change the namespace of the Class if you shift it to other assembly :-(
----------------------------------------------------------------------------------------------
Use HashTable against ListDictionary if n >10 ( See Microsoft documentation )
--> No evidence to support this, except to the fact that HybridDictionary uses an Internal flag to switch the data type ( from ListDictionary to Hashtable) when elements are greater than 10 .
----------------------------------------------------------------------------------------------
ServiceController (Can be used to create you own service manager for Windows service)
--> We should write our own service manager because MMC snap in does not support custom commands.
------------------------------------------------------------------------------------------------
Set ANSI_NULLS ON
--> Do not use Equal and not equals operator with Null when using this , instead use Is Null and Is Not Null operators
------------------------------------------------------------------------------------------------
Set Quoted_Identifier ON
--> Can's use double quotes for string comparison if it is ON :-(
If you want to use [Where name = "Ankur Jindal"] instead of [Where name = 'Ankur Jindal'] then Set Quoted_Identifier OFF

Labels