Pages

Wednesday, December 1, 2010

OOPs Access Modifiers behaviour



private
protected
public
Internal/friend
Protected internal/friend
By Object
No
No
Yes
Yes
No
By Derived Class
No
Yes
Yes
Yes
Yes (Same Assembly)

Tuesday, November 30, 2010

Monday, November 29, 2010

Static Variables vs Application Object

For having a global variable we can use static variables as well application cache.



Application Object need to be initialized first time into Global.asax.cs application_start() method and keep alive until a IIS reset or worker process recycle not occurs.


1. The cache is thead-safe, i.e.  the objects in the cache may not be thread safe, but the cache collection itself is.

e.g.

Application_Start()
{
Application["globalVar1"]="Global variable One stored here";
Gvar2= "Global Variable Two is here";
}

And this can be get anywhere in application by using
string var1 = (string)Application["globalVar1"]; 


public class Global : System.Web.HttpApplication
{
public static string StaticTest ="This is the original value";
. . .


If a static member is named MyStaticMember in your Global.asax file, you can use MyClass.MyStaticMember to access it from your page.  
  
or 

public static string GVar2;  

For using the Gvar2 we need to simply write the className.Gvar2 // Here Global.Gvar2 will do the work for us.


reading / writing a static reference variable is not (at least not without some additional work).


So what factors you must count for choosing static -
1. Application holds variable as Object.
2. While getting the value we need to caste into the objects which it stores. Of course casting need some value.
  So when we need to use some primitive variables and they are not going to changes very frequent (locking issue in case of frequent changes) we should use static variable.
Application object need to be used when we need to Hold some objects application wide.


Storing and reading a static value is faster when we compare it with the Application object because static variables do not need to look-up in a collection when you refer to them and you do not need to cast from object to a specific type.
The key reason that the Application object exists in ASP.NET is for compatibility with classic ASP code to allow easy migration of existing applications to ASP.NET.

Also, yes, static variables behave the same way regardless of where they are loaded from, and exist exactly once per app domain (unless you're talking about those labeled [ThreadStatic])

Dependency Injection [DI]

Also knows as Inversion of Control, facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies that often inhibit reuse. Dependency injection can help you design your applications so that the architecture links the components rather than the components linking themselves.


Object Dependency : While a class is created by using composition design pattern then it implies tightly coupled class. i.e. If Class A have instance object of Class B in it then it implies that A is dependent on class B also case B futher uses Instance of class C as public/private property/field then it creates a dependency hierarchy which implies A is also depends on Class C.


Advantages of DI
    * Loose coupling
    * Centralized configuration
    * Easily testable

Code becomes more testable because it abstracts and isolates class dependencies.

Disadvantages of DI
primarily is that wiring instances together can become a nightmare if there are too many instances and many dependencies that need to be addressed.

Types of Dependency Injection
There are three common forms of dependency injection:

   1. Constructor Injection
   2. Setter Injection
   3. Interface-based injection

Constructor Injection

Consider a scenario of two layers say MyFacade  and MyBusinessLogic layers with MyFacade  layer to operate properly depends on the MyBusinessLogic layer. All the business logic classes implement an IMyBusinessLogic interface.

So MyFacade   class uses its argument or parameterized constructor and pass the required BusinessLogic type to inject the dependency.

   interface IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------

   }
 
   class Prod : IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------
   }
 
   class Cust : IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------
   }
------------------------------------------------------------------------
   public class MyFacade
   {
      private IMyBusinessLogic bl;
      public MyFacade  (IMyBusinessLogic bl)
      {
         this.bl = bl;
      }
   }


So in the caller class

    IBusinessLogic p1 = new Prod();
    MyFacade   MyFacade  = new MyFacade  (p1);



Here we can see that we can pass instance of any of concrete class to the MyFacade   constructor. The constructor does not accept a concrete object; instead, it accepts any class that implements the IBusinessLogic interface.

Advantage: It is flexible and promotes loose coupling

Disadvantage:
1. Once the class is instantiated, you can no longer change the object's dependency.
2. Because you can't inherit constructors, any derived classes call a base class constructor to apply the dependencies properly. Fortunately, you can overcome this drawback using the setter injection technique.



Setter Injection:
lets you create and use resources as late as possible

This is more flexible than constructor injection because you can use it to change the dependency of one object on another without having to create a new instance of the class or making any changes to its constructor.

interface IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------

   }
 
   class Prod : IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------
   }
 
   class Cust : IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------
   }
------------------------------------------------------------------------
public class MyFacade
     {
      private IMyBusinessLogic bl;
 
      public IMyBusinessLogic BL
         {
          get
          {
            return bl;
          }
 
            set
          {
            bl = value;
          }
        }
     }


Usage:

   IMyBusinessLogic p1 = new Prod();
   MyFacade   bf = new MyFacade  ();
   bf.BL = p1;


Advantage:
The dependency between the MyFacade   and the instance of IMyBusinessLogic can be changed even after instantiating the MyFacade   class.

Disadvantage:
1. Setters cannot be immutable
2. It can be difficult to identify which dependencies are needed, and when.

So normally we choose constructor injection over setter injection unless you need to change the dependency after instantiating an object instance, or cannot change constructors and recompile.


Interface Injection:
This injection is used while other classes need to implement the common interface to inject the dependencies. So in the following example IMyBusinessLogic interface as a base contract to inject an instance of any of the business logic classes (Prod or Cust) into the MyFacade   class.


interface IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------

   }
 
   class Prod : IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------
   }
 
   class Cust : IMyBusinessLogic
   {
     //-------------
     //-------------
     //-------------
     //-------------
   }
------------------------------------------------------------------------
   public class MyFacade
   {
      private IMyBusinessLogic bl;
      public SetBLObject(IMyBusinessLogic bl)
      {
         this.bl = bl;
      }
   }


Usage:
   IMyBusinessLogic p1 = new Prod();         
   IMyBusinessLogic p2 = new Cust();
   MyFacade   bf = new MyFacade ();
   bf.SetBLObject(p1);        //or bf.SetBLObject(p2);


DI can can be used to abstract the dependencies of an object outside of it and make such objects loosely coupled with each other.

Friday, November 26, 2010

Primary Key vs Unique Key

Unique Key constraints:

Unique key constraint will provide you a constraint like the column values should retain uniqueness.
It will allow null value in the column.
It will create non-clustered index by default
Any number of unique constraints can be added to a table.

Primary Key:
Primary key will create column data uniqueness in the table.
Primary key will create clustered index by default
Only one primary key can be created for a table
Multiple columns can be consolidated to form a single primary key
It wont allow null values.

Thursday, October 21, 2010

ASP.Net configuration based default timeouts

  1. executionTimeOut : Default value is 110 seconds.
  2. maxRequestLength : Default value is 4096 KB (4 MB).
  3. Session Timeout : Default value is 20 minutes. 
The above two are the configuration of httpRuntime attribute.
Note: If session timeout is less then execution timeout it means when the request finishes its processing meanwhile, the session get’s end which can raise an error.


e.g.
   1: <httpRuntime executionTimeout="43200" maxRequestLength="104856"  />
   2: <sessionState mode="InProc" cookieless="false" timeout="720"/>

Notice, executionTimeout needs to be filled in seconds where as timeout of sessionstate needs minutes as input.

Application Pool also have idle timeout settings which can be useful.

To get application pool in Windows 2003  :
  1. Right click on your website to display properties page
  2. In the 'Home Directory' Tab of properties contains a drop down Application Pool at last most.
  3. You can notice the name, and close screen.
If you are increasing the session timeout greater then 20 you must need to configure the same amount in your Application Pool Settings.

The httpRuntime tag in ASP.NET configuration files lets you determine several behaviors of ASP.NET at the machine or site, including the global value for script timeout. Here's the complete syntax for this tag:


             maxRequestLength="kbytes"
             minFreeThreads="numberOfThreads"
             minLocalRequestFreeThreads="numberOfThreads"
             appRequestQueueLimit="numberOfRequests" 
             useFullyQualifiedRedirectUrl="true|false"  />
executionTimeout is the maximum time an .aspx page can run before timing out. You should extend this value for pages that perform long database queries or remote calls to a Web service. This attribute corresponds to the Server.ScriptTimeout property.

The format of configurations corresponding to each dot net version
.net [4,3.5]

   executionTimeout = "number"
   maxRequestLength = "number"
   requestLengthDiskThreshold = "number"
   useFullyQualifiedRedirectUrl = "[True|False]"
   minFreeThreads = "number"
   minLocalRequestFreeThreads = "number"
   appRequestQueueLimit = "number"
   enableKernelOutputCache = "[True|False]"
   enableVersionHeader = "[True|False]"
   apartmentThreading = "[True|False]"
   requireRootedSaveAsPath = "[True|False]"
   enable = "[True|False]"
   sendCacheControlHeader = "[True|False]"
   shutdownTimeout = "number"
   delayNotificationTimeout = "number"
   waitChangeNotification = "number"
   maxWaitChangeNotification = "number"
   enableHeaderChecking = "[True|False]"
/>

.Net [2,3]

   executionTimeout = "HH:MM:SS"
   maxRequestLength = "number"
   requestLengthDiskThreshold = "number"
   useFullyQualifiedRedirectUrl = "[True|False]"
   minFreeThreads = "number"
   minLocalRequestFreeThreads = "number"
   appRequestQueueLimit = "number"
   enableKernelOutputCache = "[True|False]"
   enableVersionHeader = "[True|False]"
   apartmentThreading = "[True|False]"
   requireRootedSaveAsPath = "[True|False]"
   enable = "[True|False]"
   sendCacheControlHeader = "[True|False]"
   shutdownTimeout = "HH:MM:SS"
   delayNotificationTimeout = "HH:MM:SS"
   waitChangeNotification = "number"
   maxWaitChangeNotification = "number"
   enableHeaderChecking = "[True|False]"
/>

.Net [1.1]


             maxRequestLength="size in kbytes"
             executionTimeout="seconds"
             minFreeThreads="number of threads"
             minFreeLocalRequestFreeThreads="number of threads"
             appRequestQueueLimit="number of requests"
             versionHeader="version string"/>

Wednesday, October 20, 2010

UML Diagrams brief overview


In brief all diagrams are consider to depict the following things
Activity diagrams*- high-level business processes
Class diagrams***- Collection of static model elements
Communication diagrams**- instances of classes, their interrelationships and message flow b/w them
Component diagrams*** – components composing application/system/enterprise.
Composite Structure diagrams***- internal structure of classifiers with their interaction points to other system parts
Deployment diagrams***- Execution architecture of system.
Interaction overview diagrams**- overviews the control flow within system/business process
Object diagrams***- objects and their relationships at a point in time
Package diagrams***- model element organization and dependencies between packages
Sequence diagrams**- sequential logic modeling
State machine diagrams*- object/interaction state and transition between states
Timing diagram**- state/condition change response of classifier instance/role over time in response to external events
Use case diagrams*- actors and their interrelationships.
Classifiers: such as class/component/use case

Selecting the random rows from a database table for each query fired

 MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

 PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

 Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

 IBM DB2

SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Thursday, October 14, 2010

Drived Class must serializable

While a class is marked serializable and later another class extends the same class then by default everything in the parent class will be with derived class too. But it not means that if parent class is serializable then child not need to implement the serializable interface as parent already have, because the implementing of serializable by parent means all the properties of the parent are serializable in parent as well as in child but as child properties are not marked as serializable so we must specify explicitly the child class methods too as serializable or we need to mark child class to implementing serializable.

Monday, September 20, 2010

Disable right click/text selection in web page

In case its required no one can use right click context menu in browser while opening the page to restrict all the operations possible with context menu commands the the following is the command that will do the job 
 
document.oncontextmenu = function(){return false;}; 
 
In case its also required to restrict the selection of text as if text will be able to selected then hot keys can copy the contents but disabling selection of text can prohibit the copy. So to disable the selection the following will disable text selection.
 
document.onselectstart= function() {return false;};  
And if these commands are written in the javascript code block then the specified features will be enforced after complete page is loaded with javascript block.

Tuesday, August 10, 2010

JavaScript Debugging [Visual Studio]

The various steps to enable java script debugging is as given below:

1. ASP.Net application configuration to enable debugging
    Open the ASP.Net application in Visual Studio and open ‘web.config’ that created with application and find the tag ‘compilation’ in the file. The line may look like as below:

    If debug=”false” then set it to debug=”true” and resulting will look like as below:

    2.    IIS Configuration to support debugging
    Start --> Settings --> Control Panel --> Administrative Tools --> Internet Information Services (IIS)
    --> Expand Web Sites --> Default Web Site --> right click on your web project required to be debugged and select properties --> click Virtual Directory Tab --> click configuration button --> and in the new opened window click Debugging Tab and ensure that two check boxes labeled 1. “Enable Server Side Script Debugging” 2. and “Enable Client Side Script Debugging” to be checked.


    3. Configure Web browser for debugging:
     Open IE and click on menu Tools --> Internet Options --> Advanced Tab --> if ‘Disable Script Debugging (Internet Explorer)’ and Disable Script Debugging (Other)’ check boxes are checked then uncheck those two check boxes and click button OK. (Refer below Screen Shot)



    4.    Attaching ASP.Net process to Visual Studio:
    If application is opened in VS 2003. Then under Tools menu select attach a process and select aspnet process and attach the process to the application.
    If you open the project in VS 2005 or later then it does not require you to explicitly attach the aspnet process. In the JavaScript add a break point where you want to debug and also add a break point in the .vb or .cs code file where the JavaScript function is called.
    Now run the application. The application running will break at the break point within the javascript code as required.

    Features

    The JavaScript debugger presents many standard debugging features. The following list provides a review of some of these features.
    • Breakpoints: Breakpoints allow you to stop code execution at specific points within the source code. JavaScript breakpoints work just like C#/VB breakpoints.
      Breakpoints are set/cleared by clicking to the left of the code within the IDE; by using the Debug menu or by using the Breakpoint Context menu available by right-clicking on the code. In addition, you may create conditional breakpoints to allow you to define conditions for the breakpoint, as well as set up a macro to run or a message to print when the breakpoint is triggered.
      Breakpoints are viewable in the Watch window located by default in the lower left of Visual Studio 2008.
    • Call Stack: The Call Stack tab in the lower right of Visual Studio 2008 allows you to view what is being called when the ASP.NET page is loaded/running.
    • Locals: The Locals tab in the lower left of Visual Studio 2008 allows you to view the values of variables and objects during script execution. Also, you may change the contents of one of the local variables while the page is running.
    • Execute code: The Immediate Window tab in the lower right of Visual Studio 2008 allows you to execute JavaScript code on-the-fly during page execution.
    The Debug drop-down menu within Visual Studio 2008 provides a Windows submenu that allows you to define what windows to display while debugging. For example: Locals, Watch, Call Stack, and Immediate Window.
    The most used feature during debugging is often breakpoints because you can use them to stop code execution and examine the state of variables and objects at that point in the script. Breakpoints provide a number of features (which are available via the Debug drop-down menu during a debugging session) for their use.
    Code execution stops at each breakpoint — unless it is a conditional breakpoint whose condition has not been met. Once the code is halted, you may choose to continue one line at a time or until the next breakpoint is encountered.
    The debugger is actually enabled via the Debug menu in Visual Studio 2008. You go to Debug | Start to begin a debugging session or press [F5]

    Tuesday, July 6, 2010

    Dispose method and Finalize method

    Finalize Method: As .net provides a great feature of memory management which handles all kind of allocations and de-allocations automatically and for de-allocating it uses Garbage Collector. So in .NET Garbage collector does almost all clean up activity for your objects. But all the process that can happen for de-allocation is applicable only that are managed by CLR or that are constructed according to the .Net but those object that are not managed by .Net CLR are un-managed codes/objects can not be de-allocated directly by GC So these unmanaged resources (ex: - Windows API created objects, File, Database connection objects, COM objects etc) that are outside of the scope of .NET framework are needed to be cleaned explicitly. For these types of objects .NET framework provides Object.Finalize method which can be overridden for our own code execution within this function and which can be used to clean up code for un-managed resources. This method is used in VB.Net which is called by CLR when Garbage Collector destroys an object. While in C# destructors are there for the same purpose.

    Dispose Method: .NET provides “Finalize” method in which we can clean up our resources. But relying on this is not always good. This is because it is only called by the GC and you can't determine when it will be called (even though you can force it to be called, but that's not recommended).So the best is to implement “Idisposable” interface and implement the “Dispose” method where you can put your clean up routines.

    But benefit of finalize over Dispose is that finalize is executed itself and not required to be called while Dispose is required to be called. So in case we require to execute dispose itself then we can call it within finalize which is executed by CLR while destroying the object. But in case we define call dispose this way also developer called dispose too at somewhere then call dispose can occur twice that can throw exception or some issue so to avoid call twice we can suppress the call to finalize after dispose by using GC.SuppressFinalize within dispose function some in that case if dispose is not called then it will be executed with finalize while if its called then suppressfinalize call will suppress the call to finalize method. Below is the sample code of the pattern. This is the
    best way we do clean our unallocated resources and yes not to forget we do not get the hit
    of running the Garbage collector twice in this case.


    Note:- It will suppress the finalize method thus avoiding the two trip.
    Publish Post


    Public Class ClsTesting
    Implements IDisposable
    Public Overloads Sub Dispose()Implements IDisposable.Dispose
    ' write ytour clean up code here
    GC.SuppressFinalize(Me)
    End Sub
    Protected Overrides Sub Finalize()
    Dispose()
    End Sub
    End Class

    Abstract Class And Interface Class

    Interface Class: Its some kind of contract between developer/Class implementation and real world/caller of class object that commits what kind of the provisions will be their that can be accessed from the class implementation and also implementation is bound to provide the implementation of this contract.

    Abstract Class: Its also define some kind of contract that a implementing class signs and bound to implement all the abstract functions for which no implementation is provided in the abstract class. So outer world of implementing class have knowledge of all the provisions and availability of functionality that can be called directly from the object of implementer class.

    Benefit of Interface over Abstract class: As from the definition of the abstract class question arises that when everything that an Abstract class enforce or provide then why concept of Interface still exists the most well known answer of this question comes while an implementing class comes to the situation when it has to implement more than one kind of contracts to the outer world which makes the requirement of multiple inheritance which is not possible in case of abstract class as an implementer class can not implement more than one abstract class but it can implement more than one Interface.

    Benefit of Abstract class Over Interface: Both seems to be related to contract between object calling and class providing implementation of interface. Also in case of existence of interface class an additional benefit it also facilitate with the feature of multiple inheritance then why abstract class exists. Answer to this query comes from abstract class's another feature that says if some of the implementation that is known and predefine also is common and usable in derived classes too then in case of abstract class we can implement this functionality in abstract class itself that will be available with all the derived classes which is not possible with usage interfaces.

    If there is any other difference/benefit for these then I request to viewers to add their comments that can be beneficial for other viewers too.

    Thursday, May 27, 2010

    SQL Query: Second Maximum/Second Minimum

    Tip to find the first max/min is predefined but what about second. Here is one of the tip for well known table employee

    Second maximum salary
    Select max(salary) from employees where regid NOT IN
    (Select max(salary) from employees)

    Second minimum salary
    Select min(salary) from employees where regid NOT IN
    (Select min(salary) from employees)

    Wednesday, March 24, 2010

    Visual Studio 2010 .Net Framework 4.0 Some of the enhavements

    Following are some of the Visual Studio 2010 and .NET Framework 4 IDE Enhancements
    1. Multi monitor support
    2. Multi targeting
    3. Parallel Development
    4. Side by Side execution
    5. Backward compatibility and SqlServer 2008 integration.
    6. Add Reference enhancements for developers
    7. Windows 7 support for developers
    8. Share Point 2010 enhancements
    9. Office Business Application Support
    10. Cloud Development
    11. Document Map Margin and Visual Studio 2010 Tips.

    Following are some of the applications we can develop using the .NET Framework 4.0.

    * Console Applications
    * Windows Forms applications
    * Windows Services
    * WPF Browser applications
    * WPF Applications
    * Web Applications
    * Web Services, Ajax enabled Web Services
    * Dynamic Data entities Web Applications
    * Dynamic data LINQ to SQL Web Applications
    * Office Applications
    * Reporting applications like crystal reports
    * Cloud Services using Windows azure tools
    * SharePoint projects, Business Data Connectivity model and workflow applications
    * Sliverlight applications
    * WCF Services, Ajax enabled WCF services
    * Workflow console and workflow service applications
    * CLR Console applications using VC++
    * MFC and win32 applications
    * Data Tier Applications and advanced database applications.


    Refernce

    Monday, March 22, 2010

    MS SQL server name and instance name

    Open the run command and type "sqlcmd" and press enter will open the related console and to get the server name and instance name, enter the following command in the command prompt

    select @@servername
    go
    Also, connection string can be verified by entering the following command in the 'Run' window from windows start

    sqlcmd -S Server\Instance

    where server is the name of the server running Sql server and Instance is the name of the instance running on the server.

    Refernce:
    How to: Identify a SQL Server Express Instance