Showing posts with label ASP.NET(C#). Show all posts
Showing posts with label ASP.NET(C#). Show all posts

Tuesday, May 7, 2013

Generate Select All Checkbox control in C# , ASP.Net

Hi guys, today I faced a scenario where I need to create (auto generate) a Select All CheckBox control by C# code behind at runtime and and insert it to the Ajax Control toolkit TabPanel.

Once user will check the Select All checkbox all the other checkbox within that Tab will get checked without post back of page. For opposing post back and achieving mark as check JavaScript is the best option coming in mind. And hence I choose the same.

I wrote JavaScript Global function which accept Select All CheckBox Control Id and look for the related controls and auto generate the required Id for them.

Generate Select All Checkbox : 2bexpert

For achieving this functionality I have written Below mention code:

C# Code for Generating CheckBox Dynamically (Auto Generate Checkbox):

#region Generate SelectAllCbx

    private void GenerateSelectAllCbx(string cbxId, int index, int width, bool isChecked, AjaxControlToolkit.TabPanel tab)

    {

        CheckBox cbAll = new CheckBox();

        cbAll.Attributes.Add("Value", "All");

        cbAll.ID = cbxId + index.ToString();

        cbAll.Text = "Select All";

        cbAll.Width = Unit.Pixel(width);

        cbAll.Checked = isChecked;

        cbAll.Enabled = !isChecked;

        cbAll.Attributes.Add("onclick", "javascript: SelectAll(this," + index.ToString() + ");");

        tab.Controls.Add(cbAll);

 

    }

    #endregion

Just we need to call this method where we want to insert Select All CheckBox:

GenerateSelectAllCbx("cbEngRating_", 4, 750, false, tabICFRating);

 

Whenever this Method would get called it will Insert a Checkbox (Select All) and handle other automatically for achieving that below is JavaScript Code:

function SelectAll(control_id, x) {

        var chkAll = $(control_id);

        var autoId = control_id.id.substring(0, control_id.id.length - x.toString().length)

        for (var i = 0; i < x; i++) {

            $("#" + autoId + i).attr("Checked", chkAll.prop("checked"));

        }

            }

Here I am passing the Control Id and the Postfix Id to generate auto ID.

That’s it now you are able to select auto generated multiple checkbox and mark them check.




Cheers…

Anand Tiwari….

Thursday, April 25, 2013

Scroll Content of div tag like page scrolling.

Hi guys today I have faced a requirement where I need to Scroll the content of one div to show all the content in it. Actually we had a Modal Popup which was displaying some sort of information based on link click by the user.

When ever we are going to show another html (web page) in modal popup we are facing this type of challenge as there in modal popup if you are scrolling by mouse the Parent page will get started scrolling. And hence here our JavaScript is helping as to achieve this functionality. 

Lets say you have a div with lots of content (text and images or video) and your modal popup size is small to show them at once so in this case you need to do like below .

Here I have used a html table control for Demo purpose you can as you like just we need is the id of the div control which we are going to scroll. Like here ‘’dvcontainer” .

<table width="175px">
<
tr>
<
td>
<
div style="position: relative; width: 175px; height: 160px;


border: 1px solid black;
overflow: hidden">
<
div id="dvcontainer" style="position: absolute;


width: 170px; left: 0; top: 0">
<!--INSERT CONTENT HERE-->
<p>
Anand Mani Tiwari holds an Engineering degree in


Computer Science from BPUT and
has previously worked at NCPL Inc. and now working


at Orion Systems Integrators
Inc for a Client which is worlds Biggest Auditing


Company KPMG. He is a Software
Engineer and working on different Microsoft


Technologies like ASP.Net, WPF, Silverlight,
WCF... He is a Microsoft Certified Professional.


And recently Passed Microsoft Technology
Specialist Exam in HTML 5 with a Excellent


Score of 920/ 1000.
</p>
<
p>
- <a href="http://www.2bexpert.com/p/about-me.html">


Click here to see his complete profile</a>
</
p>
<!--END CONTENT-->
</div>
</
div>
</
td>
<
td>
<
a href="#" onmouseover="move('dvcontainer',1)"


onmouseout="clearTimeout(move.to)">
<
img alt="Page Up" src="images/up.gif" border="0"></a>
<
div style="height: 145px; display: block;


background: url(images/);">
</
div>
<
a href="#" onmouseover="move('dvcontainer',-1)"


onmouseout="clearTimeout(move.to)">
<
img alt="Page Down" src="images/down.gif" border="0"></a>
</
td>
</
tr>
</
table>


 




After this we need to write the code for Scroll the “dvcontainer” content. So here we go with JavaScript ….



<script type="text/javascript" language="javascript">

function
move(id, spd) {
var obj = document.getElementById(id), max = -obj.offsetHeight +


 obj.parentNode.offsetHeight, top = parseInt(obj.style.top);
if ((spd > 0 && top <= 0) || (spd < 0 && top >= max)) {
obj.style.top = top + spd + "px";
move.to = setTimeout(function () { move(id, spd); }, 20);
}
else {
obj.style.top = (spd > 0 ? 0 : max) + "px";
}
}

</script>



That’s it now you can see the div content is getting scroll on mouse hover of Up and Down image.



Required Images for this demo : up       down



I hope this post has helped you, please comment. Thanks

Generate Thumbnail Image in ASP.Net by C# Class

Hi Guys today I am going to show you how you can generate Thumbnail’s of any selected image dynamically by a C# class. This class is very handy in admin area development, where admin has to upload the images.

By this class you can generate not only Thumbnail but the real resource will also get saved in Servers folder which is handy to show the related big image as well.

We can use this Thumbnail Generator class by just calling the function GenerateThumbNail() and passing the required signatures (Parameters), we need to initiate the class first by Creating the instance first for that below is the code block:

  public Helper hlp { get; set; }

Let say we are having a ASP FileUpload control and ASP Button control to select desired file and send the same to server for making thumbnail of selected image.

Below is the *.aspx code:

<fieldset>
    <legend>Thumbnail Generator</legend>
    <asp:FileUpload ID="flUpload" runat="server" /><asp:Button ID="btnUpload"
            runat="server" Text="Upload" onclick="btnUpload_Click" />
    </fieldset>

it will generate a html page like below:

image

Now our Fileupload control having the Sorce file after selecting Image file from local Server (User Computer).

On Upload Button Click by user below mentioned code required:

protected void btnUpload_Click(object sender, EventArgs e)
   {
       hlp = new Helper();
       hlp.GenerateThumbNail(flUpload.PostedFile, "thumbFile",300);
   }

Below is the required Class for Generating Thumbnail:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;

/// <summary>
/// Summary description for Helper
/// </summary>
public class Helper
{
    public Helper()
    {
        //
        // TODO: Add constructor logic here
        //
    }


    public void GenerateThumbNail(HttpPostedFile srcFile,string thumbNailFolder,int width)
    {
        HttpPostedFile myFile = srcFile;
        string filename = srcFile.FileName;
        int oFileLength = myFile.ContentLength;
        if (oFileLength != 0)
        {
            int i = filename.LastIndexOf("\\");
            filename = filename.Substring(i + 1);
            filename = DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + filename;
            string thumb_filename = "thumb_"+DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + filename;
            byte[] myData = new Byte[oFileLength];
            myFile.InputStream.Read(myData, 0, oFileLength);

            System.IO.FileStream newFile
                = new System.IO.FileStream(HttpContext.Current.Server.MapPath("~/images/") + filename,
                                           System.IO.FileMode.Create);
            newFile.Write(myData, 0, myData.Length);
            newFile.Close();

 

            System.Drawing.Image image =
               System.Drawing.Image.FromFile(newFile.Name);
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            int thumbWidth = width;
            int thumbHeight;
            Bitmap bmp;
            if (srcHeight > srcWidth)
            {
                thumbHeight = (srcHeight / srcWidth) * thumbWidth;
                bmp = new Bitmap(thumbWidth, thumbHeight);
            }
            else
            {
                thumbHeight = thumbWidth;
                thumbWidth = (srcWidth / srcHeight) * thumbHeight;
                bmp = new Bitmap(thumbWidth, thumbHeight);
            }

            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            System.Drawing.Rectangle rectDestination =
                   new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
            gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
            bmp.Save(HttpContext.Current.Server.MapPath("~/"+thumbNailFolder + "/" + thumb_filename));
            bmp.Dispose();
            image.Dispose();
       
        }
    }
}

And that’s it, now be sure to make two folders in you solution (Project). One for original Picture Upload and another one for Thumbnail file.

I am pasting Overall screen shot of Project which will help you :

image

 

Cheers…..

 

Regards,

Anand Tiwari

Monday, December 6, 2010

How to Add CSS dynamically to controls in C#, ASP.NET

To add style Dynamically just add this code snippet.
Control_ID.Style.Add("color","#FFFF99");
As in the above example I had just given a example to change the font color dynamically. You can use another method to add the style to the control dynamically... Like
Control_ID.Attribute.Add("Style='color:#FFFF99;'");

How to Encrypt and Decrypt the Query string automatically by C#, Asp.Net

Just Create a Businesslogic class in App_code folder with the name QueryStringModule.cs
and then add the below given code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// 
/// Summary description for QueryStringModule
/// 
public class QueryStringModule : IHttpModule
{
    ///   
    /// Summary description for QueryStringModule  
    ///   
    
        //  private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));  
        #region IHttpModule Members

        public void Dispose()
        {
            // Nothing to dispose  
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion

        private const string PARAMETER_NAME = "enc=";
        private const string ENCRYPTION_KEY = "key";

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            string query = string.Empty;
            string path = string.Empty;

            try
            {
                if (context.Request.Url.OriginalString.Contains("aspx") && context.Request.RawUrl.Contains("?"))
                {
                    query = ExtractQuery(context.Request.RawUrl);
                    path = GetVirtualPath();

                    if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        // Decrypts the query string and rewrites the path.  
                        string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
                        string decryptedQuery = Decrypt(rawQuery);
                        context.RewritePath(path, string.Empty, decryptedQuery);
                    }
                    else if (context.Request.HttpMethod == "GET")
                    {
                        // Encrypt the query string and redirects to the encrypted URL.  
                        // Remove if you don't want all query strings to be encrypted automatically.  
                        string encryptedQuery = Encrypt(query);
                        context.Response.Redirect(path + encryptedQuery, false);
                    }
                }
            }
            catch (Exception ex)
            {
                // m_Logger.Error("An error occurred while parsing the query string in the URL: " + path, ex);  
                context.Response.Redirect("~/Home.aspx");
            }

        }

        ///   
        /// Parses the current URL and extracts the virtual path without query string.  
        ///   
        /// The virtual path of the current URL.  
        private static string GetVirtualPath()
        {
            string path = HttpContext.Current.Request.RawUrl;
            path = path.Substring(0, path.IndexOf("?"));
            path = path.Substring(path.LastIndexOf("/") + 1);
            return path;
        }

        ///   
        /// Parses a URL and returns the query string.  
        ///   
        /// The URL to parse./// The query string without the question mark.  
        private static string ExtractQuery(string url)
        {
            int index = url.IndexOf("?") + 1;
            return url.Substring(index);
        }

        #region Encryption/decryption

        ///   
        /// The salt value used to strengthen the encryption.  
        ///   
        private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());

        ///   
        /// Encrypts any string using the Rijndael algorithm.  
        ///   
        /// The string to encrypt./// A Base64 encrypted string.  
        private static string Encrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] plainText = Encoding.Unicode.GetBytes(inputText);
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainText, 0, plainText.Length);
                        cryptoStream.FlushFinalBlock();
                        return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
        }

        ///   
        /// Decrypts a previously encrypted string.  
        ///   
        /// The encrypted string to decrypt./// A decrypted string.  
        private static string Decrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            byte[] encryptedData = Convert.FromBase64String(inputText);
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }

        #endregion

    }


After then in web.config file add this code...

 


Thats it, now get the Querystring on any page in encripted manner,
For example:
LblQuery.Text=Request.QueryString["id"].ToString();

Friday, December 3, 2010

How to make corp and thumbnail of any size of image in C#, ASP.NET

With out loosing clarity of the image you can get it by given two method, In my case I had to upload the image in the server and show them in the gallery...

protected void btnUpload_Click(object sender, EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;

// Set constant values

sSavePath = "uploadedImages/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;

// If file field is not empty

if (fileUploader.PostedFile != null)
{
// Check file size (must not be 0)

HttpPostedFile myFile = fileUploader.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Visible = true;
lblOutput.Text = "No file was uploaded.";
return;
}

// Check file extension (must be JPG)

if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Visible = true;
lblOutput.Text = "The file must have an extension of JPG";
return;
}

// Read file into a data stream

byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);

// Make sure a duplicate file does not exist.  If it does, keep on appending an 

// incremental numeric until it is unique

string sFilename = System.IO.Path.GetFileName(myFile.FileName);

int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}

// Save the stream to disk

System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();

// Check whether the file is really a JPEG by opening it

System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

// If jpg file is a jpeg, create a thumbnail filename that is unique.

file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}

// Save thumbnail and output it onto the webpage

System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
filename = sThumbFile;
imgUser.ImageUrl = sSavePath + sThumbFile;
fileURL = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Visible = true;
lblOutput.Text = "File uploaded successfully!";

// Destroy objects

myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Visible = true;
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}

}

Next...

public bool ThumbnailCallback()
{
return false;
}

Thats all...

Friday, November 26, 2010

How to Read and Get Data From XML Document in C#

By this Method we can easily get Data from XML Database. For this first of all create a "ContactsList.xml" XML file and under root section add your recoreds.

public void GetData()
{
try
{
string path = "ContactsList.xml";
FileStream fs = new FileStream path,FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
DataSet ds = new DataSet();
ds.ReadXml(fs);
if (ds.Tables.Count != 0)
{
DataTable dt = ds.Tables[0];

int a = dt.Rows.Count;

for (int i = 0; i < a; i++)
{
string[] str1 = new string[4];
str1[0] = dt.Rows[i].ItemArray[0].ToString();


str1[1] = dt.Rows[i].ItemArray[1].ToString();
str1[2] = dt.Rows[i].ItemArray[2].ToString();
int count = Convert.ToInt32(dt.Rows[i].ItemArray[7].ToString());
if (count.Equals(1) || count.Equals(0))
{
str1[3] = dt.Rows[i].ItemArray[3].ToString();
ListViewItem item1 = new ListViewItem(str1);
ldtvw_Contact.Items.Add(item1);
}
else
{
string interests = dt.Rows[i].ItemArray[3].ToString() + "," + dt.Rows[i].ItemArray[4].ToString() + "," + dt.Rows[i].ItemArray[5].ToString() + "," + dt.Rows[i].ItemArray[6].ToString();
str1[3] = interests;
ListViewItem item1 = new ListViewItem(str1);
ldtvw_Contact.Items.Add(item1);
}

}

fs.Close();
}

Thats All....

Thursday, November 25, 2010

How to Generate Random String in C#, ASP.NET

To Generate a Random String is very Tricky and useful stuff to Know as we can use this functionality at the time of Generating Random Password automatically for each User Registering on the website.

I am sure this will help you a lot, here I am writing the Method to Generate the Random String.

private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }
Now the above code will generate the Random String. If you want to have a Strong Password then password must contains Number. So lets go to generate Random Numbers:
public string GetRandomNumber()
    {
        StringBuilder strbuild = new StringBuilder();
        strbuild.Append(RandomNumber(1000, 9999));
        return strbuild.ToString();
    }

private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

Now you are ready to generate a random password. for that you have to call these methods as given below:
public string GetPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }

That's All, Please give your comments if the post is helpful.

Sunday, November 21, 2010

Freeze GridView Header While Scrolling

This is very common problem in Web development that we need to freeze the GridView header at the time of scrolling, Here is one simple tips:

Step 1 : Create a CSS class as following
<br />.HeaderFreez <br />{ <br />position:relative ; <br />top:expression(this.offsetParent.scrollTop); <br />z-index: 10; <br />} <br />

Step 2 Set Gridview’s HeaderStyle CssClass as follows
CssClass="HeaderFreez"
That’s all guys ...

Connection Pooling

Creating and establishing a connection with a database server is a high resource consuming process and hence by result more time taking.
If any application needs to fire any query against any database server, we need to first establish a connection with the server and then execute the query against that database server.
So why we will again and again open and close the connection of Database, for that only connection pooling came in feature.
When the first time ADO.Net is stabilizing connection with the database and connection open with the respective credentials the ADO. Net  is  saving the references for the that connection and while closing the connection ADO.Net is not closing total connection and when another request done for the Database action ADO.Net using that references for the Database process so no Hassel for opening and closing connection again and again, and process is more faster .
Sample Connection String with Connection Pooling…..

initial catalog=Northwind; Data Source=localhost; Connection Timeout=30;
User Id=USER; Password=PASS; Min Pool Size=20; Max Pool Size=200;
 Incr Pool Size=10; Decr Pool Size=5;

What Is A Web Service?

A Web Service is a program that can be invoked in a distributed web envi ronment. Web Service technologies like SOAP, WSDL, and UDDI are standards to describe, publish, discover, and use Web Services; they define a development model  for integrating applications over the web.

Steps to Create a Web Service

1.  Create (or use an existing) virtual directory for any folder on your computer.
2.  Create an empty file called “test.asmx” in the folder.
3.  Edit the file and add the  following text:
<%@ WebService Language="C#" Class="MyMath" %>
using System.Web.Services;
public class MyMath
{
    [WebMethod]
    public int Add(int num1, int num2)
    {
         return num1+num2;
    }
}

Tuesday, October 19, 2010

Model View Controller (MVC)

MVC is not referred to as a design pattern but a “set of classes to build a user interface” that uses design patterns such as Observer, Strategy, and Composite. It also uses Factory Method and Decorator, but the main MVC relationship is defined by the Observer and Strategy patterns.
There are three types of objects. The Model is our application data, the View is a screen, and the Controller defines the way the View reacts to user input. The views and models use the Publish-Subscribe protocol - when Model data is changed, it will update the View. It allows us to attach multiple Views to the same Model [2]. This is achieved by using the Observer design pattern.









The goal of this pattern is to define the one-to-many relationship between the Subject and the Observers; if the Subject is changed all Observers are updated. The Subject maintains the list of the Observers and can attach and detach objects to the list. The Observer in return exposes an Update method on its interface that Subject can use to update all objects it observes. The C# implementation would look like this:


public abstract class Subject 
{ 
    private readonly ICollection<Observer> Observers = 
            new Collection<Observer>(); 

    public void Attach(Observer observer) 
    { 
        Observers.Add(observer); 
    } 
    public void Detach(Observer observer) 
    { 
        Observers.Remove(observer); 
    } 
    public void Notify() 
    { 
        foreach (Observer o in Observers) 
        { 
            o.Update(); 
        } 
    } 
} 

public class ConcreteSubject : Subject 
{ 
    public object SubjectState { get; set; } 
} 

public abstract class Observer 
{ 
    public abstract void Update(); 
} 

public class ConcreteObserver : Observer 
{ 
    private object ObserverState; 
    private ConcreteSubject Subject { get; set; } 

    public ConcreteObserver(ConcreteSubject subject) 
    { 
        Subject = subject; 
    } 
    public override void Update() 
    { 
        ObserverState = Subject.SubjectState; 
    } 
}
 
The other component of the MVC pattern is the View-Controller relationship.
The View uses the Controller to implement a specific type of response.
The controller can be changed to let the View respond differently to user input.
This View-Controller link is an example of the Strategy design pattern.
 

Each ConcreteStrategy encapsulates a particular type of response.
A Context object has a reference to a Strategy object and can
forward the requests to a specific Strategy though the common interface.
Here is a C# code:
 
public abstract class Strategy 
{ 
    public abstract void AlgorithmInterface(); 
} 
public class ConcreteStrategyA : Strategy 
{ 
    public override void AlgorithmInterface() 
    { 
        // code here 
    } 
} 
public class Context 
{ 
    private readonly Strategy Strategy; 

    public Context(Strategy strategy) 
    { 
        Strategy = strategy; 
    } 
    public void ContextInterface() 
    { 
        Strategy.AlgorithmInterface(); 
    } 
}
Now we know that the Model acts as a Subject from the Observer pattern and the View takes on the role of the Observer object. In the other relationship of the MVC, the View  is a Context and the Controller is a Strategy object. Combining our  knowledge of the two diagrams, we can draw the MVC UML class diagram as  below: 
 


 
 
 
Here is the implementation code for the MVC pattern:
public abstract class Model 
{ 
    private readonly ICollection<View> Views = new Collection<View>(); 
    public void Attach(View view) 
    { 
        Views.Add(view); 
    } 
    public void Detach(View view) 
    { 
        Views.Remove(view); 
    } 
    public void Notify() 
    { 
        foreach (View o in Views) 
        { 
            o.Update(); 
        } 
    } 
} 

public class ConcreteModel : Model 
{ 
    public object ModelState { get; set; } 
} 

public abstract class View 
{ 
    public abstract void Update(); 
    private readonly Controller Controller; 
    protected View() 
    { 
    } 
    protected View(Controller controller) 
    { 
        Controller = controller; 
    } 
    public void ContextInterface() 
    { 
        Controller.AlgorithmInterface(); 
    } 
} 

public class ConcreteView : View 
{ 
    private object ViewState; 
    private ConcreteModel Model { get; set; } 
    public ConcreteView(ConcreteModel model) 
    { 
        Model = model; 
    } 
    public override void Update() 
    { 
        ViewState = Model.ModelState; 
    } 
} 

public abstract class Controller 
{ 
    public abstract void AlgorithmInterface(); 
} 

public class ConcreteController : Controller 
{ 
    public override void AlgorithmInterface() 
    { 
        // code here 
    } 
}
If we leave out the concrete classes for simplicity,
we will get a more familiar MVC diagram.
Please note that we use pseudo- rather than proper UML shapes,
where circles represent a group of classes (e.g., Model and ConcreteModel),
not classes as on the UML class diagram on Figure 3.