Showing posts with label .Net Tips and Tricks. Show all posts
Showing posts with label .Net Tips and Tricks. Show all posts

Tuesday, October 18, 2011

Web Site performance


A modern web page requires the browser to make a number of requests to the web server for a page to download all its content. Most of the root cause analysis found that the web server spends 10-20 % of time in serving the dynamic part (code part) and rest of the time in serving most of the static content like CSS, JavaScript and Images. Correcting these web performance issues not only saves money by consuming less bandwidth but also saves money on infrastructure investments (less servers). Before we proceed some of the tools that help in monitoring the performance of web sites are Fiddler, Network Monitor and IIS logs. Fiddler and Network Monitor are freely downloadable from Microsoft.
Please remember the three key performance rules. All our performance suggestion will revolve around these rules
  •   Try to reduce the number of http calls to the server
  •   Send as little as possible
  •   Send as infrequently as possible

To do a performance improvement of a web site one should first consider
  •       Infrastructure Improvements which focus on IIS and other network settings 
  •       Frontend Improvements


Infrastructure Improvements

Let’s get started with the infrastructure improvements which include 5 key areas. They are HttpCompression, Content Expiration, Content Distribution Network (CDNs), eTags, HttpHeaders. Please note that the infrastructure and frontend improvements are not limited to the items that are discussed in this post.

HttpCompression: One of the performance rules is to send as little as possible. IIS by default allows you send request in Http Compression. It is possible to send the compressed http request with both IIS 6.0 and IIS 7 and above. In IIS 7 by default compress static files. The compressed version consumes a less bandwidth and at times it reduces bandwidth up to 30-50%. There are two important factor you must consider before enabling HttpCompression.

  • 1.      Check applicationHost.config file and make sure the images are not enabled for compression. Images have their own compression logic and might cause bad performance if IIS compression is enabled for images.
  • 2.      IIS 7 & above uses CPU for http compression. Although not official by Microsoft but it is likely to be around 1%.  IIS 7 has option to turn off the compression if the CPU usage goes beyond a certain preset limit. But looking at the benefits we are going to achieve it is advisable to enable it.


Content expiration: Based on the send as infrequent possible rule, we can use the client browser caching. Set up the up the expiration for all static content of your application. A good candidate for setting up the expiration are the static image, JavaScript files and CSS files. You may set the expiration based on your website needs.

Content Distribution Network (CDN): One of the items that we can think of is CDN. Let’s say a file which we want to refer in our internet site (say a JQuery file) instead of serving from our web server it is better to serve it from major player Microsoft etc. Major players have the CDN infrastructure to serve the page from a geographically closer location.
Although it adds some amount of performance improvement, one of the biggest disadvantages that it adds another failure point to your web application. If the major player site is down for some reason this will impact your site as well.

Removing E-Tags and Unnecessary Headers: One of the performance rules is ‘Send as little as possible’. By default IIS adds E-Tags and unnecessary headers like the version of ASP.Net etc with each request which you may not wish to show to the client browser. We may write a simple httpModule code to remove the unnecessary headers.
Note: we may need to have a careful consideration before trying something with the httpModules as it might have a negative impact as well.

Frontend performance Techniques
Externalize CSS & JavaScript: One of the performance rules again is to send as little as possible. With externalizing the CSS and JavaScript we can leverage the below

a.      Reduce the page size
b.      Allow reuse of the file
c.      Allows us to set the expiration of the file which helps in browser caching.

Minification and Consolidation: Again with respect to send as little as possible, minification and consolidation plays a major role. Often the JavaScript, CSS files have lots of comments, blank spaces which goes to production as is. While it is necessary for the developer to understand the comments it is not necessary to move the same files to production. Minification of the file removes all the unnecessary items that need not move to production. Consolidation again removes number of https calls to the server. So instead of having multiple try to consolidate files as much as possible.

Tools that can be used for this is MS Build.

Image optimization: Image optimization plays a major role in the in the send as little as possible rule mentioned earlier. Free tools like Paint.Net have a ways to compress the images. To human eye it would not make any difference between the compressed and uncompressed images.

CSS Sprite: If you have multiple small images, whenever you web site is request the client makes a call to the server for each of the images. To reduce the number of hits on the server we can use the CSS sprites, where we can club multiple images into a single image file and css to control which section of the image to be shown.

There are multiple CSS sprite tools available online which generate a single image file and CSS from a number of images.

Apart from the infrastructure and frontend improvements there are miscelinious performance options like caching, tools like YSlow, making async calls etc to improve the performance. Again those can be explored as whenever it is necessary. I hope you enjoyed the content and happy coding.

Saturday, January 29, 2011

Dependency property in WPF

Here is sample application for dependency properties. Here is a person class whose property triggers a notification when the values are changed

person.cs class


public class Person :DependencyObject
    {
        public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register
            ("LastName", typeof(string), typeof(Person));
        public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register
            ("FirstName", typeof(string), typeof(Person));


        public string LastName
        {
            get
            {
                return (string)GetValue(LastNameProperty);
            }
            set
            {
                SetValue(LastNameProperty, value);
            }
        }
        public string FirstName
        {
            get
            {
                return (string)GetValue(FirstNameProperty);
            }
            set
            {
                SetValue(FirstNameProperty, value);
            }
                
        }
      
        public string Name
        {
            get { return this.LastName + "," + this.FirstName; }
        }
    }

Here is the XAML file



    
        
    
    
        
            

            

            
        
    



 public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            BindData();
        }
        private void BindData()
        {
         base.DataContext = new Person { FirstName = "puru", LastName = "adhikari" };
        }
    }
Hope this helps :)

Tuesday, July 6, 2010

UrlReferrer property in ASP.Net

For a scenario where you want to reload the previous page on click event of the Back Button of New redirected page, the following solution will be helpful.

Sol:- You need to use UrlReferrer property of Request object to access the previous page URL.

Code:-
In the code behind file of the New Page.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //check if the webpage is loaded for the first time.
{
ViewState["PreviousPage"] =
Request.UrlReferrer;//Saves the Previous page url in ViewState
}
}

protected void btnBack_Click(object sender, EventArgs e)
{
if (ViewState["PreviousPage"] != null) //Check if the ViewState
//contains Previous page URL
{
Response.Redirect(ViewState["PreviousPage"].ToString());//Redirect to
//Previous page by retrieving the PreviousPage Url from ViewState.
}
}

Monday, July 5, 2010

?? operator in C#

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. For example:

int? x = null;
...
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
The ?? operator also works with reference types:

//message = param, unless param is null
//in which case message = "No message"
string message = param ?? "No message";

Monday, June 28, 2010

DataReade CommandBehavior.CloseConnection

When returning DataReader from a function, specify CommandBehavior.CloseConnection
When you create an ADO.NET DataReader object, specify the CommandBehavior.CloseConnection enumeration in your call to ExecuteReader. This ensures that when you close the DataReader, the SQL connection is also closed. This is especially helpful when you return a DataReader from a function, and you do not have control over the calling code. If the caller forgets to close the connection but closes the reader, both are closed when the DataReader is created by using CommandBehavior.CloseConnection. This is shown in the following code fragment.

public SqlDataReader CustomerRead(int CustomerID)

{

//... create connection and command, open connection

return myCommand.ExecuteReader(CommandBehavior.CloseConnection);

}



//... client code

SqlDataReader myReader = CustomerRead(10248);

//... read some data

myReader.Close(); // reader and connection are closed

Sunday, June 27, 2010

What is the difference between URL and URI?

A URL is the address of some resource on the web, which means that normally you type the address into a browser and you get something back. There are other type of resources than web pages, but that's the easiest conceptually. The browser goes out somewhere on the internet and accesses something.

A URI is just a unique string that uniquely identifies something, commonly a namespace. Sometimes they look like a URL that you could type into the address bar of your web browser, but it doesn't have to point to any physical resource on the web.

URI is the more generic term, and a URL is a particular type of URI in that a URL has to uniquely identify some resource on the web.

Saturday, June 26, 2010

Url Rewriting with ASP.NET,C#

People often ask me for guidance on how they can dynamically "re-write" URLs and/or have the ability to publish cleaner URL end-points within their ASP.NET web applications. This blog post summarizes a few approaches you can take to cleanly map or rewrite URLs with ASP.NET, and have the option to structure the URLs of your application however you want.

Why does URL mapping and rewriting matter?
The most common scenarios where developers want greater flexibility with URLs are:

1) Handling cases where you want to restructure the pages within your web application, and you want to ensure that people who have bookmarked old URLs don't break when you move pages around. Url-rewriting enables you to transparently forward requests to the new page location without breaking browsers.

2) Improving the search relevancy of pages on your site with search engines like Google, Yahoo and Live. Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites, which can often increase the chance of someone clicking your link. Moving from using querystring arguments to instead use fully qualified URL's can also in some cases increase your priority in search engine results. Using techniques that force referring links to use the same case and URL entrypoint (for example: weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) can also avoid diluting your pagerank across multiple URLs, and increase your search results.

In a world where search engines increasingly drive traffic to sites, extracting any little improvement in your page ranking can yield very good ROI to your business. Increasingly this is driving developers to use URL-Rewriting and other SEO (search engine optimization) techniques to optimize sites (note that SEO is a fast moving space, and the recommendations for increasing your search relevancy evolve monthly). For a list of some good search engine optimization suggestions, I'd recommend reading the SSW Rules to Better Google Rankings, as well as MarketPosition's article on how URLs can affect top search engine ranking.

Sample URL Rewriting Scenario
For the purpose of this blog post, I'm going to assume we are building a set of e-commerce catalog pages within an application, and that the products are organized by categories (for example: books, videos, CDs, DVDs, etc).

Let's assume that we initially have a page called "Products.aspx" that takes a category name as a querystring argument, and filters the products accordingly. The corresponding URLs to this Products.aspx page look like this:

http://www.store.com/products.aspx?category=books
http://www.store.com/products.aspx?category=DVDs
http://www.store.com/products.aspx?category=CDs
Rather than use a querystring to expose each category, we want to modify the application so that each product category looks like a unique URL to a search engine, and has the category keyword embedded in the actual URL (and not as a querystring argument). We'll spend the rest of this blog post going over 4 different approaches that we could take to achieve this.

Approach 1: Use Request.PathInfo Parameters Instead of QueryStrings

The first approach I'm going to demonstrate doesn't use Url-Rewriting at all, and instead uses a little-known feature of ASP.NET - the Request.PathInfo property. To help explain the usefulness of this property, consider the below URL scenario for our e-commerce store:

http://www.store.com/products.aspx/Books
http://www.store.com/products.aspx/DVDs
http://www.store.com/products.aspx/CDs
One thing you'll notice with the above URLs is that they no longer have Querystring values - instead the category parameter value is appended on to the URL as a trailing /param value after the Products.aspx page handler name. An automated search engine crawler will then interpret these URLs as three different URLs, and not as one URL with three different input values (search engines ignore the filename extension and just treat it as another character within the URL).

You might wonder how you handle this appended parameter scenario within ASP.NET. The good news is that it is pretty simple. Simply use the Request.PathInfo property, which will return the content immediately following the products.aspx portion of the URL. So for the above URLs, Request.PathInfo would return "/Books", "/DVDs", and "/CDs" (in case you are wondering, the Request.Path property would return "/products.aspx").

You could then easily write a function to retrieve the category like so (the below function strips out the leading slash and returning just "Books", "DVDs" or "CDs"):

Function GetCategory() As String

If (Request.PathInfo.Length = 0) Then
Return ""
Else
Return Request.PathInfo.Substring(1)
End If

End Function
Sample Download: A sample application that I've built that shows using this technique can be downloaded here. What is nice about this sample and technique is that no server configuration changes are required in order to deploy an ASP.NET application using this approach. It will also work fine in a shared hosting environment.

Approach 2: Using an HttpModule to Perform URL Rewriting
An alternative approach to the above Request.PathInfo technique would be to take advantage of the HttpContext.RewritePath() method that ASP.NET provides. This method allows a developer to dynamically rewrite the processing path of an incoming URL, and for ASP.NET to then continue executing the request using the newly re-written path.

For example, we could choose to expose the following URLs to the public:

http://www.store.com/products/Books.aspx
http://www.store.com/products/DVDs.aspx
http://www.store.com/products/CDs.aspx
This looks to the outside world like there are three separate pages on the site (and will look great to a search crawler). By using the HttpContext.RewritePath() method we can dynamically re-write the incoming URLs when they first reach the server to instead call a single Products.aspx page that takes the category name as a Querystring or PathInfo parameter instead. For example, we could use an an Application_BeginRequest event in Global.asax like so to do this:

void Application_BeginRequest(object sender, EventArgs e) {

string fullOrigionalpath = Request.Url.ToString();

if (fullOrigionalpath.Contains("/Products/Books.aspx")) {
Context.RewritePath("/Products.aspx?Category=Books");
}
else if (fullOrigionalpath.Contains("/Products/DVDs.aspx")) {
Context.RewritePath("/Products.aspx?Category=DVDs");
}
}
The downside of manually writing code like above is that it can be tedious and error prone. Rather than do it yourself, I'd recommend using one of the already built HttpModules available on the web for free to perform this work for you.

Source of this blog @ http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Thursday, June 24, 2010

How to respond with code 404 (Not Found) in ASP.NET

Best Books available @ http://astore.amazon.com/dotnetclr-20

How to respond with code 404 (Not Found) in ASP.NET
Suppose you configured custom 404 page in web.config file in the customErrors section. So whenever user requests non-existent aspx page, ASP.NET run-time returns well formatted message to the user.

Also you have a page that shows articles from a database according to article ID passed in the url (for example: article.aspx?id=345). But if user passes article ID that doesn't exists the page must return code 404 (Not Found) and show the custom 404 page like in the previous situation.

Fortunately you don't need to parse the customErrors section to get name of the custom 404 page. Just throw HttpException:

throw new HttpException(404, "Article not found");

ASP.NET run-time will catch the exception and will redirect to the custom 404.


Wednesday, June 23, 2010

How to Speed up Visual Studio 2005 launch

You can Optimize the launch of the Visual Studio 2005 to serve the studio faster.

Disable "Start Page"

Go to Tools | Options.
In Environment | Startup section, change At startup setting to Show empty environment.

Disable splash screen.

Open the properties of Visual Studio 2005 shortcut.
Add the parameter /nosplash to the target.
Close all unnecessary panels/tabs to prevent them from appearing when the IDE loads.


Tuesday, June 22, 2010

How to Show Obsolete Code Warning to users in .Net

If you've been using the .NET Framework for a number of years chances are you've seen the Framework versions advance and seen instances where some of the .NET Framework classes such as prior Configuration classes have gone obsolete and you've received warnings from the compiler about it to make you aware. You may have wondered how to do that same thing with your own code. There is an Obsolete attribute that you can use to decorate your own classes and methods to indicate they are being phased out as well. If you're working independently of others, then chances are you won't need it. However, in working with a project team where you may have implemented a framework, helper classes or other conventions, it can be very helpful to use the Obsolete attribute to flag dead code that won't be used going forward. This allows them to be migrated over time rather than just deleting from your code. This is very handy as you refactor code to communicate through the compiler that a particular item is obsolete. By default the items are served up as warnings, but an optional flag can indicate if they should be treated as warnings. It is worthwhile to have that setting be a configuration value so that you can enable or disable it across the board.

// Include message for compiler to present
[Obsolete("This class is dead. It has been replaced by MyClass3.")]
class MyClass1
{
// ...
}

// Include message and generate a compiler error
[Obsolete("This class is dead. It has been replaced by MyClass4. "), true]
class MyClass2
{
// ...
}

Friday, August 14, 2009

What is AppDomain and Storing and Retriving data from App Domain




We all know that with the launch of .Net framework there has been lot many new things. One of the new features is “AppDomain”. What are appdomins (application domains)? Before that let us first understand what processes are. Processes are physically isolated memory and resources are needed to maintain themselves. Also every process has at least one thread. With .Net Microsoft has introduced another extra layer of abstraction or isolation with in the processes called as AppDomain. The AppDomain is not a physical isolation but rather a logical isolation with in the process. This means that we can have a single process hosting multiple appdomains.

Why You Should Use AppDomains?

AppDomain can be use to load and Assembly dynamically, and the entire AppDomain can be destroyed, without affecting the Process. I think this illustrates the abtraction/isolation that an AppDomain gives us.

How to store and retrieve data from app domain. Here is the code

class Program
{
static void Main(string[] args)
{
AppDomain objDomain = System.AppDomain.CurrentDomain;
string Name = "MyApp";
string Value = "My Application Domain";
objDomain.SetData(Name, Value);
Console.WriteLine(objDomain.GetData(Name));
Console.ReadLine();
}
}

Tuesday, August 4, 2009

CAPTCHA in ASP.Net C# , Challange Password in C#



Have you ever wondered why people put images in the website and ask you to type it. In a simple term CAPTCHA. What is it ??
CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart"

As the word explains, you generate a code in a Image form which no other comuter or computer program can read. A human has to typed in a text box to make sure that the image content and user input is correct. we have options either to display only numbers, Alphanumeric or image of objects like Car, bus etc. Here i am going to explain about CAPTCHA with ASP.Net

Let us build the Class which will build the Image for us.. below is the code for that

First is the Image Generation Class

CaptchaImage.cs Class


public class CaptchaImage
{
// Public properties (all read-only).
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}

// Internal properties.
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;

// For generating random numbers.
private Random random = new Random();

// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
public CaptchaImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}

// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width, height and font family.
// ====================================================================
public CaptchaImage(string s, int width, int height, string familyName)
{
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(familyName);
this.GenerateImage();
}

// ====================================================================
// This member overrides Object.Finalize.
// ====================================================================
~CaptchaImage()
{
Dispose(false);
}

// ====================================================================
// Releases all resources used by this object.
// ====================================================================
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}

// ====================================================================
// Custom Dispose method to clean up unmanaged resources.
// ====================================================================
protected virtual void Dispose(bool disposing)
{
if (disposing)
// Dispose of the bitmap.
this.image.Dispose();
}

// ====================================================================
// Sets the image width and height.
// ====================================================================
private void SetDimensions(int width, int height)
{
// Check the width and height.
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}

// ====================================================================
// Sets the font used for the image text.
// ====================================================================
private void SetFamilyName(string familyName)
{
// If the named font is not installed, default to a system font.
try
{
Font font = new Font(this.familyName,80F,FontStyle.Bold);
this.familyName = familyName;
font.Dispose();
}
catch (Exception ex)
{
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}

// ====================================================================
// Creates the bitmap image.
// ====================================================================
private void GenerateImage()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);

// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.White, Color.WhiteSmoke);
g.FillRectangle(hatchBrush, rect);

// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > rect.Width);

// Set up the text format.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
float v = 4F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.DarkBlue, Color.Black);
g.FillPath(hatchBrush, path);

// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}

// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();

// Set the image.
this.image = bitmap;
}
}



Now the code where you want to call the CAPTCHA
Generate a Random code and put it in session, Please see that this session variable is used in the JpegImage.aspx.cs class

Session["CaptchaImageText"] = GenerateRandomCode();
Code to Generate Random Code
private string GenerateRandomCode()
{
string s = "";
for (int i = 0; i < s =" String.Concat(s,">
To Validate the user input write a function like this

private bool ValidateCaptcha()
{
if (txtCaptcha.Text.Trim() == Session["CaptchaImageText"].ToString())
return true;
else
{
lblError.Visible = true;
lblError.Text = "Please enter correct code. Click on Refresh to get a new code";
return false;
}
}


Thats it. You should be able to put this image to validate the user.

LDAP Password Change in C# over internet




One of the recent challanges we had is to change the LDAP password over internet. The scenario
Application hosted to change password : ASP.Net 2.0 hosted in IIS 6.0
Domain : Exposed Internet (not with in Domain)
LDAP server : with in Intranet domain
Requirement is to change the password when some one logs from internet and change the password.
I have used the below code to make it possible
This method will return true if the password change is success

private bool ChangePassword(string strUserName, string strOldPassword, string strNewPassword)
{
const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
const long ADS_OPTION_PASSWORD_METHOD = 7;
const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
const int ADS_PASSWORD_ENCODE_CLEAR = 1;
string strPort = "389";
int intPort;
intPort = Int32.Parse(strPort);

try
{
string strUserString = "partnermind" + @"\" + strUserName.Trim();
//Replace XXX.XXX.XXX.XXX with your LDAP server IP
DirectoryEntry entry = new DirectoryEntry("LDAP://XXX.XXX.XXX.XXX", strUserString, strOldPassword, AuthenticationTypes.Secure AuthenticationTypes.Sealing AuthenticationTypes.ServerBind);
DirectorySearcher search = new DirectorySearcher(entry);
string strFilter = "(SAMAccountName=" + strUserName + ")";
search.Filter = strFilter;
SearchResult result = search.FindOne();
DirectoryEntry user = result.GetDirectoryEntry();
//Setting up the beloow 2 properties is very important. Other wise it will now rork
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
user.Invoke("ChangePassword", new object[] {strOldPassword, strNewPassword });
user.CommitChanges();
}
catch (Exception exception)
{
lblError.Visible = true;
lblError.Text = "There is an error while changing password.";
ManageError.WriteError("Change password failed for"+strUserName+"/nUser:"+exception.Message);
return false;
}
return true;
}



Hope this helps every one.. Happy Coding:)