.Net Pearls -1 System.IO.Path

It’s been a while since I wrote my lost blog post. I thought start it again. Recently I was looking for a get the extn for a file. Initially it took some time for me to get extension and finally I realized System.IO.Path

Two mostly use full methods in System.IO.Path
class is “GetFileName” and “GetExtension”

    var extn = System.IO.Path.GetExtension(@”c:\temp\text.txt”);

            // Result = .txt

 

    var fileName = System.IO.Path.GetFileName(@”c:\temp\text.txt”);

            //Result = text.txt

 

And finally there may other use full methods in in it.

 

 

Difference between ASP.Net MVC and MVP

Ever since Microsoft released MVC, this is one of the common questions in everyone’s mind is the Difference between MVC and MVP.  The two patterns are having much similarities compare to their differences. The both patterns are evolved on separation of concerns and both contain Views and Models.

But when comes to the difference part, the major difference is the way handling the incoming request. In MVP, the incoming request comes to View and View is delegating it to presenter. And presenter is responsible for
talk to model and update the view. Here model is completely shielding from View. Where as in MVC, all incoming requests are intercepting by the controller and controller is responsible for generating the correct View and Model. Here View is aware of the model

ASP.Net MVP Vs.Asp.Net MVC

The MVP pattern will built on ASP.Net WebForms. The WebForms development paradigm uses Viewstate. In large Web application it will cause some performance issues.  ASP.Net MVC is new alternative frame work and it view is state less.

For more Details read this http://www.aspiringcraftsman.com/2007/08/interactive-application-architecture/

Windows Server 2008 R2 (or Window 7 or SharePoint 2010 VHD) Native boot from VHD

 This is the one of thing recently I have searched most of my time. I thought it would be better if I blogged this.  In my case I have Windows 7 ultimate edition installed on my desktop (Base OS) and I want to install Windows Server 2008 R2 but I don’t want install it on physical drive. So solution is Virtual Hard Disk (VHD) Here my main intention to install Windows Server 2008 R2 is for SharePoint 2010 .Instead of creating a new Virtual Hard Disk and install OS,SharePoint 2010 etc..  I directly download SharePoint trial VHD from internet. http://go.microsoft.com/?linkid=9728417 . I will explain in another post how to install OS in VHD. After downloading all files extract them in a folder. It will extract into a single 45 GB VHD file and everything is installed it. So my next task to make the VHD as native boot (Dual boot). It is very simple, all we have to do is we need to run some DOS commands. Okay, here are the steps   Start –> All Programs –> Accessories –> Command Prompt (Right click – Run as Administrator) It will open command prompt and run the following commands in command prompt.

1.         diskpart
			

2.         select vdisk file=C:\VHD\windows2008.vhd
			

3.         attach vdisk
			

4.         exit
			

In step 2 I have stored my VHD in C:\VHD\Windows2008.vhd. Replace it with your VHD path. Now a new Drive will attach to your computer. Let’s name it as [I ]  it may be different on your computer. Now open the Command Prompt and run the below command, here my new Drive letter is I, make sure you have entered correct Drive, It will copy a bootconfig entry in to your base OS drive

5.      I:\windows\system32\bcdboot  I:\windows 
			

Now it is time to add a native boot VHD to an existing windows 7 boot menu. Before begin it is always safe to back up your exiting bootconfig file.  You can do it by running fowling command in command prompt.

6.     bcdedit /export c:\bcdbackup
			

  Next we will copy any exiting boot entry

7.     bcdedit /copy {default} /d " Name you want display while dual boot"
			

When the bcdedit command executes successfully, it will return a GUID output in the command prompt window. Now set the  device and osdevice  options for boot entry options for boot entry

8.    bcdedit /set {guid} device vhd=[C:]\VHD\windows2008.vhd
			

9.     bcdedit /set {guid} osdevice vhd=[C:]\VHD\windows2008.vhd
			

Make sure that you have copied guid with braces. Some x86-based systems require a boot configuration option for the kernel in order to detect certain hardware information and successfully native-boot from a VHD. At a command prompt, type

10.     bcdedit /set {guid} detecthal on
			

Now all set to go. Restart your computer you will see your new OS in boot menu

Singleton Pattern vs. Static Class

Recently one of my friends asked me the difference between Singleton Pattern and Static Class. I said something really close, but I could not convinence him.  Later I Bing’ed it. I found the wide variety of difference. I consolidated some of them below

First let we see what is Singleton and Static Class over here.

Singleton Pattern: The name it self better describes about it.  Singleton means only once instance of the class. We can define it as a pattern that is used to restrict instantiation of that class to a single instance.

Below code describes the thread safe Singleton Pattern

 
public class SingletonPattern
    {
        private static SingletonPattern _instance = null;
        private static object _lock = new object();

        private SingletonPattern()
        {
        }
        public static SingletonPattern Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new SingletonPattern();
                        }
                    }
                }
                return _instance;
            }
        }

        public void DoSomthing()
        {
        }
    }

In above code SingletonPattern class contains the logic that always ensures that only on instance of the class is created. This is achieved by declaring a private constructor and a Static property of SingletonPattern class type.

The DoSomething method in above SingletonPattern class will be accessed in the code like below

 SingletonPattern.Instance.DoSomthing();

Static Class:  Static Class can be defined as a class that can’t be instantiated. This is achieved by placing a key word Static.  Static class will declared like below

public static class StaticClass

    {

        public static void DoSomthing()

        {

        }

    }

The DoSomething method in above StaticClass will be accessed in the code like below

 
StaticClass.DoSomthing();

I don’t know about you, but to me, there doesn’t appear to be a whole lot of practical difference here. In fact Static Class is much simpler than singleton pattern.

Now the real problem comes in to the picture, what if you want to extend or inherit new class from either of these? By default Static Class are sealed. You can’t extend Static Class. Where Singleton Pattern is take advantage over Static Class and few other differences between them are below.

  1. Singleton pattern will handle objects and subclass very well over Static Classes
  2. Singleton pattern will extend the classes and implement   the interfaces. Where Static Class is does not.
  3. we can easily “Lazy Initialization and asynchronous Initialization” the Singleton Classes
  4. Singleton Instance can be passed as parameter to other methods.

Hope now you are little clearer about Singleton vs. Static Class

How to call an ASP.net WebService (OR WCF Service) using Jquery

After seeing much response to my previous article “How to calls server side code using JavaScript”, I am very much impressed to write this. I would like keep this much simple.

Step 1: Create a new Ajax enabled Website

Step 2: Add a Web Service (common.asmx or .svc file) to it.

Step 3: on Webservice code behind file make sure that add 

<System.Web.Script.Services.ScriptService()>_

Attribute to your class as show in below. This will enable to call your webservice from JavaScript.

 Your Webservice code behind file should look like below. Here we are adding a Web method “SayHello”, which is taking Name as input parameter and returns string as output parameter.

 

<System.Web.Script.Services.ScriptService()> _

Public Class Common

    Inherits System.Web.Services.WebService 

                <WebMethod(True)> _

    Public Function SayHello(ByVal Name As string) AS string

        Return “Hello” + Name

    End Function

End Class

Step 4:  Now on your Default.aspx Add a Textbox and Button (Button1) control

Step 5: Now add a new folder called scripts in your project add new JavaScript file  Common.js

 Step 6: Download Jqery library from http://jquery.com/  add it to your script folder. 

Step 7: Now open your common.js and add the following reference as shown in below

Step 8: add following Jquery function on your common.js file

$(document).ready(function() {

 $(‘[id$=Button1]’).click(function() { 

var serviceurl =  “http://yourservname/common.asmx/SayHello”;

var varName = $(‘[id$=TextBox1]’).text;

var ajaxdata = “{‘Name’:'” + varName + “‘}”;

      $.ajax({

            type: “POST”,

            url: serviceurl,

            data: ajaxdata,

            contentType: “application/json; charset=utf-8”,

            dataType: “json”,

            success: onSucess(response),

            error: onError

        });

        return false;

 });

  }); 

function onSucess(response) {

    alert(response);

function onError() {

    alert(“Error while calling webservice”);

}

Step 9: Now add your common.js  file and Jquery.js file to your default.aspx page and run your application

 Step 10: Enter a name in your text box and click on button.  You will see your javascript calling web service.

Validating an XML File using XSD in .NET .20

Below given is the.NET 1.1 code for validating an XML File using an XSD File.

.NET 1.1 Code

//.NET1.1 code
///
/// Methode to validate XML File
///
///

This method expects input XML as string
///
Path to schema file
/// true if xml is validated else false
private bool ValidateXmlUsingXsd(string XmlData,String SchemaPath)
{
XmlValidatingReader v = new XmlValidatingReader(XmlData, XmlNodeType.Document, null);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);  

while (v.Read())
{
// Can add code here to process the content.
}
v.Close();

return isValid;

}

///

public static void MyValidationEventHandler(object sender,
ValidationEventArgs args)
{
//these two variables should be initialized as class level variables
isValid = false;
errorMessage = “Validation event\n” + args.Message;
///
/// Method to get XML in a string from an XML file
///
///

}

///
private string GetStringFromXML(string fileName)
{
StreamReader rd = new StreamReader(fileName);
string str = rd.ReadToEnd();
rd.Close();
return str;
}

Calling the method :
bool valid = ValidateXmlUsingXsd(str, txtXSD.Text);

There are some changes in the .NET 2.0 code for XML Validation .
XmlValidatingReader is marked as obsolete. Need to use XMLReader.Create() using XmlReaderSettngs instead

There are some behavioral changes between validation using the XmlReaderSettings and XmlSchemaSet classes and validation using the XmlValidatingReader class.

The XmlReaderSettings and XmlSchemaSet classes do not support XML-Data Reduced (XDR) schema validation.

The most important difference I found out is that to do XML data validation using a schema, settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
Flag must be enabled. Otherwise the Schema check error will not be displayed.

//.NET2.0 code
private bool ValidateXmlUsingXsd2(string XmlData,String SchemaPath)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, SchemaPath);
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

More about XmlSchemaValidationFlags Enumeration

StringReader xmlStream = new StringReader(XmlData);
XmlReader reader = XmlReader.Create(xmlStream, settings);
while (reader.Read()) ;

return isValid;
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
isValid = false;
errorMessage = “Validation Error: ” + e.Message;
}

 


Member name
Description
AllowXmlAttributes
Allow xml:* attributes even if they are not defined in the schema. The attributes will be validated based on their data type.
None
Do not process identity constraints, inline schemas, schema location hints, or report schema validation warnings.
ProcessIdentityConstraints
Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation.
ProcessInlineSchema
Process inline schemas encountered during validation.
ProcessSchemaLocation
Process schema location hints (xsi:schemaLocation, xsi:noNamespaceSchemaLocation) encountered during validation.
ReportValidationWarnings
Report schema validation warnings encountered during validation.

In a nutshell, Always set settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; when a schema validation is required for the XML in .NET 2.0

 

///
/// This event handler is called only when a validation error occurs
///
///

Validating an XML File using XSD in .NET .20

Below given is the.NET 1.1 code for validating an XML File using an XSD File.

.NET 1.1 Code

//.NET1.1 code
///
/// Methode to validate XML File
///
///

This method expects input XML as string
///
Path to schema file
/// true if xml is validated else false
private bool ValidateXmlUsingXsd(string XmlData,String SchemaPath)
{
XmlValidatingReader v = new XmlValidatingReader(XmlData, XmlNodeType.Document, null);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);  

while (v.Read())
{
// Can add code here to process the content.
}
v.Close();

return isValid;

}

///

public static void MyValidationEventHandler(object sender,
ValidationEventArgs args)
{
//these two variables should be initialized as class level variables
isValid = false;
errorMessage = “Validation event\n” + args.Message;
///
/// Method to get XML in a string from an XML file
///
///

}

///
private string GetStringFromXML(string fileName)
{
StreamReader rd = new StreamReader(fileName);
string str = rd.ReadToEnd();
rd.Close();
return str;
}

Calling the method :
bool valid = ValidateXmlUsingXsd(str, txtXSD.Text);

There are some changes in the .NET 2.0 code for XML Validation .
XmlValidatingReader is marked as obsolete. Need to use XMLReader.Create() using XmlReaderSettngs instead

There are some behavioral changes between validation using the XmlReaderSettings and XmlSchemaSet classes and validation using the XmlValidatingReader class.

The XmlReaderSettings and XmlSchemaSet classes do not support XML-Data Reduced (XDR) schema validation.

The most important difference I found out is that to do XML data validation using a schema, settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
Flag must be enabled. Otherwise the Schema check error will not be displayed.

//.NET2.0 code
private bool ValidateXmlUsingXsd2(string XmlData,String SchemaPath)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, SchemaPath);
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

More about XmlSchemaValidationFlags Enumeration

StringReader xmlStream = new StringReader(XmlData);
XmlReader reader = XmlReader.Create(xmlStream, settings);
while (reader.Read()) ;

return isValid;
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
isValid = false;
errorMessage = “Validation Error: ” + e.Message;
}

 


Member name
Description
AllowXmlAttributes
Allow xml:* attributes even if they are not defined in the schema. The attributes will be validated based on their data type.
None
Do not process identity constraints, inline schemas, schema location hints, or report schema validation warnings.
ProcessIdentityConstraints
Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation.
ProcessInlineSchema
Process inline schemas encountered during validation.
ProcessSchemaLocation
Process schema location hints (xsi:schemaLocation, xsi:noNamespaceSchemaLocation) encountered during validation.
ReportValidationWarnings
Report schema validation warnings encountered during validation.

In a nutshell, Always set settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; when a schema validation is required for the XML in .NET 2.0

 

///
/// This event handler is called only when a validation error occurs
///
///