Friday, December 3, 2010

default access modifier in c#

internal


 public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Reference:
http://msdn.microsoft.com/en-us/library/ms173121.aspx

MVC pattern


Reference:

keys

Primary key
  • an attribute/column which uniquely identifies a record
  • primary key can be column/combination of columns
  • primary key cannot have null values

Candidate key

  • Candidate key is a column which is not a primary key, but it can qualify as a primary key
  • there can be multiple candidate key in one table

alternate key

  • any of the candidate key that is not part of primary key

Tuesday, November 30, 2010

yeild

yeild is the income return of an investment. (in finance)

in C#,

  • yeild keyword use inside iterator block.
  • it indicates the end of iterator block

restriction
  • cannot use with unsafe block
  • parameter to method cannot be out/ref 
  • cannot appear in anonymous method

Thursday, November 25, 2010

correlated sub query

It is a query nested inside another query.

http://en.wikipedia.org/wiki/Correlated_subquery


Scenario: Write a query to select all employees from eastern region. DB diagram follows:




--select all employees from Eastern region
select * from employees where EmployeeID in
(
    -- select all Employees under territory which comes under Eastern region
    select EmployeeID from employeeterritories where TerritoryID in
    (
        --select all territory for Easter region (RegionID = 1)
        select TerritoryID from territories where RegionID = 1
     )
 )

Generalization & Realization

In UML modeling,

Generalization is inheritance.
Realization is implemeting interface.


In UML modeling, generalization relationship is a relationship in which one entity is based on another entity.

Realized - is a related to interface. Interface should implement in class, in UML terms it is called as realized. To realize an interface, a class should implement all its properites and methods

Reference:

1. Generalization:

http://publib.boulder.ibm.com/infocenter/rsmhelp/v7r0m0/index.jsp?topic=/com.ibm.xtools.modeler.doc/topics/creal.html

2. Realization:

http://publib.boulder.ibm.com/infocenter/rsmhelp/v7r0m0/index.jsp?topic=/com.ibm.xtools.modeler.doc/topics/creal.html

Monday, November 22, 2010

upcasting and downcasting

upcasting - is possible, its implicit coversion and is safe. (ie,  A aa=new B() - is upcasting. Here were are converting from Type B to Type A. It is possible, because A is the base class. And all the base class methods and properties will be available in object aa). Its called upcasting because we more moving up the object hierarchy.

downcasting - is explicit conversion and is unsafe. you will have to be very careful while downcasting types.  Its called downcasting because we are moving down the object hierarchy.


(with sample: class A, class A:B, class C:B)

Class A
{
}

Class B:A
{
}

Class C:B
{
}


Question:
A aa=new B();       // is this possible? Ans:
A aa=new C();       // is this possible? Ans:
B bb=new A();       // is this possible? Ans:
B bb=(B)new A();  // is this possible? Ans:


Solution

A aa = new B(); // is possible.

Implicit conversion from Type B to Type A is possible. Because Type A is the base class and Type B is derived from Type A.

//B bb = new A();   //compile Error : Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists


//B bb = (B) new A(); //runtime Error : System.InvalidCastException - Unable to cast object of type 'A' to type 'B'



Hint:

Car c=new BMW();   //possible
BMW b=new Car();  //not possible, compile error - implicit conversion not possible from type Car to BMW
BMW_E_Series be=new Car(); //not possible, compile error
BMW_E_Series be= (BMW_E_Series) new Car(); //runtime error, explicit conversion not possible


Reference:

http://www.c-sharpcorner.com/UploadFile/pcurnow/polymorphcasting06222007131659PM/polymorphcasting.aspx

Tuesday, November 16, 2010

Difference between new Operator and Modifier

• new operator Used to create objects on the heap and invoke constructors.

• new modifier Used to hide an inherited member from a base class member.

Example for new modifier:


Tuesday, November 9, 2010

tic tac toe

Create design for tic tac toe game. Draw use case diagram, class diagram & write the pseudo code of the logic.

Nested class

namespace NestedClass
{
class Program
{
static void Main(string[] args)
{
A a = new A();

A.AA aa = new A.AA();

}
}

public class A
{
public class AA
{
public int i = 10;
A x = new A();
A.AA xx = new AA();
}
}
}

Application state in ASP.NET

  • Application is a server side state mechanism in ASP.NET.
  • It is a global way to store data in ASP.NET applications.
  • It stores as key/value pair.
  • application state is an instance of HttpApplicationState class
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Different state management techniques in ASP.NET

client side state management techniques:

  1. ViewState
  2. ControlState
  3. Cookies
  4. Hidden fields

Server side state management techniques

  1. Session
  2. Application
Reference: http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

String is a reference type. In the below code, what would be the output?

class Program
{
static void Main(string[] args)
{
string s = "abc";
CallMethod(s);
Console.WriteLine(s);
Console.Read();

}
static void CallMethod(string s)
{
s = "xyz";
}
}

Output: abc

difference between server.transfer and response.redirect

Both Respone.Redirect and Server.Transfer open up another page, but the interaction between client(browser) and server(asp.net) differs in each situation.

Resonse.Redirect simply tell the browser to visit another page.
Its the reponsibility of the browser to open up the another page.
External sites can be opened.

Server.Transfer works for only sites which runs on the server.
External sites cannot be opened.
Sharing states between pages is much easier using Server.Transfer.
Server.Transfer keeps the URL the same. This may lead to confusion.

Tuesday, October 19, 2010

unit testing void methods

Assert class does not allow us to test void methods. So the work around would be to throw Exceptions from the void method, and handle it in your test class.

NUnit.Framework provides a method level attibute - ExpectedException for handling exceptions in your test class.


Reference: http://www.nunit.org/index.php?p=exception&r=2.2.10




Wednesday, August 4, 2010

Team building games

1. fit for you card


- FFY
- its an employee feedback method
- what makes you satisfied work with your organization
- helps to improve relationships with your manager/peer/team lead

 2. cross LAVA river & stay safe


- rule1: work together
- rule2: use potoons(paper plates) to cross river.
- rule3: At any point of time human contact should be there on potoons
- rule4: potoons disappear without human contact, so work together
- Good luck and have fun!




potoons - call it as magic plates


3. Musical chair 

- strom came and took away


1. everyone whoz wearing company badge
2. everyone who is smart
3. everyone has black hair
4. everyone has black shoe


- If team size is 25, arrange 24 chairs, one person would be the instructor
- You should look for a chair in your right hand side,
- do not sit on the adjacent chair/same chair
- Enjoy!


Note: This is the best game can be played after a heavy lunch as this requires physical invlovement.



References:

Team Building Activities, Initiative Games, & Problem Solving Exercises:
http://wilderdom.com/games/InitiativeGames.html

Tuesday, May 18, 2010

ClickOnce

Advantage of using ClickOnce

1. windows installer deployment requires administrator privileges where is normal user can do installation using ClickOnce
2. ClickOnce allow to set automatic application updates
3. There will not be any version conflicts using ClickOnce



Requirement: Need to deploy a console based application to all the machines in the network. And whenever there is any functionality addition to application it should update in already installed the applications in the network.














Solution: Use ClickOnce feature provided by Microsoft along with visual studio 2005.

People were not preferred to develop any winforms/console applications before introduction of ClickOnce feature. This is because deployment & maintenance was an overhead.

ClickOnce helps you to deploy your WPF, winforms or console application in any machines in the network or any standalone machines. There are 3 ways in which we can achieve this.

  1. Publish using http
  2. Copy to shared folder in server.
  3. Write to CD/DVD
Here are the steps for Publish using http.

Make your changes in the application and set assembly version in assemblyInfo.cs file




You could also check assembly version at Project-Properties-Publish tab- Modify publish version



Use publish option under build menu for publishing the changes using http




 
Click on Next





Click on Finish, Brower opens up with the publish details. Choose Install button to install the software










Now big question: Say I am a user in the network and I have already installed the application. So whenever a new patch is updated or new functionality is added, I want those changes to reflect in my application automatically.


ClickOnce give an option to configure this. It is called as Update Strategy. This can be achieved in 3 ways:

  1. After starting up the application
  2. Before starting up the application
  3. making the updates required

I am going with before starting up the application. This option can be set using Project-Properties-Publish tab-Click on Update button.






Say I have updated my application or I did some code change, I am going to publish it in to the website





Repeat the publish steps.





You get the updates when you click on Ok



 
How it works: I guess it is based on publisher-Subscriber policy.

.net difference between throw and throw ex

  • stack information is truncated if we are using throw ex
  • where as stack information gets preserved in throw

throw ex - throw
throw  - rethrow


class Program
    {
        static void Main(string[] args)
        {
            A aa = new A();
            aa.Method1();
        
            Console.Read();
        }
    }

    class A
    {
        public void Method1()
        {
            try
            {
                B bb = new B();
                bb.Method2();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
    }

    class B
    {
        public void Method2()
        {
            try
            {
                C cc = new C();
                cc.Method3();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    class C
    {
        public void Method3()
        {
            try
            {
                throw new InvalidOperationException();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }
    }
 


throw
at CatchSample.C.Method3() in C:\temp\oops\oops\CatchSample\Program.cs:line 60
at CatchSample.B.Method2() in C:\temp\oops\oops\CatchSample\Program.cs:line 45
at CatchSample.A.Method1() in C:\temp\oops\oops\CatchSample\Program.cs:line 25

throw ex
at CatchSample.B.Method2() in C:\temp\oops\oops\CatchSample\Program.cs:line 45
at CatchSample.A.Method1() in C:\temp\oops\oops\CatchSample\Program.cs:line 25

NoteStackTrace information is lost in case of throw ex


Reference:

http://aspadvice.com/blogs/joteke/archive/2004/04/15/2277.aspx

http://geekswithblogs.net/sdorman/archive/2007/08/20/Difference-between-quotthrowquot-and-quotthrow-exquot-in-.NET.aspx

Monday, May 17, 2010

Accessing COM object from .net

  • .NET COM interop allows to use existing COM object in .net without modifying original component
  • First step is to import relevant COM types using COM interop utility.
  • Tlbimp.exe is the utility to import COM types to managed application.
  •  

Reference: http://msdn.microsoft.com/en-us/library/aa645736%28VS.71%29.aspx

Saturday, May 15, 2010

Difference between singleton and static classes

  • Singleton can be used with parameters to methods, but you cannot use static class as parameters.
  • Singleton can be used with interfaces
  • static class mainly use to hold gloabl data of application

Reference: http://dotnetperls.com/singleton-static

Saturday, May 1, 2010

Security in ASP.NET

Following are the steps in which security can be enforced in ASP.NET

  1. Authentication
  2. Authorization
  3. Privacy or Confidentiality
  4. Data integrity
  5. Non-Repudation

Authentication is the process of validating the user credentials.
Authorization is the process of checking the access of the authenticated user for a resource.
Privacy is the process of ensuring the passed message over wire is not dropped
Data integrity is the process of ensuring the data is not hampered or modified while passing through the wire.
Non-repudiation ensures that the author of the message/data cannot disavow responsibility.


Authorization is the process of checking access of an identity. .NET allows 2 ways to authorize access to the resource.

  1. FileAuthorization
  2. URLAuthorization
FileAuthorization check access in access control list (ACL) of the ASP.NET page for the identity. ACL will have the access details for the users, and authorization happens by looking at ACL.

URLAuthentication allow or deny access to user or role based on the entry in the configuration file. Authorization section in the configuration file allow to add access detail for the user.


  
  
  
  




Reference:

http://www.c-sharpcorner.com/UploadFile/gsparamasivam/CryptEncryption11282005061028AM/CryptEncryption.aspx

Wednesday, April 28, 2010

Caching in ASP.NET

If you want to improve performance of your ASP.NET application, then caching is the obvious choice.

Retrieving data/resources outside application takes more processing steps, more time and consumption of many resources in the server. ie, request will have to go to the server and server may have to contact a sql server for details.

consider if the data/resource readily available in the browser. This saves time, and eliminates many processing steps and result is high performance.

this technique of temporarily storing page output/ application data in client/server is called as caching

Caching can be implemented in 3 different ways:

  1. output caching
  2. fragment caching
  3. data caching

output caching - entire asp.net page can be cached. So that page don't have to re-create everytime and this results in fast loading of web page

fragment caching - part of asp.net page is cached and this part is loaded fast. @ OutputCache directive can be used for caching

data caching - caching application data improves the performance. Cache object allows to add any object to the cache. It is stored as key value pair.

Reference:

http://authors.aspalliance.com/aspxtreme/webapps/aspcachingfeatures.aspx

Tuesday, April 27, 2010

delegate & multicast delegate

Delegate is like function pointer.

  • Delegate used to invokes a function.
  • Multicast delegate used to invoke more than one function.

class demo
    {
        // delegates are used to invoke function
        delegate int mathdelegate(int a, int b);
        
        public demo()
        {
            mathdelegate objDelegate = new mathdelegate(this.add);
            int result = objDelegate(10, 20);
            Console.WriteLine(result);


            //multicast delegates are used to invoke more than one function
            objDelegate += new mathdelegate(sub);
            result = objDelegate(30, 10);
            Console.WriteLine(result);

            objDelegate += new mathdelegate(mul);
            result = objDelegate(30, 10);
            Console.WriteLine(result);

            
        }

        public int add(int a, int b)
        {
            return a + b;
        }

        public int sub(int a, int b)
        {
            return a - b;
        }

        public int mul(int a, int b)
        {
            return a * b;
        }
    }

Friday, April 23, 2010

outlook object model overview

Accessing Objects in an Outlook Project


--------------------------------------------------------------------------------



Outlook provides many objects with which you can interact. To use the object model effectively, you should be familiar with the following top-level objects:



•Application



•Explorer



•Inspector



•MAPIFolder



•MailItem



•AppointmentItem



•TaskItem



•ContactItem



Application Object

The Application object represents the Outlook application, and it is the highest-level object in the Outlook object model. Some of the most important members of this object include:



•The CreateItem method which you can use to create a new item such as an e-mail message, task, or appointment.



•The Explorers property, which you can use to access the windows that display the contents of a folder in the Outlook user interface (UI).



•The Inspectors property, which you can use to access the windows that display the contents of a single item, such as an e-mail message or meeting request.



To get an instance of the Application object, use the Application field of the ThisAddIn class in your project. For more information, see Programming Application-Level Add-Ins.



Note

To help avoid security warnings when you use properties and methods that are blocked by the Outlook object model guard, get Outlook objects from the Application field of the ThisAddIn class. For more information, see Specific Security Considerations for Office Solutions.





Explorer Object

The Explorer object represents a window that displays the contents of a folder that contains items such as e-mail messages, tasks, or appointments. The Explorer object includes methods and properties that you can use to modify the window, and events that are raised when the window changes.



To get an Explorer object, do one of the following:



•Use the Explorers property of the Application object to access all of the Explorer objects in Outlook.



•Use the ActiveExplorer method of the Application object to get the Explorer that currently has focus.



•Use the GetExplorer method of the MAPIFolder object to get the Explorer for the current folder.



Inspector Object

The Inspector object represents a window that displays a single item such as an e-mail message, task, or appointment. The Inspector object includes methods and properties that you can use to modify the window, and events that are raised when the window changes.



To get an Inspector object, do one of the following:



•Use the Inspectors property of the Application object to access all of the Inspector objects in Outlook.



•Use the ActiveInspector method of the Application object to get the Inspector that currently has focus.



•Use the GetInspector method of a specific item, such as a MailItem or AppointmentItem, to retrieve the Inspector that is associated with it.



MAPIFolder Object

The MAPIFolder object represents a folder that contains e-mail messages, contacts, tasks, and other items. Outlook provides 16 default MAPIFolder objects.



The default MAPIFolder objects are defined by the OlDefaultFolders enumeration values. For example,



Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox corresponds to the Inbox folder in Outlook.



For an example that shows how to access a default MAPIFolder and create a new MAPIFolder, see How to: Create Custom Folder Items.



MailItem Object

The MailItem object represents an e-mail message. MailItem objects are usually in folders, such as Inbox, Sent Items, and Outbox. MailItem exposes properties and methods that can be used to create and send e-mail messages.



For an example that shows how to create an e-mail message, see How to: Create an E-Mail Item.



AppointmentItem Object

The AppointmentItem object represents a meeting, a one-time appointment, or a recurring appointment or meeting in the Calendar folder. The AppointmentItem object includes methods that perform actions such as responding to or forwarding meeting requests, and properties that specify meeting details such as the location and time.



For an example that shows how to create an appointment, see How to: Create a Meeting Request.



TaskItem Object

The TaskItem object represents a task to be performed within a specified time frame. TaskItem objects are located in the Tasks folder.



To create a task, use the CreateItem method of the Application object, and pass in the value olTaskItem for the parameter.



ContactItem Object

The ContactItemobject represents a contact in the Contacts folder. ContactItem objects contain a variety of contact information for the people they represent, such as street addresses, e-mail addresses, and phone numbers.



For an example that shows how to create a new contact, see How to: Add an Entry to Outlook Contacts. For an example that shows how to search for an existing contact, see How to: Search for a Specific Contact.



Using the Outlook Object Model Documentation

--------------------------------------------------------------------------------



For information about the objects you can use in the Outlook object model, see the following sets of documentation:



•Welcome to the Outlook 2007 Primary Interop Assembly Reference



•Welcome to the Microsoft Office Outlook 2007 Developer Reference



•Welcome to the Microsoft Office Outlook 2003 VBA Language Reference



The first link provides information about the classes and interfaces in the primary interop assembly for Outlook. The other links provide information about the Outlook object model as it is exposed to Visual Basic for Applications (VBA) code. Each set of documentation has advantages and disadvantages for developers who are using Office development tools in Visual Studio.



Primary Interop Assembly Reference

This documentation describes all of the types in the Outlook primary interop assembly that you can use in Office projects:



•It describes the types in the primary interop assembly for Outlook 2007.



•It does not provide any code examples at this time.

 
 
http://msdn.microsoft.com/en-us/library/ms268893.aspx

Saturday, February 6, 2010

nth maximum value from table

select Max(empage) from Emp
where empage not in (select top 1 empage from Emp  order by EmpAge desc )

Friday, February 5, 2010

abstraction and encapsulation

abstraction

abstraction is a process. It manages complexity of objects. Abstraction identifies critical behavior of objects and eliminates the tedious details.

Example: i need to create a payroll software and software should have details of all employees within company. Employees behaviors will differ from one another. Different employees will have different hobbies, different size and shape, etc. All these behaviors are not required for creating payroll software. So we should follow a process for identifying crucial behaviors of the object. In case of payroll system, employee object should have employee id, name, band and department. All other behaviors can be eliminated. This process is called abstraction.


encapsulation

encapsulation is the mechanism by which abstraction can be implemented. Storing data and function in a single unit(class) is encapsulation. data's cannot be accessible from the outside world. function within classes can access these data. This is often referred as Information hiding.


Example: Consider a Math class. It has Add method and other member variables. Add method is exposed to the outside world. But outside world will not be knowing what is happening inside Add method. This is called information hiding.


reference:

http://oreilly.com/catalog/objectvbnet/chapter/ch01.pdf

Association, Aggregation, Composition



I have a hand, I have a car.

I have a hand - life time of hand is same as my life time. hand dies with me :) it is tightly coupled. Its composition

I have a car - my car remains even if  I die. This is aggregation.

association: is a relationship between two classes. It is the basic way of relation between two classes.

aggregation and association are more specific way of relationship between classes.

aggregation: has a relationship. one class can exist without other class
composition: one class is tightly coupled with other class. Life time of the classes will be the same.





Example2:


university has a chancellor   (association)
university have faculties  (composition)


university can exist without chancellors
university cannot exist without faculties. if faculties dispose then university will not exist.

university composed of faculties










Thursday, January 28, 2010

Why name JIT?

.net compiler convert source code into intermediate language during compilation. this is also called as Microsoft intermediate language(MSIL).
Its the job of the JIT compiler to take MSIL and convert it to native code at run time.


.net will not convert all MSIL code into native code at once. Because it is time and space consuming. Some part of the .net code never executes. So there is no need to keep this code in the memory. This is resource consuming.


So .net came up with an approach called JIT compilation, it converts MSIL to native code on demand at application runtime. So the name JUST IN TIME COMPILING

Wednesday, January 6, 2010

Measuring execution time in C#

How to measure a method's execution time without using timer?

Use DateTime and TimeSpan classes in .net framework.

public void sampleMethod()
{
DateTime starttime = DateTime.Now;
//
//......
//do code here
//......
DateTime endtime = DateTime.Now;
TimeSpan duration = endtime - starttime;
string time = duration.Hours + ":" + duration.Minutes + ":" + duration.Seconds + ":" + duration.Milliseconds;
}