Knockout JS [Hello World]

Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore: a clear separation between domain data, view components and data to be displayed.
What is Model?
Model is your business entity like User,Customer objects which contains property.
What is ViewModel:
Viewmodel looks like Model but it contains behavior
Let's create a simple hello world example using knockout.js.Create a html file named index.html and add following code
In the above code,first I have added refrence of knockout.js and then created two html controls input and span.Notice the markup on line 8 and 9 We are using a new attribute: data-bind.
data-bind is knockout syntax for binding viewmodel property to view.
On line 10 to 14 I have created a simple viewmodel which have one singal property message with default value "Hello World".
On line 15 I am attaching viewmodel to view 

Using the DropDownList Helper with ASP.NET MVC


This post will teach you the basics of working with the DropDownList helper helper in an ASP.NET MVC Web application.
The DropDownList helper used to create an HTML select list requires a IEnumerable , either explicitly or implicitly. That is, you can pass the IEnumerable explicitly to the DropDownList helper or you can add the IEnumerable to the ViewBag using the same name for the SelectListItem as the model property.
Let's suppose you want to show list of Animals as dropdownlist

public static List<String> GetPets()
        {
            List<string> petList = new List<string>();
            petList.Add("Dog");
            petList.Add("Cat");
            petList.Add("Hamster");
            petList.Add("Parrot");
            petList.Add("Gold fish");
            petList.Add("Mountain lion");
            petList.Add("Elephant");

            return petList;
        }

Open your controller method and add items to ViewBag item by passing the item to SelectList.

public ActionResult Index()
        {

            ViewData["Pets"] = new SelectList(GetPets());
            return View();
        }

In your view add following razor helper method.Run the application you will see that dropdownlist is generaeted

@Html.DropDownList("pets")

The above was very simple form.Let's create a complex form with some other information.In this example I am going to create a simple user registration form.Create two class named Country and Registration in model folder and add following code


public class Registration
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

    }
    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

After that create a RegistrationViewModel class in Model folder and paste the following code

public class RegistrationViewModel
    {
        private readonly List<Country> _countries;
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

        public int SelectedCountryID { get; set; }
        public RegistrationViewModel()
        {
            List<Country> countries = new List<Country>(){
                new Country{Id=1,Name="India"},
                new Country{Id=2,Name="USA"},
                new Country{Id=3,Name="UK"},
                new Country{Id=4,Name="Australia"},
                new Country{Id=5,Name="Nepal"},
            };
            _countries = countries;
        }
        public IEnumerable<SelectListItem> Contry
        {
            get { return new SelectList(_countries, "Id", "Name"); }
        }
    }
The tricky part here is that I have added a readonly property Country that returns list of countries which I will pass to DropDownListFor helper function.Create two action methods in your controller as below.Right click on Create action method and generate strongly type view.Open the genrated view and modify the Country section as below

      <div class="editor-field">
            @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
            @Html.ValidationMessageFor(model => model.County)

        </div>


public ActionResult Create()
        {
            RegistrationViewModel model = new RegistrationViewModel();
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(RegistrationViewModel _model)
        {
            RegistrationViewModel model = _model;
            return View(model);
        }


@model eManagerDemo.Models.RegistrationViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>RegistrationViewModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.County)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
            @Html.ValidationMessageFor(model => model.County)

        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

If you run the application by pressing F5 you will see following output as shown in below image.


How to create html helper in razor (.NET MVC)


Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages.The Razor syntax is a template markup syntax, based on the C# programming language, that enables the programmer to use an HTML construction workflow[clarification needed]. Instead of using the ASP.NET .ASPX markup syntax with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block.

HTML Helper
Html helper are much like asp.net control that return html string.But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In this post I will show you how to create Html helper in MVC.NET.There are two ways to create html helper in MVC.
Inline Helpers
These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.For example in following code snippet I have created a ToUpper html helper that wrap the text inside b tag and converts  the text to upper case 

@helper ToUpper(string text) { 
        
        @text.ToUpper()
    
    }
@{
    ViewBag.Title = "Demo";
    Layout = null;
}


@ToUpper(@ViewBag.Message)

Custom Helper
If you want to use your Html helper in application level then you can create custom helper.
You can create custom helper function by creating extensions method.In following code snippet I have created a SubmitButton html helper that generate submit button.



public static class HtmlHelpers
    {
        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string text)
        {
            string str = "<input type=\"submit\" value=\"" + text + "\" />";
            return new MvcHtmlString(str);
        }
    }

How to use custom Helper

@Html.ToUpper("Submit")

How to check stream has Image or not

Let's suppose you have a page on which user upload there image and you want to validate that user is uploading image file only not other file format.The one easy solution is use regex and validate the extension of the file but if user rename the extension of the file and upload some executable code.Following is the simple c# code snippet that check the file type by the header value.

private bool IsImage()
    {
        bool isImage = false;
        FileStream stream = new FileStream(Server.MapPath(@"Images\a.txt"), FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        // Read the first 25 characters, we will be checking for a GIF or JPG signature.
        char[] strBuffer = new char[25];
        reader.ReadBlock(strBuffer, 0, 25);
        string stringBuffer = new string(strBuffer);
        // Is this an image?
        if (stringBuffer.IndexOf("GIF8") &gt; -1 || stringBuffer.IndexOf("JFIF") &gt; -1)
        {
            isImage = true;
            Response.Write("It's an image");

        }
        else
        {
            Response.Write("It's HTML or other junk.");
        }
        return isImage;
    }

How To Change your ASP.Net controls at runtime

Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping
it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for SafeTextBox
///
public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = System.Web.HttpUtility.HtmlEncode(value);
        }
    }
}

Then I needed to hook the tag mapping up in the web.config to convert all the text boxes into SafeTextBox instances. It simply converts all TextBox instances on the entire site. Here is what’s needed in the web.config:

<pages> <tagMapping> <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="SafeTextBox"/> </tagMapping> </pages>
After we add the following line of code in the web.config file all the TextBox control will be mapped to the TextBox.

How to change some text before it is sent to the client.

In this post,I will show you how to modify the response before it is sent to the client.The trick here is to override the Render method of the Page class and modify the response.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs"
Inherits="InterceptHtml" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           Hello World!
           <br />
           Hi
       </div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class InterceptHtml : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

       Response.Filter = new ReplaceHTML(Response.Filter);


   }
   /// <summary>
   /// Second Method!!!!!!! overide the Render Method.
   /// </summary>
   /// <param name="writer"></param>
   protected override void Render(HtmlTextWriter writer)
   {


       StringWriter output = new StringWriter();
       base.Render(new HtmlTextWriter(output));
       writer.Write(output.ToString().Replace("Hi", "This is the replaced text!
Welcome to <a href=\"http://www.aspdotnetcodebook.blogspot.com\
">www.aspdotnetcodebook.blogspot.com</a>"));
   }
}
II nd Method
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// To intercept and get a reference to the HTML, we now need to create a
/// class to inherit System.IO.Stream. So, create a new class in
/// </summary>
public class ReplaceHTML : System.IO.Stream
{

    private System.IO.Stream Base;

    public ReplaceHTML(System.IO.Stream ResponseStream)
    {
        if (ResponseStream == null)
            throw new ArgumentNullException("ResponseStream");
        this.Base = ResponseStream;
    }






    public override int Read(byte[] buffer, int offset, int count)
    {
        return this.Base.Read(buffer, offset, count);
    }


    public override void SetLength(long value)
    {

    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        // Get HTML code 
        string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);

        // Replace the text with something else 
        HTML = HTML.Replace("Hello World!", "I've replaced the Hello World example!");

        // Send output 
        buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
        this.Base.Write(buffer, 0, buffer.Length);
    }

    public override bool CanRead
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanSeek
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanWrite
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override void Flush()
    {
        HttpContext.Current.Response.Flush();

    }

    public override long Length
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override long Position
    {
        get
        {
            throw new Exception("The method or operation is not implemented.");
        }
        set
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }

    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

How To - Prevent Script Attacks

This post describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.
Applies to ASP.NET 1.1 and ASP.NET 2.0.
Check out this article

How to return data from ajax call

In this post,I will show you how to return data from ajax request.As you know that you can not return data from ajax request but if you want to perform some action on return data of ajax.The better approach is to organize your code properly around callbacks. In the example,you can make GetUsers accept a callback and use it as success callback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReturnAjax.aspx.cs" Inherits="ReturnAjax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            function GetUsers(name, callback) {
                $.ajax({

                    type: "POST",
                    async: true,
                    url: "ReturnAjax.aspx/GetUsers",
                    data: "{name:'" + name + "'}",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        //Pass return data to callback function and do the operation
                        callback(data.d);
                    }
                });
            }
            $("#check").click(function () {
                GetUsers($("#txtName").val(), function (users) {
                    $('#result').empty();
                    $.each(users, function (index, user) {
                        $('#result').append('<p><strong>' + user.UserId + ' ' + user.Name + '</br>');

                    });
                });
            });
        });

      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <input type="button" name="check" value="check " id="check" /><br />
        <div id="result">
        </div>
    </div>
    </form>
</body>
</html>
AjaxReturn.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReturnAjax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static UserData[] GetUsers(string name)
    {
        return UserData.Users.Where(x => x.Name.StartsWith(name)).ToArray();
    }
}
public class UserData
{
    public string UserId { get; set; }
    public string Name { get; set; }

    public static List<UserData> Users
    {
        get
        {
            return new List<UserData>()
                      {
                          new UserData(){UserId = "1",Name = "Bill"},
                          new UserData(){UserId = "2",Name = "Booler"},
                          new UserData(){UserId = "3",Name = "Scott"},
                          new UserData(){UserId = "4",Name = "Anders"},
                      };
        }
    }
}

How To Convert HTML to Text, Easily


Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy.
It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code:

<%@ Page Language="C#" ValidateRequest="False" AutoEventWireup="true" CodeFile="StripTag.aspx.cs"
 Inherits="StripTag" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <asp:TextBox ID="TextBox1" runat="server" Height="172px" Width="363px" TextMode="MultiLine"></asp:TextBox></div>
     <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
 </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class StripTag : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {


   }
   public string StripTags(string HTML)
   {
       // Removes tags from passed HTML 
       return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", "");
   }


   protected void Button1_Click(object sender, EventArgs e)
   {
       Label1.Text = StripTags(TextBox1.Text);

   }
}

WinForms Designer Load Error

how to resolve the error
One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. for more details check out this link

How to change default binding in wcf 4.0

In this post I will share a very handy tips for wcf 4.0.As we all know that default binding is a new feature introduced in wcf 4.0.With WCF 4, this is no longer the case because the runtime automatically adds one or more "default endpoints" for you, thereby making the service usable without any configuration.
<protocolMapping>
      <add binding="wsHttpBinding" scheme="http"/>
    </protocolMapping>

How to create a simple http server in node.js


Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.


Start by creating a new file named “app.js”. Insert the following code into the file and save it.


var http = require("http");
var app = http.createServer(function(request, response) {  
    response.writeHead(200, {
        "Content-Type": "text/html"
    });  
    response.write("<!DOCTYPE "
        html ">");  
    response.write("<html>");  
    response.write("<head>");  
    response.write("<title>Hello Node Server Page</title>");  
    response.write("</head>");  
    response.write("<body>");  
    response.write("Hello World!");  
    response.write("</body>");  
    response.write("</html>");  
    response.end();
}); 
app.listen(9090);
console.log("Server is listening");

To start the server, type the command shown below. If everything works properly, you will see a message that the server is listening. Note that the example server attempts to bind to port 9090, the standard HTTP port. If this port is already in use, or is restricted on your machine, you will experience an error.

node app.js

How to stream large file using node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.




var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
    var newFile = fs.createWriteStream("x.wmv");
    var fileBytes = req.headers['content-length'];
    var uploadedBytes = 0;
    req.pipe(newFile);
    req.on('data', function(chunk) {
        uploadedBytes += chunk.length;
        var progress = (uploadedBytes / fileBytes) * 100;
        res.write("progress:" + parseInt(progress, 10) + "\n");
    });
    res.write("Done");

}).listen(8888);

Understand WebMessage Format


In this post I will show how how to use WebMessageBodyStyle parameter attribute in REST Service.WebMessageBodyStyle is an enumeration that specifies whether to wrap parameter and return values.WebMessageBodyStyle contains four member.

I have listed down all the members and there discription in following table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestLoginService
{

    [ServiceContract]
    public interface ILoginService
    {

        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare)]
        AuthResult Login(User user);
    }


}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestLoginService
{
    public class LoginService : ILoginService
    {

        public AuthResult Login(User user)
        {
            if (user.UserName == "john" && user.Password == "password")
            {
                return new AuthResult { UserName = user.UserName, IsAuthenticated = true };

            }
            return new AuthResult { UserName = user.UserName, IsAuthenticated = false };
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RestLoginService
{
   public class User
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace RestLoginService
{
    [DataContract]
    public class AuthResult
    {
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public bool IsAuthenticated { get; set; }
    }
}

Web.Config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http"/>
    </protocolMapping>
    <behaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Decorator Design Pattern

Intent:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality (also known as Wrapper)





using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DecoratorPattern
{

    public class UpperStream : Stream
    {
        private Stream _stream;
        public UpperStream(Stream stream)
        {
            this._stream = stream;

        }
        public override long Length
        {
            get { return _stream.Length; }
        }
        public override int Read(byte[] buffer, int offset, int count)
        {

            var numberOfBytesRead = _stream.Read(buffer, offset, count);
            for (int i = 0; i < numberOfBytesRead; i++)
            {
                buffer[i] = (byte)char.ToUpper((char)((int)buffer[i]));
            }


            return numberOfBytesRead;
        }
        public override bool CanRead
        {
            get { return true; }
        }
        public override bool CanSeek
        {
            get { throw new NotImplementedException(); }
        }
        public override bool CanWrite
        {
            get { throw new NotImplementedException(); }
        }
        public override void Flush()
        {
            throw new NotImplementedException();
        }
        public override long Position
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }
        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string message = "Hello Decorator";
            MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(message));
            UpperStream stream = new UpperStream(ms);
            StreamReader reader = new StreamReader(stream);
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}

Strategy Design Pattern

Strategy Design Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.


Problem:
Client wants to decide at run-time what serialization it should use to serialize a type. Many different serialization algorithms are already available.
Solution:
Encapsulate the different serialization algorithms using the Strategy pattern!
C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPattern
{

    public interface ISerializer
    {
        void Serialize();
    }
    public class XmlSerializer : ISerializer
    {
        public void Serialize()
        {
            Console.WriteLine("Xml serilizer Invoked");
        }
    }
    public class JsonSerializer : ISerializer
    {
        public void Serialize()
        {
            Console.WriteLine("Json serializer Invoked");
        }
    }
    public class Context
    {
        private ISerializer _serializer;
        public Context(ISerializer serializer)
        {
            this._serializer = serializer;
        }
        public void Serialize()
        {
            _serializer.Serialize();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Context ctx = new Context(new XmlSerializer());
            ctx.Serialize();
        }
    }
}

Adapter Design Pattern

Adapter Pattern: The Adapter pattern converts the interface of a class into another interface that clients expect.The client makes a request on the adapter by invoking a method from the target interface on it and then adapter translates that request into one or more calls on the adaptee using the adaptee interface. The client receives the results of the call and never knows there is an adapter doing the translation


Pre-Condition: You are maintaining an existing system that makes use of a third-party class library from vendor A
Stimulus: Vendor A goes belly up and corporate policy does not allow you to make use of an unsupported class library.
Response: Vendor B provides a similar class library but its interface is completely different from the interface provided by vendor A
Assumptions: You don’t want to change your code, and you can’t change vendor B’s code
Solution?: Write new code that adapts vendor B’s interface to the interface expected by your original code

C# Example





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Adapter
{

    public class VendorA
    {

        public string GetResponse()
        {

            return "<Root><Item><Column1>John</Column1> <Column2>Doe</Column2><Column3>John@email.com</Column3> </Item></Root>";
        }
    }

    public class VendorB
    {
        public string GetResponse()
        {

            return "John,Doe,John@email.com\nsantosh,singh,santosh@gmail.com";
        }


    }
    public interface IRquest
    {
        string Get();

    }
    public class Adapter : IRquest
    {
        private VendorB _vendorb = new VendorB();
        public string Get()
        {
            var lines = _vendorb.GetResponse().Split('\n');


            var xml = new XElement("Root",
               lines.Select(line => new XElement("Item",
                  line.Split(new char[] { ',' })
                      .Select((column, index) => new XElement("Column" + index, column)))));

            return xml.ToString();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Adapter client = new Adapter();
            var response = client.Get();
            Console.WriteLine(response);
        }
    }
}