Thursday, July 25, 2013

Observer Design Pattern Example

Announcement Ticker
 public class Announcement
    {
        public string Company { get; set; }
        public string Content { get; set; }
        
       
    }
public class AnnouncementChangeEventArgs
    {
        private Announcement announcement;
        public AnnouncementChangeEventArgs(Announcement announcement)
        {
            this.announcement = announcement;
        }
        public Announcement Announcement
        {
            get
            {
                return this.announcement;
            }
            
        }
    }
public class AnnouncementTicker
    {
        private Announcement announcement;
        public Announcement Announcement
        {
            get
            {
                return announcement;
            }
            set
            {
                this.announcement = value;
                OnAnnouncementChange(new AnnouncementChangeEventArgs(this.announcement));
            }
        }
        public event EventHandler AnnouncementChange;

        protected virtual void OnAnnouncementChange(AnnouncementChangeEventArgs e)
        {
            if (AnnouncementChange != null)
            {
                AnnouncementChange(this, e);
            }
        }
    }
Microsoft Announcement Observer
public class MicrosoftObserver
    {
         
        public MicrosoftObserver(AnnouncementTicker ticker)
        {
            ticker.AnnouncementChange += new EventHandler(bt_BlogChange);
        }

        private void bt_BlogChange(object sender, AnnouncementChangeEventArgs e)
        {
            UpdateDashboard(e.Announcement);
        }

        private void UpdateDashboard(Announcement announcement)
        {
            if (announcement.Company == "0")
            {
                var isNewWindow = true;                 
                MicrosoftDashboard d = ((MicrosoftDashboard)Application.OpenForms["MicrosoftDashboard"]);
                if (d != null && d.Visible == true)
                {
                    isNewWindow = false;
                }               

                d = d ?? new MicrosoftDashboard();
                d.Text = "Microsoft Dashboard";
                var existingContent = d.BlogContent.Text;
                d.BlogContent.Text = string.Format(existingContent + "\n" + announcement.Content);
                if (isNewWindow)
                    d.Show();
            }
        }
        
    }
Google Announcement Observer
public class GoogleObserver
    {
        public GoogleObserver(AnnouncementTicker ticker)
        {
            ticker.AnnouncementChange += new EventHandler(bt_AnnouncementChange);
        }

        private void bt_AnnouncementChange(object sender, AnnouncementChangeEventArgs e)
        {
            UpdateDashboard(e.Announcement);
        }

        private void UpdateDashboard(Announcement announcement)
        {
            if (announcement.Company == "1")
            {
                var isNewWindow = true;
                GoogleDashboard d = ((GoogleDashboard)Application.OpenForms["GoogleDashboard"]);
                if (d != null && d.Visible == true)
                {
                    isNewWindow = false;
                }

                d = d ?? new GoogleDashboard();
                d.Text = "Google Dashboard";
                var existingContent = d.BlogContent.Text;
                d.BlogContent.Text = string.Format(existingContent + "\n" + announcement.Content);
                if (isNewWindow)
                    d.Show();
            }
            
        }

        
    }

Ticker Windows Form
public partial class TIcker : Form
    {
        public TIcker()
        {
            InitializeComponent();
        }

       

        private void button1_Click(object sender, EventArgs e)
        {
            AnnouncementTicker ticker = new AnnouncementTicker();

            MicrosoftObserver msft = new MicrosoftObserver(ticker);
            GoogleObserver ggl = new GoogleObserver(ticker);

            ticker.Announcement = new Announcement { Company = Company.SelectedIndex.ToString(), Content = Content.Text };
               
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            Company.Items.Add(new { Name ="Microsoft", Id = 1});
            Company.Items.Add(new { Name = "Google", Id = 2 });
            Company.DisplayMember = "Name";
            Company.ValueMember = "Id";
            Company.SelectedIndex = 0;
        }

        private void Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

Wednesday, July 24, 2013

“ASP.NET_SessionId” cookie in ASP.NET

When a user opens his web browser and makes a request to a ASP.NET Web Application for which a cookie based Session is enabled, Server generates a new SessionId and sends it to web Browser as a cookie with the name "ASP.NET_SessionId". Applications in the same DNS domain share the same Session Id and cookie. When the user browses within the same DNS domain, the browser sends same Session Id and cookie to the domain. Since it is shared across applications in a domain, so ASP.NET doesn't remove the cookie when the session is expired or Session.Abandon() is invoked. Because of this design, the code that is used to check if a Server Session is actually expired doesn't work properly. Generally we use following code snippet to check if session is expired.
if (Session.IsNewSession)
{
   if (Request.Headers("Cookie") != null && Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0)
   {
        return true;
   }   
}

return false;
As ASP.NET doesn't remove the cookie "ASP.NET_SessionId" when the session is expired, so the above code doesn't check correctly. To ensure the above code works properly, the developer has to manually remove the session cookie in the event of a Session Expiry by using the following code.
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId") { Expires = DateTime.Now.AddDays(-1d) });
 

Monday, July 22, 2013

Custom Binding Handler in Knockout

demo.html


    
    
    
    
    
    
    



First Name: Last Name:

viewModel.js
function ProfileViewModel() {
    this.profileClosure = ko.observable(false),
    this.firstName = ko.observable("Alex");
    this.lastName = ko.observable("Xaviar");
}

myViewModel = {
    profileVM: ko.observable(),
    initialize: function () {
        myViewModel.profileVM = new ProfileViewModel();
        ko.applyBindings(myViewModel);
    }
    
}
ko-extensions.js
ko.bindingHandlers.closureMode= {
    init: function (element, valueAccessor) {        
        var shouldClose = valueAccessor();
        if (shouldClose) {
            disableAll(element);
        }
        else
            enableAll();
    },
    update: function (element, valueAccessor, allBindingsAccessor) {        
        var shouldClose = valueAccessor();
        var allBindings = allBindingsAccessor();
        var highlight = allBindings.highlight || false;
        if (shouldClose){
            disableAll(element);
        }
        else
            enableAll(element);

        if (shouldClose && highlight) {
            highlightAll(element);
        }
        else
            setToNormal(element);
    }
};

function disableAll(element) {        
    $(element).find('#firstname').attr('disabled', true);
    $(element).find('#lastname').attr('disabled', true);
}

function highlightAll(element) {    
    $(element).find('#firstname').addClass('highlight');
    $(element).find('#lastname').addClass('highlight');
    
}

function enableAll(element) {
    $(element).find('#firstname').attr('disabled', false);
    $(element).find('#lastname').attr('disabled', false);
}

function setToNormal(element) {
    $(element).find('#firstname').removeClass('highlight');
    $(element).find('#lastname').removeClass('highlight');

    $(element).find('#firstname').addClass('normal');
    $(element).find('#lastname').addClass('normal');
}

Sunday, July 21, 2013

HTTP Respons Status Codes

  • 2XX - Request worked
  • 3XX - Resource moved
  • 4xx - Client error
  • 5xx - Server error

Saturday, July 20, 2013

Using KnownType in Serialization

[DataContract]
[KnownType(typeof(Student))]
[KnownType(typeof(Teacher))]
public class Person
{
   [DataMember]
   public string Name{get; set;}
}

//Serialize all derived types of Person.
[DataContract]
[KnownType("GetDerivedTypes")]
public class Person
{
   [DataMember]
   public string Name{get; set;}

   static IEnumerable GetDerivedTypes()
   {
       return from type in typeof(Person).Assembly.GetTypes()
       where typeof(Person).IsAssignableFrom(type)
       select type;
   }
}

[DataContract]
public class Student: Person
{
   [DataMember]
   public string Grade{get; set;}
}

[DataContract]
public class Teacher : Person
{
   [DataMember]
   public string Subject {get; set;}
}

public class MySerializer
{
   var mySerializer = new DataContractSerializer(typeof(Person));
   var stream = new MemoryStream();
   var writter = new XMLTextWritter(stream, Encoding.UTF8) {Formatting = Formatting.Indented};
   mySerializer.WriteObject(writter, new Teacher());
   writter.flush();
   Console.Writeline(stream);
   
}


Thursday, July 18, 2013

RESTful WCF Service

CRUD operations using RESTful WCF Service
    [ServiceContract]
    public interface IBlogService
    {
        [OperationContract]
        [WebInvoke(Method="GET", BodyStyle=WebMessageBodyStyle.Bare, RequestFormat= WebMessageFormat.Json, UriTemplate = "Blog/{id}")]
        BlogPost GetBlogPost(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, UriTemplate = "Blog/All")]
        List GetAllPosts();

        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, UriTemplate = "AddBlog/{id}")]
        BlogPost PostBlog(string id, BlogPost post);

        [OperationContract]
        [WebInvoke(Method = "PUT", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, UriTemplate = "UpdateBlog/{id}")]
        void PutBlog(string id, BlogPost post);

        [OperationContract]
        [WebInvoke(Method = "DELETE", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, UriTemplate = "DeleteBlog/{id}")]
        void DeleteBlog(string id);
    }
    [DataContract]
    public class BlogPost
    {
        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public string Content { get; set; }
        [DataMember]
        public string Labels { get; set; }
    }
    
    public class BlogService : IBlogService
    {
        static List posts = new List  
                {              
                    new BlogPost{ Id = "1", Title= "Web Api Framework on .NET", Content = "services exposed over plain HTTP", Labels= "" },              
                    new BlogPost{ Id = "2", Title= "MVC4", Content= "Mobile Support", Labels= "" },              
                    new BlogPost{ Id = "3", Title = "KnockoutJS", Content= "Javascript based MVVM framework", Labels= ""}          
                };


        public BlogPost GetBlogPost(string id)
        {
            WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
            return posts.Find(m => m.Id == id);            
        }

        public List GetAllPosts()
        {
            WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
            return posts;
        }

        public BlogPost PostBlog(BlogPost post)
        {
            WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
            posts.Add(post);
            return post;

        }

        public void PutBlog(string id, BlogPost post)
        {
            var blog = posts.Find(m => m.Id == id);
            blog.Title = post.Title;
            blog.Content = post.Content;
        }

        public void DeleteBlog(string id)
        {
            var post = posts.Find(m => m.Id == id);
            posts.Remove(post);
        }
    }


    
      
        
      
    
    
      
        
          
          
          
                  

        
      
      
        
          
        
      
    
    
      
        
      
      

    
  
  
    
    
    
  


    
    
    
    
    


    
My Blogs
    Add Blog
    Title :
    Content:
    Delete Blog

    Wednesday, July 17, 2013

    Javascript Patterns

    Javascript Prototype Pattern

    var TaxCalculator = function(data){
    this.name = data.Name;
    this.basic = data.Basic;
    this.allowances = data.Allowances;
    this.deductions = data.Deductions;
    this.result = 0
    }
    
    TaxCalculator.prototype = {
    CalculateTax: function(){
    this.result = ((this.basic +this.allowances) - this.deductions)*0.1;
    }
    }
    
    
    $(document).ready(function(){
     var data = {Name:Alex, Basic:4000, Allowances:600, Deductions: 400};
     var calc = new TaxCalculator(data);
    calc.CalculateTax();
     alert(calc.result);
    });
    
    
    Overridding a function in prototype pattern
    TaxCalculator.prototype.CalculateTax = function(){
     this.result = ((this.basic +this.allowances) - this.deductions)*0.2;
    }
    
    Namespaces in javascript
    myNamespace = myNamespace || {};
    
    myNamespace.TaxCalculator = function(data){
    this.name = data.Name;
    this.basic = data.Basic;
    this.allowances = data.Allowances;
    this.deductions = data.Deductions;
    this.result = 0
    }
    
    myNamespace.TaxCalculator.prototype = {
    CalculateTax: function(){
    this.result = ((this.basic +this.allowances) - this.deductions)*0.1;
    }
    }
    
    $(document).ready(function(){
     var data = {Name:Alex, Basic:4000, Allowances:600, Deductions: 400};
     var calc = new myNamespace.TaxCalculator(data);
     calc.CalculateTax();
     alert(calc.result);
    });
    
    Module Pattern
    var TaxCalculator = function(data){
       //private members
       var name = data.Name;
       var basic = data.Basic;
       var allowances = data.Allowances;
       var deductions = data.Deductions;
       var result = 0;
    
       return {
          //public members
          CalculateTax : function(){
             result = ((basic + allowances) - deductions)*0.1;
             return result;
          }
       };
    }
    
    $(document).ready(function(){
     var data = {Name:Alex, Basic:4000, Allowances:600, Deductions: 400};
     var calc = new myNamespace.TaxCalculator(data);
     alert(calc.CalculateTax());
     
    });