Working with Factory Design Pattern using C#

Overview
The Factory design pattern is useful when a class cannot anticipate the class of objects it must create or when a class wants its subclasses to specify the objects it creates.  It is also useful when you want to delegate responsibility to one of several helper subclasses and localize the knowledge of which helper subclass is the delegate.

Its intent is to define an interface for creating an object, but let the subclasses decide which class to instantiate.  The Factory Method allows a class to defer instantiation to the subclasses. (Reference www.dofactory.com)

Factory Design Pattern allows applications to provide encapsulation by hiding the complex components and their dependencies from the client.  It writes an object creation code in a centralized location, called the Factory class, which helps to reduce the code redundancy in the application.  The client code instantiates the Factory class and passes some parameter values to the Factory class.  The Factory class instantiates the required object, based on the received Parameter values, and returns it to the client. This way, Encapsulation is preserved and also helps to build reusable components.

In the case of the following simple .NET example, we can consider a System.Convert class. This class contains a set of conversion functions, few of them are demonstrated below.

Listing 1

int intValue = Convert.ToUInt16(true);
In this Listing, we have passed the true Boolean value to the Convert.ToUInt16 method. This method internally checks parameter data type.  It then converts this Boolean value into the integer value “1” and returns it.

Similarly, in the below code, Convert.ToUInt16 method accepts the false Boolean value and returns integer value “0”.
Listing 2
int intValue = Convert.ToUInt16(false);
We can even consider a Convert.ToBoolean function which behaves similarly.
Classic examples of .NET are enumerators, such as CommandType.StoredProcedure, CommandType.TableDirect and CommandType.Text.
Listing 3
SqlCommand cmdobj = newSqlCommand(StoredProcedureName, ConnectionString);
cmdobj.CommandType =CommandType.StoredProcedure;
 
SqlCommand cmdobj = new SqlCommand(TableName,ConnectionString);
cmdobj.CommandType = CommandType.TableDirect;
 
SqlCommand cmdobj = new SqlCommand(SelectText,ConnectionString);
cmdobj.CommandType = CommandType.Text;
In the above listing, notice that based on the CommandType set to the SqlCommand object, it executes one of the following- Stored Procedure, Table or Select Query. This demonstrates that inside a SqlCommand object, logic exists which based on the Enumerator value of CommandType, executes Stored Procedure, Table or Select Query.
A non-software example that demonstrates this pattern would be a restaurant. Restaurants serve a variety of items which they list in the menu.  The restaurant's waiter provides a menu to the customer and, based on the items available in the Menu, the customer selects the items and orders them. These selected items are prepared and served to the customer by the waiter.
If you map this non-software example against the factory design pattern, we can say:
Items, as the subclasses, are served to the customer by a waiter and its preparation is hidden from the customer.
The waiter, as the Factory class, takes the customer's order based on the items available in the menu and serves them.
The customer, as the Client code, orders the items and does not see how the items are prepared.
The following sample application depicts one of the ways to implement the Factory design pattern in C#.
Requirements
Microsoft Visual C# 2005 Express Edition
Define the Interface
Add the new Windows Application project (with the name as FactoryDesignPattern).  Then add an interface class as IBase and paste the following code in it. This interface is defined for creating objects.
Listing 4
interface IBase
{
  string Perform();
}
Implement the Interface
Listing 5
class Algorithm1: IBase
{
  public string Perform()
  {
    return "Algorithm1 Performed";
  }
}
 
class Algorithm2: IBase
{
  public string Perform()
  {
    return "Algorithm2 Performed";
  }
}
 
class Algorithm3: IBase
{
  public string Perform()
  {
    return "Algorithm3 Performed";
  }
}
In Listing 5, the three classes Algorithm1, Algorithm2 and Algorithm3 are defined which implements the IBase interface (refer to Listing 4).
Define the Factory Class
First, define the Factory class.  This class is responsible for instantiating the required object and returning it to the client.  Once the object is returned, the client code will call the object methods without knowing how these objects methods are implemented.  This provides the encapsulation mechanism.
Listing 6
class Factory
{
  public IBase GetObject(int AlgorithmType)
  {
    IBase objbase = null;
    switch (AlgorithmType)
    {
      case 1:
        objbase = new Algorithm1();
        break;
      case 2:
        objbase = new Algorithm2();
        break;
      case 3:
        objbase = new Algorithm3();
        break;
      default:
        throw new Exception("Unknown Object");
    }
    return objbase;
  }
}
In the above listing, the factory class has one method, GetObject, which accepts one parameter. Based on the parameter value, one of the three IBase implementations will be returned.  The client class is responsible for choosing which Algorithm it would like to use.
If we wished to extend the factory to dynamically introduce new Algorithms, simply add another case statement in the above code with the new Algorithm object.
Create the Client Application
Add the form to the Windows Applications project and then add the button btnClient.  To this button, add the below code.
Listing 7
private void btnClient_Click(object sender,EventArgs e)
{
  try
  {
    Factory objfactory = new Factory();
    IBase objBase = objfactory.GetObject(2);
    MessageBox.Show(objBase.Perform());
 
    objBase = objfactory.GetObject(3);
    MessageBox.Show(objBase.Perform());
  }
  catch (Exception objex)
  {
    MessageBox.Show(objex.Message);
  }
}
In Listing 7, first the Factory object is created which decides the object it should return.  Then a parameter value of "2" is passed to the Getobject method of the Factory object which returns the Algorithm2 object.  This object then executes the Perform method of the Algorithm2 class.
Next, another parameter value of "3" is passed to the Getobject method of the Factory object, this time the Perform method of the Algorithm3 class is executed.
Now run the application and click the button Client on the form, after which the following messages will be displayed.
Figure 1
 
This Windows application illustrates how a client would use the factory class to create an instance of the desired Algorithm class.
This is a simple demonstration of the Factory design pattern.
Conclusion
In this article, we have seen how to hide the complex object implementation from the client by encapsulating it in the factory class.  This also provides reusable components.
Factory patterns are used extensively in building frameworks and they are implemented by the users of the Framework.
If you try to explore .NET Framework, you will find many instances of the Factory pattern implementations in it.
Downloads
References
Summary
Factory pattern provides flexibility and reusability by using a specialized object which creates other objects in a significant manner.  This results in designing a flexible system which can withstand the changing requirements.

Factory design patterns


Will the sales team come up with a new discounting idea next month? Will we support new file formats during the lifetime of this product? Are we going to change new data layer to support another database system? These kinds of questions scream for a pluggable design, where part of the source code is loaded based on some configurable option.
Our factories make it possible to create pluggable designs, which mean you can add new functionality to an existing program without changing the existing code. The moment you can ask yourself a question like the ones above, you simply add a Factory and leave the answer for the future.

Developer friendly

An object factory can literally be created with a single line of code. A single attribute tells a class that it should be created by the factory. And you’re done. You can even load DLL’s at runtime or create factories of factories; our factory implementation will automatically eliminate any other code the developer should write. Surely, it won’t get much easier than this.


High performance

Our implementation enables you to easily construct millions of factory objects per second both single-threaded and multi-threaded. A high performance solution for factories means you can make as many things pluggable as you see fit without compromising performance. And because a pluggable design will lead to more flexibility in the future, having the ability to add plugin endpoints everywhere is a very good thing.

Dependency Inversion Principle

The dependency inversion principle tells us tells us that we should try to avoid depending on things that are ‘concrete’. For example, if we should depend on a list structure, but don’t know if we should use a linked list structure or an array structure, we should use the interface that supports both. Our factory uses this principle to build related objects, but goes one step further: objects are constructed based on a key. This means the construction of derived types is also decoupled from the application, which is like a Dependency Inversion Principle on steroids.




migration


Office 365 Migration with MetaVis Migrator


Method 'Post' of object 'IOWSPostData' failed SharePoint 2010 Excel sheet upload in sharepoint


Method 'Post' of object 'IOWSPostData' Failed in Sharepoint 2010

Over the past several months I've been testing out new features in Sharepoint 2010, one of which is the new chart webpart. To test it I've been trying to import a spreadsheet into Sharepoint 2010, but I've never gotten the import to work without an error, until now. Everytime I tried to import a spreadsheet, no matter how small or simple, I got a method 'Post' of object 'IOWSPostData' Failed error message. Here's what happened to me, and how I fixed the problem.

Background
I'm running Sharepoint 2010 (the release candidate) and Office 2007. I confirmed this error message does not occur if you're running Sharepoint 2010 and Office 2010, only when the environments are 
mixed.
  1. From your site, open All Site Content. Click Create and select Import Spreadsheet. Give the list a name and navigate to the file location.

  2. Choose Range of Cells and select the range on the spreadsheet.


  3. Click Import. The following error message will appear:


  4. The same error will appear if you select a Named Range or a Table Range.
How to Fix It
I found several other folks (here and here are the best examples) had had this problem as well, but none of their fixes had worked for me because I had a hybrid environment of 2010 and 2007. I'm guessing that other folks will encounter this problem too, because big companies don't often migrate Office all at once, especially while they're evaluating new products like Sharepoint 2010.

All of the posts I'd read about this problem suggested editing the Excel Add-in file EXPTOOWS.XLA located in the \Program Files\Microsoft Office\Office 12\1033 folder. But editing that file didn't help me a bit. Turned out there's another version of that same file in \Program Files\Microsoft Office\Office14\1033, and that was the one that needed editing in my case.

Before you begin, a few notes for the uninitiated:
  • EXPTOOWS.XLA is a hidden file. In order to find it, you'll have to show all hidden files on the system. Do this through the Control Panel, Appearance and Personalization, Folder Options, Show Hidden Files and Folders.
  • The 1033 folder is read-only, so you 1) must be an administrator to write to the folder and 2) can't just edit the file and save it back to the same directory.
To modify the file:
  1. Once you've found the file, rename it to OldEXPTOOWS.XLA (this will give you a backup in case something happens). You may be prompted to confirm the change because this is a read-only folder.
  2. Double-click on OldEXPTOOWS.XLA. This will open Excel but it will look like nothing else is happening. On your keyboard, press ALT-F11 to open the built-in Visual Basic editor. It will look something like this:



  3. Open the code window and scroll until you find this section:

    Sub Initialize(List, Title, URL, QuickLaunch)
    strQuickLaunch = QuickLaunch
    aTarget(iPublishURL) = URL
    aTarget(iPublishListName) = List
    aTarget(iPublishListDesc) = Title
    lVer = -1 ' can't tell STS server version
    If Val(Application.Version) >= 12 Then
    lVer = Application.SharePointVersion(URL)
    End If
    End Sub
  4. Comment out this line lVer = Application.SharePointVersion(URL) by adding a single apostrophe ( ' )to the beginning of the line.
  5. Add a line immediately beneath the commented line that reads lVer = 2 (that's an L, as in lollipop). The section will now look like this (I have highlighted the changes):

    Sub Initialize(List, Title, URL, QuickLaunch)
    strQuickLaunch = QuickLaunch
    aTarget(iPublishURL) = URL
    aTarget(iPublishListName) = List
    aTarget(iPublishListDesc) = Title
    lVer = -1 ' can't tell STS server version
    If Val(Application.Version) >= 12 Then
    ' lVer = Application.SharePointVersion(URL)
    lVer = 2
    End If
    End Sub


  6. Click File, Save. You will get an error message that the file is Read Only. Click OK to continue. A Save As dialog will appear. Change the file type to Excel Add-in (.xla). When you do this, the file location will change to the Excel addin directory - you will want to save the file to somewhere you can remember (like the Desktop). Make sure you've named it EXPTOOWS.XLA.
  7. Close the VB editor and exit Excel.
  8. Using Windows Explorer, navigate to \Program Files\Microsoft Office\Office14\1033.
  9. Copy the new file (EXPTOOWS.XLA) from your Desktop (or wherever you saved it) into \Office14\1033. You will be prompted to confirm this action.
  10. When the new file is in the \Office14\1033 folder, you should be able to import the spreadsheet into Sharepoint 2010 (although you may have to restart IE or the Sharepoint session).
Some of the blog posts say that you can change the version in the line from lVer = 2 to lVer = 3 and try that too. In my tests, it didn't matter which version you used as long as it was in the version in the \Office14\1033 directory. A modified EXPTOOWS.XLA in the \Office12\1033 folder didn't seem to cause this any ill-effects either.
MAIN SOURCE-http://makingspwork.blogspot.in/2010/04/method-post-of-object-iowspostdata.html

Calender control using jquery


<link href="css/jquery-ui-1.8.19.custom.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="jquery-ui-1.8.19.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {

            var date = new Date();
            var currentMonth = date.getMonth();
            var currentDate = date.getDate();
            var currentYear = date.getFullYear();

            $('#<%= txtDate.ClientID  %>').datepicker({
                minDate: new Date(currentYear, currentMonth, currentDate)
            });
        });


<script type="text/javascript">
$(function () {
$("#txtDate").datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1970:2012'
});
});
</script>


</script>
https://www.dropbox.com/s/vkoywk9e82zbkk2/jquery-1.7.2.min.js
https://www.dropbox.com/s/m86818er11601xf/jquery-ui-1.8.19.custom.css
https://www.dropbox.com/s/f52ldmqem6ltvgl/jquery-ui-1.8.19.custom.min.js
https://www.dropbox.com/sh/ujzfwpvuscjkk8o/F47oY_F2Ro

Image size reduce C#



using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO;




private Stream TrimeImage(Stream StreamOriginalImage,int DispMaxWidth, int DispMaxHeight)
        {
            Bitmap mg = new Bitmap(StreamOriginalImage);
            Size newSize = new Size(Convert.ToInt32(DispMaxWidth), Convert.ToInt32(DispMaxHeight));
         
            double ratio = 0d;
            double myThumbWidth = 0d;
            double myThumbHeight = 0d;
            int x = 0;
            int y = 0;

            Bitmap bp;

            if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
            Convert.ToDouble(newSize.Height)))
                ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
            else
                ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
            myThumbHeight = Math.Ceiling(mg.Height / ratio);
            myThumbWidth = Math.Ceiling(mg.Width / ratio);

            //Size thumbSize = new Size((int)myThumbWidth, (int)myThumbHeight);
            Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
            bp = new Bitmap(newSize.Width, newSize.Height);
            x = (newSize.Width - thumbSize.Width) / 2;
            y = (newSize.Height - thumbSize.Height);
            // Had to add System.Drawing class in front of Graphics ---
            System.Drawing.Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);

            MemoryStream memoryStream = new MemoryStream();
            if (bp != null)
            {
                bp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            return memoryStream;
        }





1.ie properties trust site put url
2.site administrator-> site lib and list
3.select report data sourc->microsoft sql server analltical service
4.report builder model->Report model(name)->ok
5.doc lib->report builder report->chose any report

Visual Web Part to Custom List


 SPSecurity.RunWithElevatedPrivileges(delegate
                {

                    using (SPSite siteobj = new SPSite("http://win-kcesc4910nq:43729/"))
                    {
                        using (SPWeb webobj = siteobj.OpenWeb())
                        {

                            if (string.IsNullOrEmpty(TextBox1.Text) || string.IsNullOrEmpty(TextBox2.Text) || string.IsNullOrEmpty(TextBox3.Text))
                            {
                                lbl_sub.Text = "please enter some value";

                            }

                            else
                            {
                                SPList listobj = webobj.Lists["vwp"];
                                SPListItem itemobj = listobj.AddItem();
                                itemobj["name"] = TextBox1.Text.ToString();

                                //SPFieldDateTime dateTime = new SPFieldDateTime(itemobj.Fields, itemobj.Fields.Add(TextBox2.Text, SPFieldType.DateTime, true));
                                //dateTime.DisplayFormat = SPDateTimeFieldFormatType.DateTime;

                                itemobj["dob"] = Convert.ToDateTime(TextBox2.Text.ToString());
                                // itemobj["dob"] = TextBox2.Text.ToString();
                                itemobj["comment"] = TextBox3.Text.ToString();
                                //  itemobj["image"] = FileUpload1.FileBytes.ToString();


                                Stream StreamOriginalImage = null;
                                string path = string.Empty;
                                if (FileUpload1.HasFile)
                                {
                                    StreamOriginalImage = FileUpload1.PostedFile.InputStream;
                                }

                                Stream StreamCropedImage = TrimeImage(StreamOriginalImage,10, 10);

                                //SPList pics = webobj.Lists["vwp"];
                                listobj.RootFolder.Files.Add(FileUpload1.FileName, StreamCropedImage, true);
                                //SPContext.Current.Web.Files.Add(String.Concat(SPContext.Current.Web.Site.RootWeb.Url, path), StreamImage, true);

                                itemobj["image"] = listobj.RootFolder.ServerRelativeUrl + "/" + FileUpload1.FileName;

                                Image1.ImageUrl = listobj.RootFolder.ServerRelativeUrl + "/" + FileUpload1.FileName;

                                // return web.Url.TrimEnd('/') + '/' + uploadedFile.Url.TrimStart('/');

                                itemobj.Update();
                            }

                        }
                    }


                });


Network Connection




open cmd-->ping target machine ip
go to network chose target machine -->type uid,pwd
click on remember me

note==>

on target machine-->

go to
Control Panel\All Control Panel Items\Network and Sharing Center\Advanced sharing settings
password protected sharing-->turn on
create a user with password
select a folder to share -->right click-->properties-->
click on sharing-->click on advanced sharing-->
check on share this folder-->click on permission-->
click on add-->click on advanced-->click on find now-->
select user-->click on ok-->click on ok-->check on full control-->
click on ok-->click on ok-->click on close.

For sharepoint.sandbox.dll
 start-run-> %windir%\assembly\GAC_64\Microsoft.Sharepoint.Sandbox\14.0.0.0__71e9bce111e9429c