Monday, September 13, 2010

Abstract Factory Vs Builder

The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage.
An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would need to know how to handle only the abstract Letter or Resume class, not the specific version that it got from the concrete factory.
In software development, a Factory is the location in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage. This allows for new derived types to be introduced with no change to the code that uses the base class.
Use of this pattern makes it possible to interchange concrete classes without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Used correctly the "extra work" pays off in the second instance of using the Factory.
 
 
The builder pattern is a software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance to the composite pattern, a structural pattern.
        Builder
Abstract interface for creating objects (product).
Concrete Builder
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.
        Director
The Director class is responsible for managing the correct sequence of object creation. It receives a Concrete Builder as a parameter and executes the necessary operations on it.
        Product
The final object that will be created by the Director using Builder.
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components are built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
 
 
 
 
Diff b/w Factory & Builder
 
The factor pattern defers the choice of what concrete type of object to 
make until run time. E.g. going to a restaurant to order the special of 
the day.  The waiter is the interface to the factory that takes the 
abstractor generic message "Get me the special of the day!" and returns 
the concrete product (i.e Liver souffle or Chicken caramel) 
The builder pattern encapsulates the logic of how to put together a 
complex object so that the client just requests a configuration and the 
builder directs the logic of building it.   E.g The main contractor 
(builder) in building a house knows, given a floor plan, knows how to 
execute the sequence of operations (i,e. by delegating to subcontractors) 
needed to build the complex object.  If that logic was not encapsulated in 
a builder, then the buyers would have to organize the subcontracting 
themselves ("Dear, shouldn't we have asked for the foundation to be laid 
before the roofers showed up?") 
The factory is concerned with what is made, the builder with how it is 
made.  Design patterns points out that (page 105) Abstract factory is 
similar to builder in that it too may construct complex objects.  The 
primary difference is that the Builder pattern focuses on constructing a 
complex object step by step.  Abstract factor's emphasis is on families of 
product objects(either simple or complex).  Builder returns the product as 
the final step, but as far as the Abstract Factory is concerned, the 
product gets returned immediately 
 
 

Friday, September 3, 2010

Windows Powershell??

Starting looking at windows powershell scripting and its effective use. Came across a very usefull site for powershell scripts.
Will be exploring it in details as it looks like a long term core windows tool.
 
Below is a very detailed and usefull script which can be easily converted to a C# example :D
 
 
 
 
Function Take-ScreenShot {
    <# 
.SYNOPSIS 
    Used to take a screenshot of the desktop or the active window.
.DESCRIPTION 
    Used to take a screenshot of the desktop or the active window and save to an image file if needed.
.PARAMETER screen
    Screenshot of the entire screen
.PARAMETER activewindow
    Screenshot of the active window
.PARAMETER file
    Name of the file to save as. Default is image.bmp
.PARAMETER imagetype
    Type of image being saved. Can use JPEG,BMP,PNG. Default is bitmap(bmp)   
.INPUTS
.OUTPUTS   
.NOTES 
    Name: Take-ScreenShot
    Author: Boe Prox
    DateCreated: 07/25/2010    
.EXAMPLE 
    Take-ScreenShot -activewindow
    Takes a screen shot of the active window       
.EXAMPLE 
    Take-ScreenShot -Screen
    Takes a screenshot of the entire desktop
.EXAMPLE 
    Take-ScreenShot -activewindow -file "C:\image.bmp" -imagetype bmp
    Takes a screenshot of the active window and saves the file named image.bmp with the image being bitmap
.EXAMPLE 
    Take-ScreenShot -screen -file "C:\image.png" -imagetype png   
    Takes a screenshot of the entire desktop and saves the file named image.png with the image being png
#> 
#Requires -Version 2
        [cmdletbinding(
                SupportsShouldProcess = $True,
                DefaultParameterSetName = "screen",
                ConfirmImpact = "low"
        )]
Param (
       [Parameter(
            Mandatory = $False,
            ParameterSetName = "screen",
            ValueFromPipeline = $True)]
            [switch]$screen,
       [Parameter(
            Mandatory = $False,
            ParameterSetName = "window",
            ValueFromPipeline = $False)]
            [switch]$activewindow,
       [Parameter(
            Mandatory = $False,
            ParameterSetName = "",
            ValueFromPipeline = $False)]
            [string]$file,
       [Parameter(
            Mandatory = $False,
            ParameterSetName = "",
            ValueFromPipeline = $False)]
            [string]
            [ValidateSet("bmp","jpeg","png")]
            $imagetype = "bmp"          
 
)
# C# code
$code = @'
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace ScreenShotDemo
{
  /// <summary>
  /// Provides functions to capture the entire screen, or a particular window, and save it to a file.
  /// </summary>
  public class ScreenCapture
  {
    /// <summary>
    /// Creates an Image object containing a screen shot the active window
    /// </summary>
    /// <returns></returns>
    public Image CaptureActiveWindow()
    {
      return CaptureWindow( User32.GetForegroundWindow() );
    }
    /// <summary>
    /// Creates an Image object containing a screen shot of the entire desktop
    /// </summary>
    /// <returns></returns>
    public Image CaptureScreen()
    {
      return CaptureWindow( User32.GetDesktopWindow() );
    }   
    /// <summary>
    /// Creates an Image object containing a screen shot of a specific window
    /// </summary>
    /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
    /// <returns></returns>
    private Image CaptureWindow(IntPtr handle)
    {
      // get te hDC of the target window
      IntPtr hdcSrc = User32.GetWindowDC(handle);
      // get the size
      User32.RECT windowRect = new User32.RECT();
      User32.GetWindowRect(handle,ref windowRect);
      int width = windowRect.right - windowRect.left;
      int height = windowRect.bottom - windowRect.top;
      // create a device context we can copy to
      IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
      // create a bitmap we can copy it to,
      // using GetDeviceCaps to get the width/height
      IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
      // select the bitmap object
      IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
      // bitblt over
      GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
      // restore selection
      GDI32.SelectObject(hdcDest,hOld);
      // clean up
      GDI32.DeleteDC(hdcDest);
      User32.ReleaseDC(handle,hdcSrc);
      // get a .NET image object for it
      Image img = Image.FromHbitmap(hBitmap);
      // free up the Bitmap object
      GDI32.DeleteObject(hBitmap);
      return img;
    }
    /// <summary>
    /// Captures a screen shot of the active window, and saves it to a file
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="format"></param>
    public void CaptureActiveWindowToFile(string filename, ImageFormat format)
    {
      Image img = CaptureActiveWindow();
      img.Save(filename,format);
    }
    /// <summary>
    /// Captures a screen shot of the entire desktop, and saves it to a file
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="format"></param>
    public void CaptureScreenToFile(string filename, ImageFormat format)
    {
      Image img = CaptureScreen();
      img.Save(filename,format);
    }   
 
    /// <summary>
    /// Helper class containing Gdi32 API functions
    /// </summary>
    private class GDI32
    {
 
      public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
      [DllImport("gdi32.dll")]
      public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
        int nWidth,int nHeight,IntPtr hObjectSource,
        int nXSrc,int nYSrc,int dwRop);
      [DllImport("gdi32.dll")]
      public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
        int nHeight);
      [DllImport("gdi32.dll")]
      public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
      [DllImport("gdi32.dll")]
      public static extern bool DeleteDC(IntPtr hDC);
      [DllImport("gdi32.dll")]
      public static extern bool DeleteObject(IntPtr hObject);
      [DllImport("gdi32.dll")]
      public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
    }
 
    /// <summary>
    /// Helper class containing User32 API functions
    /// </summary>
    private class User32
    {
      [StructLayout(LayoutKind.Sequential)]
      public struct RECT
      {
        public int left;
        public int top;
        public int right;
        public int bottom;
      }
      [DllImport("user32.dll")]
      public static extern IntPtr GetDesktopWindow();
      [DllImport("user32.dll")]
      public static extern IntPtr GetWindowDC(IntPtr hWnd);
      [DllImport("user32.dll")]
      public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
      [DllImport("user32.dll")]
      public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
      [DllImport("user32.dll")]
      public static extern IntPtr GetForegroundWindow();     
    }
  }
}
'@
#User Add-Type to import the code
add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing'
#Create the object for the Function
$capture = New-Object ScreenShotDemo.ScreenCapture
 
#Take screenshot of the entire screen
If ($Screen) {
    Write-Verbose "Taking screenshot of entire desktop"
    #Save to a file
    If ($file) {
        If ($file -eq "") {
            $file = "$pwd\image.bmp"
            }
        Write-Verbose "Creating screen file: $file with imagetype of $imagetype"
        $capture.CaptureScreenToFile($file,$imagetype)
        }
    Else {
        $capture.CaptureScreen()
        }
    }
#Take screenshot of the active window   
If ($ActiveWindow) {
    Write-Verbose "Taking screenshot of the active window"
    #Save to a file
    If ($file) {
        If ($file -eq "") {
            $file = "$pwd\image.bmp"
            }
        Write-Verbose "Creating activewindow file: $file with imagetype of $imagetype"
        $capture.CaptureActiveWindowToFile($file,$imagetype)
        }
    Else {
        $capture.CaptureActiveWindow()
        }   
    }   
}
 



Additioanl Powershell scripting sites

http://pshscripts.blogspot.com/

Wednesday, August 11, 2010

Implementing cookie for page redirect

Problem :
 
I have a requirement for the below scenario where I have to implement this using the browser cookies. This should be done using plain Html or Asp code.
 
E.g..  1 > User access www.example.com
      2 > In the landing page of www.example.com user will have another link for www.xyz.com.
      3 > User access the link in step 2.
      4 > User closes the browser.
      5 > Next time when the user access www.example.com  the user should be redirected to www.xyz.com directly.
 
 
 
Create a javascript file ‘cookieRedirect.js’ with following code
 
var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
 
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
 
var favorite = GetCookie('animal');
 
if (favorite != null) {
switch (favorite) {
case 'cat' :     url = 'cat.html'; // change these!
                 break;
case 'dog' :     url = 'dog.html';
                 break;
case 'gerbil' : url = 'gerbil.html';
                break;
case 'gopher' : url = 'gopher.html';
                break;
}
// window.location.href = url;
alert('You would have been taken to the ' + favorite + ' page (' + url + '), but this is just a demo!');
}
 
 
 
Add following lines to page HEAD
 
<script type="text/javascript" src="cookieRedirect.js"></script>
 
 
Add following lines to page Body
 
<form>
<table><tr><td>
Please choose your Favorite Pet:<br>
<input type=checkbox name="cat" onClick="SetCookie('animal', this.name, exp);">Cat<br>
<input type=checkbox name="dog" onClick="SetCookie('animal', this.name, exp);">Dog<br>
<input type=checkbox name="gerbil" onClick="SetCookie('animal', this.name, exp);">Gerbil<br>
<input type=checkbox name="gopher" onClick="SetCookie('animal', this.name, exp);">Gopher<br>
</td></tr>
</table>
</form>
<br>
(Choose an animal then <a href="cookie-redirect.html">reload</a> the page to see how the redirect works.)
 
 

Monday, August 9, 2010

Outlook 2007 | Asp.Net Interop

invoke the client machine's outlook by creating an ActiveX object using javascript. This way I do not need my application to intertop and install outlook on the server (which would not have met the requirement anyway). Also unlike "mailto" there is no restrcitiion of the length of the email and format of the email could be designed in HTML.
 
 
This javascript would then be registered using Script Manager as I am also using AJAX controls on the site. Here's the code snippet for anyone who has a similar problem to deal with in the future:
 
string script = "var objO = new ActiveXObject('Outlook.Application');var objNS = objO.GetNameSpace('MAPI'); var mItm = objO.CreateItem(0); mItm.Display(); mItm.To = ''; mItm.Subject = '" + EmailReader.LoadEmailSubjectTemplate(Convert.ToInt32(refId)) + "';mItm.HTMLBody = '" + EmailReader.LoadEmailBodyTemplate(Convert.ToInt32(refId)) + "'; mItm.GetInspector.WindowState = 2;";
            if (!ClientScript.IsStartupScriptRegistered(script))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Nomination", script, true);
            }
 
 

Thursday, June 17, 2010

Organic Search | identify source page details

Problem :
 
We had a requirement to personalize a landing page based on what search term the user used when they performed a search on an organic search site (e.g. Google, Yahoo, Bing etc).
 
Here’s the detailed scenario:
1.      User goes to google and enters a search term
2.      Google shows the result set based on the search term
3.      Somewhere in the results will be a link (not sponsored link) to our client’s website
4.      The user clicks the link and comes to our site, at this point we want to know what search term the user used
5.      Based on the search term we would like to target specific content to the user on that page
 
What we want to know is outside of sponsored links, is it possible to identify what search term was used to perform the search. Will it be available in the HTTP header or some other means to get it.
 
 
Solution : [C#]
 
You can use "Referral URL" to extract search term, like with Google, referral URL for "test" (searched test in google.com) will something be like given below (q=test), by parsing the URL you can extract the search term.
In general Your web site visitors could come from different sources, like search engines, blogs, banner ads, affiliates, web directories etc.
To find out which page is generated request to your page, use this code:
 
string MyReferrer = Request.UrlReferrer.ToString();
 
Here is the code for paring the source url:
 
    private String findSearchText(String referrerURL, List paramList) throws UnsupportedEncodingException {
        int queryStringIndex = referrerURL.indexOf("?");
        if (queryStringIndex < 0 || queryStringIndex >= referrerURL.length() - 2) {
            return null;
        }
        referrerURL = referrerURL.substring(queryStringIndex + 1);
        String[] paramSplits = referrerURL.split("&");
        for (int i = 0; i < paramSplits.length; i++) {
            String[] paramValueSplits = paramSplits[i].split("=");
            if (paramValueSplits.length != 2) {
                continue;
            }
            if (paramList.contains(paramValueSplits[0])) {
                return URLDecoder.decode(paramValueSplits[1], UTF_8_ENCODING);
            }
        }
        return null;
    }
 
The List paramlist is the following list:
 
 
 

Tuesday, June 15, 2010

If at all Banks can work together!!!!!!!!

Online transactions has been so much talked about with so many service providers with showcasing their abilities.
 
I was wondering if I could put something on my site which will enable people pay online without the hassle of me getting subscribed to some online payment gateway and also restricting users for a limited set of banks.
 
Solution : All banks should have option similar to paying via bank to some other bank account, it’s just that the payment will be the other way.
Explanation:
Online user will send a online request from a web portal with their Bank account detail like Account No and IFCS Code.
Online portal will send a request via their bank to the online user bank account for payment.
Online user will accept/reject/update&accept transaction request .
Bank’s does transaction and portal get’s paid.
 
This solution remove security risk outside of the scope of banks, makes it more transparent. Add value to Bank’s.
 
 
 
 

Monday, June 14, 2010

Assign a Strong Name to a Third Party Dll

So here is the scenario – you get a .net dll from somewhere that contains some cool functionality you wish to use in your SharePoint application. The probem is that you can’t sign your own application dll because the referenced third party dll is not signed or strongly named.
When you go to build your VS project you will get the following error – ‘Referenced assembly doesn’t have strong name’
So how can I sign/strongly name the dll I hear you ask? Well here’s how:
1.Open the Visual Studio Command Prompt – probably best to copy the dll in into the VC folder to save you having to cd or type a long path in
2.Create a key pair to sign the assembly – sn.exe –k key.snk
3.Disassemble the dll using ILDASM – ILDASM.exe Yourdll.dll /out=Yourdll.il
This will create a ‘Yourdll.il’ file containing the IL for the assembly. It will also extract the assembly so you will now have a folder with lots of files, you will also see a .res file containing the resources for the dll.
4.Reassemble the dll using ILASM to sign the output with the key created above –ILASM.exe Yourdll.il /dll /out=Yourdll2.dll /key=key.snk
5.Success! 
You should now have a signed version of the dll, you can now add this to your VS project or deploy to the GAC etc   !