Sunday, December 4, 2016


Context:Given below a grid of rules applicable for different screen in a financial application.
Objective: To come up with a design that supports the implementation of the given requirement.

Design:

Thursday, December 1, 2016


Resource level locks in Sql Server
  1. Row
  2. Key
  3. Table
  4. Page
  5. Extent
  6. Partition
  7. Database
Models of locks
  1. Shared Lock(S) - Can be held by any processes
  2. Update Lock(U) - Mix of shared and exclusive lock
  3. Exclusive Lock(X) - Can be held by only one process
  4. Intent Lock(I)
    • Intent Shared(IS)
    • Shared with Intent Exclusive(SIX)
    • Intent Exclusive(IX)
  5. Bulk Update Lock(BU)
  6. Schema Lock
    • Schema Stability (Sch-S) - It is applied while generating the execution plan
    • Schema Modification (Sch-M) - It is applied while executing a DDL Statement
Transaction Isolation Levels
  1. Pessimistic
    • Read Uncommitted (NOLOCK) - No shared lock acquired
    • Read Committed (READCOMMITTED) (Default) - Shared lock acquired and released immediately
    • Repeatable Read (REPEATABLEREAD) - Lock till the end of transaction
    • Serialization (HOLDLOCK) - Lock till the end of transaction and a range of rows
  2. Optimistic
    • Snapshot
    • Snapshot Read Committed
  1. sys.dm_tran_locks view keeps track of a Lock and resource identification
  2. sys.dm_exec_sessions view provides transaction isolation level in use for the current process

Friday, December 6, 2013

How to use SQLCacheDependency in ASP.NET MVC

Database
Database : Employee
Table : EmpDetails
Developer Command Prompt
aspnet_regsql.exe -S DBServerName -E -d database name -ed 
aspnet_regsql.exe -S DBServerName -E -d database name -t table name -et
Web.Config
  
    
      
        
          
        
      
    
  
Cache Class
public class SQLDependencyCacheProvider
    {
        private static System.Web.Caching.Cache _cache;

        public System.Web.Caching.Cache Cache
        {
            get
            {
                if (_cache == null)
                {
                    _cache = HttpRuntime.Cache;
                }

                return _cache;
            }
        }

        public T GetCacheItem(string key)
        {
            var item = Cache.Get(key);
            return (item != null) ? (T)Convert.ChangeType(item, typeof(T)) : default(T);
        }

        public void InsertCacheItem(string key, T value)
        {
            Cache.Insert(key, value, new SqlCacheDependency("Employee", "EmpDetails"));
        }
    }


Thursday, December 5, 2013

How to Configure ASP.NET Tracing for ASP.NET MVC Applications

  1. ASP.NET Application Level Tracing
  2. Writting Custom ASP.NET Trace Messages using System.Diagnostics.TraceSource class and trace sources
  3. Writting Custom ASP.NET Trace Messages using System.Diagnostics.Trace class
PRE-Requisite(Trace Complier Constant) : Trace statements (Custom tracing) require the TRACE compiler constant, but it’s on by default and you can verify that in the Build tab of the project properties window
The problem is that this setting in the .csproj file only applies to .cs files. ASP.NET uses a different compile process for .cshtml files (or .aspx files in Web Forms), and the settings for that compile process are in the Web.config file. If you don’t explicitly specify the TRACE constant there, tracing method calls in .cshtml views are ignored. Below is an example of what you have to add to the application Web.config file for a Visual Studio project that targets .NET 4.5, in order to define a TRACE constant for the .cshtml compiler:
 
   
     
     
   
 

ASP.NET Application Level Tracing

Web.Config entries

  
    
  


    
       
      
      
      
    
    
        
         
          
          
          
                   
         
       
      
        
          
          
          
        
          
    
    
      
      
    
    
      
        
        
      
    
  
C# Code
 using System.Diagnostics;
 public class AccountController : Controller
    {
        public ActionResult Index()
        {            
            TraceSource source = new TraceSource("AccountController");
            source.TraceEvent(TraceEventType.Warning, 100, "This is message logged from Account Controller");
            return View();
        }

    }
Writting Custom ASP.NET Trace Messages using System.Diagnostics.Trace class
 using System.Diagnostics;
 public class AccountController : Controller
    {
        public ActionResult Index()
        {          
            Trace.WriteLine("This is message logged from Account Controller");
            return View();
        }

    }

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');
}