Sharepoint Central administration gives a blank page after installing Sharepoint 2007 on Windows 7 64bit

June 6, 2011 Leave a comment

This article shows the solution of the problem I faced after installing sharepoint 2007 on Windows 7 64 bit machine.

Note: this solution is applicable on Sharepoint 2010

The problem is getting a blank page instead of Central Administration after the configuration of Sharepoint on the machine

Cause of the problem:

The following authentication mechanisms are not installed or disabled on the IIS

1- Digest Authentication

2- Basic Authentication

3- Windows Authentication

To install them open command prompt and run the following command

Command:

start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ManagementScriptingTools;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;WCF-NonHTTP-Activation

This will fix the problem.

Categories: IIS7, Sharepoint 2007

Creating a Sharepoint portal for Mobile

May 30, 2011 Leave a comment

Introduction

This article discusses the approach I used to develop a mobile version for a Sharepoint 2010 publishing portal, after a lot of research I found that Sharepoint out of the box features will not fit my business needs, so you will find in this article the approach I used.

Note: I’m not sure that this is the best way to develop a mobile version for sharepoint portal so feel free to send me your feedback and comments if you have a better approach.

Sharepoint 2010 Mobile support limitations

Sharepoint 2010 has a mobile support but after research we found the following limitations

  1. Sharepoint 2010 doesn’t allow to create a custom master page for your mobile site
  2. Sharepoint doesn’t allow creating custom style sheet and classes for mobile
  3. Publishing portal template is not supported
  4. Any layout or any customization in the master pages will affect all other sites on the same farm

The Approach Used in My project

  1. Disable SharePoint default mobile redirection feature to stop the redirection to the mbllists.aspx page.
  2. Create Http Module which detects that the request is coming from a Mobile device and redirect to the Mobile home page.
  3. Create a new sub site for mobile with an optimized master page and layouts for mobile. (Physical pages and user controls).
  4. Multilanguage support
  5. Create the Search Control and search result page from scratch (Querying the Crawler results).
  6. Create optimized style sheets and Masterpage for mobile.

Limitations of this approach

  • The customer will not be able to create any pages for the mobile site from the back end
  • The customer will not be able to create any subsites for the mobile site from the back end
  • Will not be able to use SharePoint search, and the way around is to use SharePoint API and create the search controls and the result page from scratch.

The following sections will explain how to implement each point

1. Disable SharePoint default mobile redirection feature to stop the redirection to the mbllists.aspx page

a. Open compat.browser file you will find it in the following directory

C:\inetpub\wwwroot\wss\VirtualDirectories\[port number]\App_Browsers

b. change isMobileDevice for each browser from True to False and save the file.

Example

<capabilities>
<capability name=”isMobileDevice” value=”false” />
<capability name=”platform” value=”WinCE” />
<capability name=”supportsTouchScreen” value=”true” />
</capabilities>

2. Create Http Module which detects that the request is coming from a Mobile device and redirect to the Mobile home page

This is a normal Http Module which detects that the request is coming from a mobile phone and redirect to the mobile site

Sample function used in the Module

public static bool isMobileBrowser()
{
//GETS THE CURRENT USER CONTEXT
HttpContext context = HttpContext.Current;

            //FIRST TRY BUILT IN ASP.NT CHECK
            if (context.Request.Browser.IsMobileDevice)
{
return true;
}
//THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"]
!= null)
{
return true;
}
//THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains(“wap”))
{
return true;
}
//AND FINALLY CHECK THE HTTP_USER_AGENT
//HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
{
//Create a list of all mobile types
string[] mobiles =
new[]
{
“midp”, “j2me”, “avant”, “docomo”,
“novarra”, “palmos”, “palmsource”,
“240×320″, “opwv”, “chtml”,
“pda”, “windows ce”, “mmp/”,
“blackberry”, “mib/”, “symbian”,
“wireless”, “nokia”, “hand”,”android”, “mobi”,
“phone”, “cdm”, “up.b”, “audio”,
“SIE-”, “SEC-”, “samsung”, “htc”,
“mot-”, “mitsu”, “sagem”, “sony”
, “alcatel”, “lg”, “eric”, “vx”,
“philips”, “mmm”, “xx”,
“panasonic”, “sharp”, “wap”, “sch”,
“rover”, “pocket”, “benq”, “java”,
“pt”, “pg”, “vox”, “amoi”,
“bird”, “compal”, “kg”, “voda”,
“sany”, “kdd”, “dbt”, “sendo”,
“sgh”, “gradi”, “jb”, “dddi”,
“moto”, “iphone”
};

                //Loop through each item in the list created above
                //and check if the header contains that text
                foreach (string s in mobiles)
{
if (context.Request.ServerVariables["HTTP_USER_AGENT"].
ToLower().Contains(s.ToLower()))
{
return true;
}
}
}

return false;
}

We call this function in the OnBeginRequest event handler as the following

public void OnBeginRequest(Object s, EventArgs e)
{

HttpApplication app = s as HttpApplication;
HttpRequest request = HttpContext.Current.Request;

            if (isMobileBrowser())
{
if (!request.Url.ToString().ToLower().Contains(“/mobilesite/”))
{
app.Context.Response.Redirect(“/mobilesite/default.aspx”);
}
}
}

3. Create a new sub site for mobile with an optimized master page and layouts for mobile

a. To do this you create the pages and user controls using the normal ASP.NET

b. To deploy you have to options

1. Create a physical folder for the mobile site under the virtual directory then copy the pages and user controls and master page into it

2. Create the folder under the Sharepoint — using sharepoint designer — then copy the pages and user controls into it (what we implemented)

The benefit of this way is that you don’t have to copy the physical files every time you restore the portal, it will be included in the backup file.

Description: \\linkdotnet.local\linkdev\amr.monjid\Desktop\moca2.jpg

Description: \\linkdotnet.local\linkdev\amr.monjid\Desktop\moca2.jpg

c. Web.config

1. Each name space must be registered as safe in web.config file

Example

<SafeControl Assembly=”MOCA.VideoGallery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=25c226a5c87bfac0″ Namespace=”MOCA.VideoGallery.VideoGallery”TypeName=”*” Safe=”True” SafeAgainstScript=”False” />

<SafeControl Assembly=”MOCA.UserControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=737b390bc690dbba”Namespace=”Linkdev.SharePoint.Search.Controls” TypeName=”*” Safe=”True” SafeAgainstScript=”False” />

4. Multilanguage support

The portal saves the selected language by the user in a cookie then reads this value and changes the culture accordingly

Example:

Save the culture

protected void btnEnglish_click(object sender, EventArgs e)
{
if (Request.Cookies["PMOMobileCulture"] == null)
{
HttpCookie CultureCookie = new HttpCookie(“PMOMobileCulture”);
CultureCookie.Value = “en”;
Response.Cookies.Add(CultureCookie);
}
else
{
Response.Cookies["PMOMobileCulture"].Value = “en”;
}
}

Read the culture

if (Request.Cookies["PMOMobileCulture"] != null)
{
HttpCookie CultureCookie = Request.Cookies["PMOMobileCulture"];
if (!String.IsNullOrEmpty(CultureCookie.Value))
{
if (CultureCookie.Value.ToLower().Contains(“en”))
selectedLanguage = “en”;
else
selectedLanguage = “ar-AE”;
}
else
{
selectedLanguage = “ar-AE”;
}
}
else
{
selectedLanguage = “ar-AE”;

            Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new

                CultureInfo(selectedLanguage);

5. Create the Search Control and search result page from scratch (Querying the Crawler results).

1. Site Crowling

a. From Central Administration Create a new content source under the Search Service Application

b. Select the type of content to be crawled to be (web sites)

c. Add the URL of the portal you want to crawl

Description: \\linkdotnet.local\linkdev\amr.monjid\Desktop\search.jpg

Very Important Note: All links in the site must be normal HTML anchors otherwise the crawler won’t be able to crawl the content

d. Start the Crawler

2. Search Controls and the result page

a. The following code querying the crawling results using the keywords entered by the user

private DataTable Search(string Keywords, out int totalCount)
{

DataTable resultsDataTable = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SearchQueryAndSiteSettingsServiceProxy settingsProxy = SPFarm.Local.ServiceProxies.GetValue<SearchQueryAndSiteSettingsServiceProxy>();
SearchServiceApplicationProxy searchProxy = settingsProxy.ApplicationProxies.GetValue<SearchServiceApplicationProxy>(“MOCA_Search_Service_Application”);

                string squery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.Append(“SELECT Title, Path, Description, Write, Author,Rank, Size FROM Scope() WHERE ContentSource = ‘Mobile Content Source’ and FREETEXT(DEFAULTPROPERTIES,’” + Keywords + “‘) ORDER BY Rank desc”);

                FullTextSqlQuery sqlQuery = new FullTextSqlQuery(searchProxy);
sqlQuery.ResultTypes = ResultType.RelevantResults;
sqlQuery.EnableStemming = true;
sqlQuery.TrimDuplicates = true;
sqlQuery.QueryText = sb.ToString();
ResultTableCollection resultsTableCollection = sqlQuery.Execute();

                ResultTable searchResultsTable = resultsTableCollection[ResultType.RelevantResults];

                resultsDataTable.TableName = “Results”;
resultsDataTable.Load(searchResultsTable, LoadOption.OverwriteChanges);
});

return resultsDataTable;
 }


Categories: Uncategorized

How to Bulk Import and Export to Active Directory

February 21, 2011 Leave a comment

Introduction

In this guide, you will perform the following task:

  • Perform batch operations using the LDIFDE utility. Export users from the Marketing organizational unit (OU) in the Reskit domain into a file format compatible with the LDIF standard format. Perform a batch modification of all the users in the Marketing OU. Use LDIF to create a new user and delete a user.

Requirements and Prerequisites

You must install the Windows 2000 Server operating system, including Active Directory, on a server in your network. You can then run the Administration Tools from the server or from a workstation running the Windows 2000 Professional operating system.

This step-by-step guide assumes that you have run the procedures in A Common Infrastructure for Windows 2000 Server Deployment Step-by-Step Part 1.

The common infrastructure documents specify a particular hardware and software configuration. If you are not using the common infrastructure, you need to make the appropriate changes to this document. For the latest information about hardware requirements and compatibility for servers, clients, and peripherals, see the Windows 2000 Product Compatibility search page (http://www.microsoft.com/windows2000/server/howtobuy/upgrading/compat/default.asp).

The Administration Tools are installed by default on all Windows 2000-based domain controllers. The LDIFDE utility described in this guide is installed by default on servers, and can be copied to any Windows 2000-based workstation. The VBScript programs that you create can be run from either servers or workstations.

For all procedures in this guide, you must be logged on as an administrator. If you log on using an account that does not have administrative privileges, you may not be able to perform export and import operations in Active Directory.

Using the LDIFDE Utility

 

The LDAP Data Interchange Format (LDIF) is an Internet draft standard for a file format that can be used for performing batch operations on directories that conform to the LDAP standards. LDIF can be used to export and import data, allowing batch operations such as Add, Modify, and Delete to be performed in Active Directory. A utility called LDIFDE is included in the Windows 2000 operating system to support batch operations based on the LDIF standard.

Using LDIF to Export All Objects in the Marketing OU

You can use LDIFDE to export all objects in the Marketing organizational unit (OU), created in ” Step-by-Step Guide to Common Infrastructure Part 1“. This example searches the organizational unit for certain objects and creates a file containing the names of those objects.

To export all objects in the Marketing OU

  1. Click Start, point to Programs, then point to Accessories, and click Command Prompt.
  2. At the command prompt, type:ldifde -f marketing.ldf -s hq-res-dc-01-d”ou=Marketing,dc= reskit,dc=com”-psubtree–r”(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=reskit,DC=com)”

This creates a LDIF file named Marketing.ldf, by connecting to the server named HQ-RES-DC-01 and executing a subtree search of the Marketing OU for all objects of the category Person. (See Figure 1 below.)

Note that objectCategory is an indexed attribute designed to enhance search performance.

Bb727091.bulkst01(en-us,TechNet.10).gif

Figure 1: Creating an LDF file

You can use this LDIF file to perform a batch import of all the objects from the Marketing OU into any other LDAP-compatible directory. Some attributes may not be applicable to other implementations of LDAP. In particular, if you use this mechanism to import the objects into another Active Directory, some attributes must be omitted because they are automatically generated during object creation. (If they are not specifically omitted, the operation will fail.)

For example, the LDIFDE command that is used to omit these attributes is:

ldifde -f marketing.ldf -s hq-res-dc-01 d
“ou=Marketing,dc= reskit,dc=com”–r
>”(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=reskit,DC=com)” –m

Using LDIF to Modify All Objects in the Marketing OU

In this example, the entire Marketing organization has moved to a new office address. You use LDIF to perform a batch modification for all user objects in the Marketing organization by altering the state, street, locality, and postal code attributes.

To modify all objects in the Marketing OU

  1. Click Start, point to Programs, then point to Accessories, and click Command Prompt.
  2. At the command prompt, type the following command to extract the required entries:ldifde -f marketing.ldf -s hq-res-dc-01-d”ou=Marketing,dc= reskit,dc=com”-psubtree–r”(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=reskit,DC=com)” –l “l,st,streetAddress, postalCode”
  3. Use a text editor such as Notepad to edit the LDIF file, Marketing.ldf. (Save the file as an .ldf file.) Modify each entry so that it is similar to that shown in Figure 2 below.

Bb727091.bulkst02(en-us,TechNet.10).gif

Figure 2: Editing attributes for a move
  • Run LDIFDE to import the modifications into Active Directory. At the command prompt, type the following command, and then press > Enter. (See Figure 3 below.)ldifde –i -f marketing.ldf -s hq-res-dc-01
  •  

    Bb727091.bulkst03(en-us,TechNet.10).gif

    Figure 3: Importing modifications into the Active Directory

  • To confirm that the entries have been modified, check the Active Directory Users and Computers snap-in. (For help with using this snap-in, see the Step-by-Step Guide to Managing the Active Directory. )
  • For further information on using LDIFDE, type LDIFDE /? at the command prompt.

    Note: Another utility called CSVDE performs the same export functions as LDIFDE, but uses a comma-separated file format. Import operations with CSVDE are “add” only, and CSVDE does not offer the ability to modify or delete objects. The CSV file format is supported by applications such as Microsoft Excel.

    Using LDIF to Create a New User

    In this example, you use LDIF to add a new user named James Smith to the Marketing organizational unit.

    1. Start a text editor, such as Notepad, and create a new text file named Newuser.ldf. (Save the file as an ldif file, not as a text file.)
    2. Edit the LDIF file Newuser.ldf, and add the following text (see Figure 4 below):dn: CN=JamesSmith,OU=Marketing,DC=reskit,DC=comchangetype: add
      cn: James Smith
      objectClass: user
      samAccountName: James
      > givenName: James
      > sn: Smith
    3. Save and close the LDIF file.
    4. Run LDIFDE to import the new user into Active Directory. On the Start menu, point to Programs, then point to Accessories, and click Command Prompt. Type the following command, and then press Enter.ldifde –i -f newuser.ldf -s hq-res-dc-01
    5. To confirm that the new user has been created, check the Active Directory Users and Computers snap-in.

     

    Bb727091.bulkst04(en-us,TechNet.10).gif

    Figure 4: Adding a new user to the Marketing OU

    Using LDIF to Delete a User

    In this example, you use LDIF to remove the user named James Smith from the Marketing OU.

    1. Start a text editor such as Notepad, and create a new file named Deluser.ldf.
    2. Edit the LDIF file Deluser.ldf, and add the following text.dn: CN=JamesSmith,OU=Marketing,DC=reskit,DC=comchangetype: deleteFigure 5: Remove James Smith from OU
      Figure 5: Remove James Smith from OU
    3. Run LDIFDE to delete the user from Active Directory. At the command prompt, type the following command, and then press Enter.ldifde –i -f deluser.ldf -s hq-res-dc-01
    4. To confirm that the user has been deleted, check the Active Directory Users and Computers snap-in.

    Source: Microsoft Technet

    Anonymous methods in C#

    December 15, 2010 Leave a comment

     

    Introduction:

    As you may know, if the caller want to respond to any event, it must create a method -(event handler) that matches the signature of it’s associated delegate. Such method is only called by the event associated delegate object.

    (if you don’t know about delegates and events see my articles Delegates in C#, Events in C#).

    Example:

    public
    class MyClass
    {
    public delegate void MyDelegate(string message);
    public event MyDelegate MyEvent;
    public void RaiseMyEvent(string msg)
    {
    if (MyEvent != null)
    MyEvent(msg);
    }
    }
    class Caller
    {
    static void Main(string[] args)
    {
    MyClass myClass1 = new MyClass();
    myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);
    myClass1.RaiseMyEvent(“Hiii”);
    }
    //this method called only by MyDelegate
    public static void myClass1_MyEvent(string message)
    {
    //do some thing to respond to the event here
    }
    }

    As you can see, event handler methods such as (myClass1_MyEvent) are never called by any part of the application other than the invoking delegate so you need it only to handle you event.

    You can associate a delegate directly to a block of code statements at the time of event registration. Such code is named anonymous method.

    The next example will show you how to handle the events using anonymous methods:

    namespace AnonymousMethods

    {

    public class MyClass

    {

    public delegate void MyDelegate(string message);

    public event MyDelegate MyEvent;

    public void RaiseMyEvent(string msg)

    {

    if (MyEvent != null)

    MyEvent(msg);

    }

    }

    class Caller

    {

    static void Main(string[] args)

    {

    MyClass myClass1 = new MyClass();

    //Register event handler as anonymous method.

    myClass1.MyEvent += delegate

    {

    Console.WriteLine(“we don’t make use of your message in the first handler”);

    };

    //Register event handler as anonymous method.

    //here we make use of the incoming arguments.

    myClass1.MyEvent += delegate(string message)

    {

    Console.WriteLine(“your message is: {0}”, message);

    };
    //the final bracket of the anonymous method must be terminated by a semicolon.

    Console.WriteLine(“Enter Your Message”);

    string msg = Console.ReadLine();

    //here is we will raise the event.

    myClass1.RaiseMyEvent(msg);

    Console.ReadLine();

    }

    }
    }

    Notice that when you use the anonymous methods you don’t need to define any static event handlers. Rather, the anonymous methods are defined at the time the caller is handling the event.

    Note: You are not required to receive the incoming arguments sent by a specific event. but if you want to make use of the incoming arguments you will need to specify the parameters defined by the delegate type (just like the second handler in the previous example).

    Example:

    myClass1.MyEvent += delegate(string message)

    {

    Console.WriteLine(“your message is: {0}”, message);

     

    };

    we’re done, I hope you now have a good understanding of anonymous methods in C#.

    Categories: .NET, C#

    Working with binary large objects (BLOBs)

    December 15, 2010 Leave a comment

    Introduction:

    You can define a BLOB as a large photo, document, audio etc. saved in binary formats that you want to save in a database.
    Saving and retrieving BLOBs in a database is more complex than querying string or numeric data.

    The BLOB may be very large and if you try to move it in one piece will consume a lot of system memory and that for sure will affect your application performance.

    To reduce the amount of system memory you have to break up the BLOB into smaller pieces.

    There are a lot of classes that are designed for moving large amount of binary data like BinaryRader, BinaryWriter which exists in System.IO namespace. In the next paragraphs you will see how to use all of this.

    Saving a BLOB value to the database:

    To save a BLOB value to database we use FileStream and BinaryReader classes.

    The next example will show you the process of saving a BLOB to a database.

     

    string filePath = @“D:\\My Movie.wmv”;

     

     

    //A stream of bytes that represnts the binary file

     

    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

     

     

    //The reader reads the binary data from the file stream

     

    BinaryReader reader = new BinaryReader(fs);

     

     

    //Bytes from the binary reader stored in BlobValue array

     

    byte[] BlobValue = reader.ReadBytes((int)fs.Length);

     

     

    fs.Close();

     

    reader.Close();

     

     

    SqlConnection BlobsDatabaseConn = new SqlConnection(“Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI”);
    SqlCommand SaveBlobeCommand = new SqlCommand();

     

    SaveBlobeCommand.Connection = BlobsDatabaseConn;

     

    SaveBlobeCommand.CommandType = CommandType.Text;

     

    SaveBlobeCommand.CommandText = “INSERT INTO BlobsTable(BlobFileName, BlobFile)” + “VALUES (@BlobFileName, @BlobFile)”;

     

     

    SqlParameter BlobFileNameParam = new SqlParameter(“@BlobFileName”, SqlDbType.NChar);

     

     

    SqlParameter BlobFileParam = new SqlParameter(“@BlobFile”, SqlDbType.Binary);

     

    SaveBlobeCommand.Parameters.Add(BlobFileNameParam);

     

    SaveBlobeCommand.Parameters.Add(BlobFileParam);

     

    BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf(“\\”) + 1);

     

    BlobFileParam.Value = BlobValue;

     

    try

     

    {

     

    SaveBlobeCommand.Connection.Open();

     

    SaveBlobeCommand.ExecuteNonQuery();

     

    MessageBox.Show(BlobFileNameParam.Value.ToString() + ” saved to database.”,“BLOB Saved”, MessageBoxButtons.OK, MessageBoxIcon.Information);

     

    }

     

     

    catch(Exception ex)

     

     

    {

     

    MessageBox.Show(ex.Message, “Save Failed”, MessageBoxButtons.OK, MessageBoxIcon.Error);

     

    }

     

     

    finally

     

     

    {

     

    SaveBlobeCommand.Connection.Close();

     

    }

    Retrieving a BLOB from the database:

    To retrieve a BLOB value from database we use FileStream and BinaryWriter classes.

    The next example will show you the process of retrieving a BLOB to a database.

    NOTE: you will see that we set the CommandBehavior to SquentialAccess when we call ExecuteReader() method, this allow us to use the GetBytes() method of the SqlDataRader, so we can read the BLOB from database in smaller, user-definable amounts.

    string
    SavePath = @“D:\\My BLOBs”;

     

    SqlConnection SaveConn = new SqlConnection(“Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI”);

     

    SqlCommand SaveCommand = new SqlCommand();

     

    SaveCommand.CommandText = “Select BlobFileName, BlobFile from BlobsTable where BlobFileName = @BlobFileName”;

     

    SaveCommand.Connection = SaveConn;

     

    SaveCommand.Parameters.Add(“@BlobFileName”, SqlDbType.NVarChar).Value = “My Movie.wmv”;

     


    //the index number to write bytes to

     

    long CurrentIndex = 0;

     


    //the number of bytes to store in the array

     

    int BufferSize = 100;

     


    //The Number of bytes returned from GetBytes() method

     

    long BytesReturned;

     


    //A byte array to hold the buffer

     

    byte[] Blob = new byte[BufferSize];

     


    SaveCommand.Connection.Open();

     


    //We set the CommandBehavior to SequentialAccess

     

    //so we can use the SqlDataReader.GerBytes() method.

     


    SqlDataReader
    reader = SaveCommand.ExecuteReader(CommandBehavior.SequentialAccess);

     


    while
    (reader.Read())

     

    {

     

    FileStream fs = new FileStream(SavePath + “\\” + reader["BlobFileName"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);

     

     

    BinaryWriter writer = new BinaryWriter(fs);

     

     

    //reset the index to the beginning of the file

     

     

    CurrentIndex = 0;

     

     

    BytesReturned = reader.GetBytes(1, //the BlobsTable column indexCurrentIndex, // the current index of the field from which to begin the read operationBlob, // Array name to write tha buffer to0, // the start index of the array to start the write operationBufferSize // the maximum length to copy into the buffer);

     

     

    while (BytesReturned == BufferSize)

     

    {

     

    writer.Write(Blob);

     

    writer.Flush();
    CurrentIndex += BufferSize;

     

    BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);

     

    }

     

    writer.Write(Blob, 0, (int)BytesReturned);

     

    writer.Flush(); writer.Close();

     

    fs.Close();

     

    }

     

    reader.Close();

     

    SaveCommand.Connection.Close();

    To fully understand the concept you need to try to write this code yourself.

    Note: The database and the full source code in the source code area with this article.

    Categories: .NET, C#, Windows Application

    The third pillar of object-oriented programming – polymorphism

    December 15, 2010 Leave a comment

    Introduction:

    You can define polymorphism as the ability of treating related types in the same way.  Polymorphism give the base class the ability of defining a set of behaviors that the childe classes can override, so each childe class will redefine how it will respond to the same behavior.

    The virtual methods:

    A virtual is a method in a base class which the childe class can reuse it or redefine and customize its behavior to be appropriate to its functionality.

    To create an overridable method that can be overridden by childe class you must define this method as (virtual)

    //this method can be overridden by any childe class

    public virtual void Move()

    {

    //do some thing in the base class

    }

    Example:

    public class Car

    {

    string model;

    int currentSpeed;

    int maxSpeed;

    public Car()

    { }

    //this method can be overridden by any childe class

    public virtual void Move()

    {

    //do some thing in the base class

    Console.WriteLine(“Your car is moving now”);

    }

    }

    If any childe class want to redefine the virtual method it need to use the override keyword, so if we want to override the Move() virtual method in the base class Car we need to do the following:

    public class SportCar : Car

    {

    public override void Move()

    {

    //Write a new implementation here

    }

    }

    Using the default implementation of the virtual method:

    When you override a virtual method from the base class, you can use the default implementation of the base class method. You can do this by using the (base) keyword to call the virtual method which in the base class.

    As you can see in the overridden method, we used the base keyword to call the Move method in the base class so we are using now the implementation of the Move() method in the base class.

    public override void Move()

    {

    //The default implementation

    base.Move();

    }

    Example:

    SportCar sportsCar1 = new SportCar();

    //Calling the overridden method

    sportCar1.Move();

    The result:

    Your car is moving now

    If you do not want to use the default implementation of  the base class method you can remove the (base.Move) form the overridden method and then reimplement the method by writing a new code that belong to it as follow:

    public override void Move()

    {

    //Write a new implementation here

    Console.WriteLine(“Sport car is moving now”);

    }

    Example:

    SportCar sportsCar1 = new SportCar();

    //Calling the overridden method

    sportCar1.Move();

    The result:

    Sport car is moving now

    You can also combine by using the virtual   method implementation and the overridden method implementation by keeping the (base.Move) in the overridden method implementation

    public override void Move()

    {

    //Using the default implementation

    base.Move();

    //Write a new implementation here

    Console.WriteLine(“Sport car is moving now”);

    }

    Note that the overridden method considered as virtual method to the subclasses of the subclass. So if create a new class that inherit from the SportCar class, you can override the Move() method in at as if it is a virtual method.

    Example:

    public class SportCar : Car

    {

    public override void Move()

    {

    //Write a new implementation here

    Console.WriteLine(“Sport car is moving now”);

    }

    }

    public class RedSportCar : SportCar

    {

    public override void Move()

    {

    //Using the SportCar.Move() method

    base.Move();

    }

    }

    Note: SportCar.Move() method work as a virtual method to the RedSportCar class.

    The sealed keyword:

    You can use the sealed keyword with virtual methods if you want to prevent the subclasses form overridden the base classes methods.

    Example:

    public class SportCar : Car

    {

    //This method can not be overridden by subclasses

    public override sealed void Move()

    {

    //Write a new implementation here

    Console.WriteLine(“Sport car is moving now”);

    }

    }

    public class RedSportCar : SportCar

    {

    //Compile time error

    //The SportCar.Move() can not be overridden

    public override void Move()

    {

    base.Move();

    }

    }

    The abstract methods:

    If you create a virtual method in the base class it is up to the subclass to override or not to override it. What if you want to enforce the subclasses to extend the base class members? To do so you need to use abstract methods.

    Abstract methods are a method with no implementation, and it is a part of an abstract class. Any subclass that derived from this base abstract class must override the abstract method or there will be a compile time error.

    Example:

    public abstract class Car

    {

    //the abstract method

    //abstract method doesn’t have a body

    public abstract void Move();

    }

    public class SportCar : Car

    {

    //the SportCar class must override the

    //abstract method Move().

    public override void Move()

    {

    //Write a new implementation here

    Console.WriteLine(“Sport car is moving now”);

    }

    }

    Note: Only abstract classes can have abstract methods.

    Categories: .NET, C#

    The second pillar of Object-Oriented Programming – Inheritance

    December 15, 2010 Leave a comment

    Introduction:

    Inheritance gives you the ability of building a new classes based on existing class. So that it allows you to extend a base class by enabling a new class to inherit its characteristics and behavior.

    The greatest thing with inheritance is that it gives you the ability of code reuse, so if you have a class which has some functionality, characteristics and behavior and you want to create another class which will has the same functionality but with some new characteristics and behaviors so instead of create a brand new class that have the same code you done before, all you need to is to create the new class and add to it only the new characteristics and behavior and inherit the other from the old class.

    The base class:

    The base class is a normal class that has characteristics (variables) and behaviors (methods) that are common for all subclasses.

    Example:

    public class Car

    {

    string model;

    int currentSpeed;

    int maxSpeed;

    public Car()

    { }

    public Car(string model, int currentSpeed, int maxSpeed)

    {

    this.model = model;

    this.currentSpeed = currentSpeed;

    this.maxSpeed = maxSpeed;

    }

    public string Model

    {

    get { return model; }

    set { model = value; }

    }

    public int CurrentSpeed

    {

    get { return currentSpeed; }

    set { currentSpeed = value; }

    }

    public int MaxSpeed

    {

    get { return maxSpeed; }

    set { maxSpeed = value; }

    }

    }

    As you can see the car class has characteristics that any car of each type can have so it have the general variables that are common for any car.

    The Subclass (derived class):

    The subclass is a class that inherit its core functionality from a base class then it add its own functionality

    Example:

    public class BMW : Car

    {

    }

    We left our BMW class with out adding any variables or methods so the BMW class is the same as the Car class so if you tried to use it you will see that it have all characteristics of the Car class.

    Example:

    BMW bmw1 = new BMW();

    bmw1.Model = “X5″;

    bmw1.CurrentSpeed = 0;

    bmw1.MaxSpeed = 230;

    So let us see how we can extend our Car type by adding some functionality to its childe BMW.

    Creating the subclass:

    As I said all you need to do with your subclass is to add the new functionality to it and it will inherit all the common functionality from the base class.

    Example:

    public class BMW : Car

    {

    bool isFullOption;

    bool hasDVD;

    public BMW()

    { }

    public BMW(string model, int currentSpeed, int maxSpeed, bool isFullOption, bool hasDVD)

    {

    //using the BMW class variables

    this.isFullOption = isFullOption;

    this.hasDVD = hasDVD;

    //using the CAR class properties

    Model = model;

    CurrentSpeed = currentSpeed;

    MaxSpeed = maxSpeed;

    }

    }

    As you saw we create the BMW subclass and add two other variables to it (isFullOption, hasDVD) also we created a custom constructor and use it to assign the value of the BMW class variables and the properties inherited from the base class Car.

    Using the base class constructors:

    Instead of creating a custom constructor in the subclass that have the same code in the base class constructor, we can create a constructor that call the base class constructor and use the subclass constructor to assign values to the variables that belongs to the subclass.

    Example:

    public class BMW : Car

    {

    bool isFullOption;

    bool hasDVD;

    public BMW()

    { }

    public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

    : base(model, currentSpeed, maxSpeed)

    {

    //using the BMW class variables

    this.isFullOption = isFullOption;

    this.hasDVD = hasDVD;

    }

    }

    We here create a custom constructor in the subclass and we will use it to receive values from the object user like (isFullOption, hasDVD, model, currentSpeed, and maxSpeed) and then we assigned the (isFullOption, hasDVD) values in the subclass constructor and pass the (model, currentSpeed, and maxSpeed) values to the base class constructor.

    BMW bmw1 = new BMW(true, true, “X5″, 100, 230);

    the first two parameters will be used by the subclass constructor and the last three will be use by the base class constructor.

    Allowing the subclass to see the base class variables (the protected keyword):

    as you saw previously all the base class members are private so the subclass can not see it and can only deal with it by its properties, so if we want the subclasses to see the variables of the base class we have to redefine these variables as protected.

    public class Car

    {

    protected string model;

    protected int currentSpeed;

    protected int maxSpeed;

    public Car()

    { }

    public Car(string model, int currentSpeed, int maxSpeed)

    {

    this.model = model;

    this.currentSpeed = currentSpeed;

    this.maxSpeed = maxSpeed;

    }

    }

    The protected keyword means that the base class variables are accessible only by the subclasses and private to all other classes.

    By using protected members we created a level of trust between the base and derived classes.

    We now can use the Car class variables directly in the BMW subclass with out using any properties.

    public class BMW : Car

    {

    bool isFullOption;

    bool hasDVD;

    public BMW()

    {

    //we now can use the member of the base class

    currentSpeed = 0;

    maxSpeed = 230;

    }

    public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

    : base(model, currentSpeed, maxSpeed)

    {

    //using the BMW class variables

    this.isFullOption = isFullOption;

    this.hasDVD = hasDVD;

    }

    }

    The sealed classes:

    We can create classes that can not be inherited by using sealed keyword in the class definition, so if we tried to inherit from a sealed class we will have a compile time error.

    Example:

    We can define our BMW class as sealed class

    public sealed class BMW : Car

    {

    bool isFullOption;

    bool hasDVD;

    public BMW()

    {

    //we now can use the member of the base class

    currentSpeed = 0;

    maxSpeed = 230;

    }

    public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

    : base(model, currentSpeed, maxSpeed)

    {

    //using the BMW class variables

    this.isFullOption = isFullOption;

    this.hasDVD = hasDVD;

    }

    }

    If we tried to inherit from BMW class we will have a compile time error.

    //Compile time error

    public class MiniCoper : BMW

    {

    }

    Note: C# dose not allow multiple base classes, so any class can inherit only from one base class.

    Categories: .NET, C#
    Follow

    Get every new post delivered to your Inbox.