Friday, December 26, 2014

Exception

Types of Exception

There are the following 2 types of exceptions:
  1. System Exception.
  2. Application Exception.
System Exception

An exception raised implicitly from some predefined condition is a “System Exception”. For example DivideByZeroException, FormatException, OverFlowException and NullReference Exception.

If you want to learn about system exceptions then read my article:

Finally Block

Application Exception

An exception that is raised explicitly by the programmer in the application on its own condition is an “Application Exception”.

It can also referred to as a “User Defined Exception”.

Now let's we learn how to develop our own User Defined Exception.

Use the following procedure to develop a User Defined Exception.

Step 1: Inherit a class from the Exception class.

For example : Exception

Step 2: Override the string message from the exception class.

For example:
Public override string Message
{
    get
   {
        Return “Display the error Message when Exception Occur”
   }
} 
Step 3: In the other class, if an exception occurs that throws an exception for the creation of an object of your own exception class then do something.

For example:

Throws new

Tuesday, December 2, 2014

Creation of ASP.NET Environment

Step 1: The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance, if the page is an ‘.ASPX page’, then it will be passed to ‘aspnet_isapi.dll’ for processing. 


Step 2: If this is the first request to the website, then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know, the application domain creates isolation between two web applications hosted on the same IIS. So in case there is an issue in one app domain, it does not affect the other app domain.

Step 3: The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4: Once all the core ASP.NET objects are created, ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system, then the object of the ‘global.asax’ file will be created. Please note global.asax file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests.

Step 5: The HttpApplication object is then assigned to the core ASP.NET objects to process the page.

Step 6: HttpApplication then starts processing the request by HTTP module events, handlers and page events. It fires the MHPM event for request processing.

Friday, November 28, 2014

Difference Between AreSame and AreEqual

==================
1.Assert.AreSame Method
========================
Verifies that specified object variables refer to the same objects.
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert.aresame(v=VS.100).aspx

2.Assert.AreEqual Method
============================
Verifies that specified values are equal.
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert.areequal(v=VS.100).aspx

List of test methods:
==============
1. Passed.
[TestMethod]
public void IsStringEqualTest
{
const string INPUT = "Obama";
const string EXPEXTED = "Obama"
Assert.AreEqual(EXPEXTED, INPUT);
}

2. Failed
.[TestMethod]
public void IsStringEqualNoIgnoreCaseTest
{
const string INPUT = "Obama";
const string EXPEXTED = "obama"
Assert.AreEqual(EXPEXTED, INPUT);
}

3. Passed.
[TestMethod]
public void IsStringEqualWithIgnoreCaseTest()
{
const string INPUT = "Obama";
const string EXPEXTED = "obama"
Assert.AreEqual(EXPEXTED, INPUT, true);
}

4. Failed
// Please use Assert.AreSame for only ref types.
// For value type useAssert.AreEqual !!!
[TestMethod]
public void IntegerSameTest()
{
int INPUT = 100;
int EXPEXTED = 100;
Assert.AreSame(EXPEXTED, INPUT);
}

5.Passed
.[TestMethod]
public void IntegerSameTest()
{
int INPUT = 100;
int EXPEXTED = 100;
Assert.AreEqual(EXPEXTED, INPUT);
}

Conclution:
===============================
Use Assert.AreSame for only ref types.
For value type use Assert.AreEqual only.
===============================

Monday, November 17, 2014

Mock Object vs. Stub Object


Mock Objects


A mock object is a simulation of a real object. Mock objects act just as real objects but in a controlled way. A mock object is created to test the behavior of a real object. In unit testing, mock objects are used to scrutinize the performance of real objects. Simply said, a mock object is just the imitation of a real object. Some important characteristics of mock objects are that they are lightweight, easily created, quick and deterministic, and so on.

Stub Object

A stub object is an object which implements an interface of a component. A stub can be configured to return a value as required. Stub objects provide a valid response, but it is of static nature meaning that no matter what input is passed in, we always get the same response.

Mock Object vs. Stub Object


Mock objects vary from stub objects in some ways. They are listed below:
The first distinct factor is that mock objects test themselves, i.e., they check if they are called at the proper time in the proper manner by the object being tested. Stubs generally just return stubbed data, which can be configured to change depending on how they are called.
Secondly, mock objects are generally lightweight relative to stubs with different instances set for mock objects for every test whilst stubs are often reused between tests.

Tuesday, September 30, 2014

Should we avoid string?

No overview of memory issues in C# and Unity would be complete without mentioning strings. From a memory standpoint, strings are strange because they are both heap-allocated and immutable. When you concatenate two strings (be they variables or string-constants) as in:
void Update()
{
    string string1 = "Two";
    string string2 = "One" + string1 + "Three";
}
... the runtime has to allocate at least one new string object that contains the result. In String.Concat() this is done efficiently via an external method called FastAllocateString(), but there is no way of getting around the heap allocation (40 Bytes on my system in the example above). If you need to modify or concatenate strings at runtime, use System.Text.StringBuilder.

Should you avoid closures and LINQ?

You probably know that C# offers anonymous methods and lambda expressions (which are almost but not quite identical to each other). You can create them with the delegate keyword and the => operator, respectively. They are often a handy tool, and they are hard to avoid if you want to use certain library functions (such as List<T>.Sort()) or LINQ.
Do anonymous methods and lambdas cause memory leaks? The answer is: it depends. The C# compiler actually has two very different ways of handling them. To understand the difference, consider the following small chunk of code:
int result = 0;
    
void Update()
{
    for (int i = 0; i < 100; i++)
    {
        System.Func<int, int> myFunc = (p) => p * p;
        result += myFunc(i);
    }
}
As you can see, the snippet seems to create a delegate myFunc 100 times each frame, using it each time to perform a calculation. But Mono only allocates heap memory the first time the Update() method is called (52 Bytes on my system), and doesn't do any further heap allocations in subsequent frames. What's going on? Using a code reflector (as I'll explain in the next blog post), one can see that the C# compiler simply replaces myFunc by a static field of type System.Func<intint> in the class that contains Update(). This field gets a name that is weird but also revealing: f__am$cache1 (it may differ somewhat on you system). In other words, the delegator is allocated only once and then cached.
Now let's make a minor change to the definition of the delegate:
        System.Func<int, int> myFunc = (p) => p * i++;
By substituting 'i++' for 'p', we've turned something that could be called a 'locally defined function' into a true closure. Closures are a pillar of functional programming. They tie functions to data - more precisely, to non-local variables that were defined outside of the function. In the case of myFunc, 'p' is a local variable but 'i' is non-local, as it belongs to the scope of the Update() method. The C# compiler now has to convert myFunc into something that can access, and even modify, non-local variables. It achieves this by declaring (behind the scenes) an entirely new class that represents the reference environment in whichmyFunc was created. An object of this class is allocated each time we pass through the for-loop, and we suddenly have a huge memory leak (2.6 Kb per frame on my computer).
Of course, the chief reason why closures and other language features where introduced in C# 3.0 is LINQ. If closures can lead to memory leaks, is it safe to use LINQ in your game? I may be the wrong person to ask, as I have always avoided LINQ like the plague. Parts of LINQ apparently will not work on operating systems that don't support just-in-time compilation, such as iOS. But from a memory aspect, LINQ is bad news anyway. An incredibly basic expression like the following:
int[] array = { 1, 2, 3, 6, 7, 8 };

void Update()
{
    IEnumerable<int> elements = from element in array
                    orderby element descending
                    where element > 2
                    select element;
    ...
}
... allocates 68 Bytes on my system in every frame (28 via Enumerable.OrderByDescending() and 40 viaEnumerable.Where())! The culprit here isn't even closures but extension methods to IEnumerable: LINQ has to create intermediary arrays to arrive at the final result, and doesn't have a system in place for recycling them afterwards. That said, I am not an expert on LINQ and I do not know if there are components of it that can be used safely within a real-time environment.

Should you avoid foreach loops?


A common suggestion which I've come across many times in the Unity forums and elsewhere is to avoidforeach loops and use for or while loops instead. The reasoning behind this seems sound at first sight. Foreach is really just syntactic sugar, because the compiler will preprocess code such as this:
foreach (SomeType s in someList)
    s.DoSomething();
...into something like the the following:
using (SomeType.Enumerator enumerator = this.someList.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        SomeType s = (SomeType)enumerator.Current;
        s.DoSomething();
    }
}
In other words, each use of foreach creates an enumerator object - an instance of theSystem.Collections.IEnumerator interface - behind the scenes. But does it create this object on the stack or on the heap? That turns out to be an excellent question, because both are actually possible! Most importantly, almost all of the collection types in the System.Collections.Generic namespace (List<T>, Dictionary<K, V>, LinkedList<T>, etc.) are smart enough to return a struct from from their implementation of GetEnumerator()). This includes the version of the collections that ships with Mono 2.6.5 (as used by Unity).
[EDIT] Matthew Hanlon pointed my attention to an unfortunate (yet also very interesting) discrepancy between Microsoft's current C# compiler and the older Mono/C# compiler that Unity uses 'under the hood' to compile your scripts on-the-fly. You probably know that you can use Microsoft Visual Studio to develop and even compile Unity/Mono compatible code. You just drop the respective assembly into the 'Assets' folder. All code is then executed in a Unity/Mono runtime environment. However, results can still differ depending on who compiled the code! foreach loops are just such a case, as I've only now figured out. While both compilers recognize whether a collection's GetEnumerator() returns a struct or a class, the Mono/C# has a bug which 'boxes' (see below, on boxing) a struct-enumerator to create a reference type.
So should you avoid foreach loops?
  • Don't use them in C# code that you allow Unity to compile for you.
  • Do use them to iterate over the standard generic collections (List<T> etc.) in C# code that you compile yourself with a recent compiler. Visual Studio as well as the free .NET Framework SDK are fine, and I assume (but haven't verified) that the one that comes with the latest versions of Mono and MonoDevelop is fine as well.
What about foreach-loops to iterate over other kinds of collections when you use an external compiler? Unfortunately, there's is no general answer. Use the techniques discussed in the second blog post to find out for yourself which collections are safe for foreach[/EDIT]

Friday, August 1, 2014

MVC



What in the world is this MVC I speak of? MVC stands for Model-View-Controller, and it’s an idea behind application development to separate the 3 main pieces of the application into their own isolated environments.

What does this mean exactly? There are three major components of any given application, be it a desktop application, mobile application, or a web-based application. These three components are the Controller, the View, and the Model. Now let’s get a more concrete idea of what each of these three components actually does within an application.

The Controller is essentially the traffic cop of the application, directing traffic to where it needs to go, figuring out which view it needs to load up, and interacting with the appropriate models. For example, when you go to login to your email on a website, the controller is going to tell the application that it needs to load the login form view. Upon attempting to login, the controller will load the model that handles logins, which will check if the username and password match what exists within the system. If successful, the controller will then pass you off to the first page you enter when logging in, such as your inbox. Once there, the inbox controller will further handle that request.

In a web-based application, the view is exactly what it sounds like: the visible interface that the user interacts with, displaying buttons, forms, and information. Generally speaking, the controller calls up the view after interacting with the model, which is what gathers the information to display in the particular view.

The Model is where data from the controller and sometimes the view is actually passed into, out of, and manipulated. Keeping in mind our last example of logging into your web-based email, the model will take the username and password given to it from the controller, check that data against the stored information in the database, and then render the view accordingly. For example, if you enter in an incorrect password, the model will tell the controller that it was incorrect, and the controller will tell the view to display an error message saying something to the effect of “Your username or password is incorrect.”

Now that you know the basic concepts of the MVC pattern, you’re probably wondering what makes it so special? Essentially, it allows for the programmer to isolate these very separate pieces of code into their own domain, which makes code maintenance and debugging much simpler than if all of these items were chunked into one massive piece. If I have a problem with an application not displaying an error message when it should, I have a very specific set of locations to look to see why this is not happening. First I would look at the “Login Controller” to see if it is telling the view to display the error. If that’s fine, I would look at the “Login Model” to see if it is passing the data back to the controller to tell it that it needs to show an error. Then if that’s correct, the last place it could be happening would be in the “Login View.”

Using this development pattern allows for very easy maintenance, as well as independent development of pieces of the same system by different programmers, which makes for quick turnover of applications all while still maintaining a very high standard of quality for the application.

Ref : http://www.tmprod.com/blog/2012/what-is-mvc-architecture-in-a-web-based-application/

Friday, July 18, 2014

Improve Performance in SQL Server

Marking a column as a primary key will automatically create a unique index on the column.


A term that is often used is "SARGable". This basically refers to a condition in a WHERE clause that is able to use an index if one exists.


Examples of SARGable conditions are: A = x, B LIKE 'AB%', C IN (x, y, z). In each of these the optimizer is able to use an index. Examples of Non-SARGable conditions are: A <> x, B LIKE '%AB', C NOT IN (x, y, z).


If you think about each of these it should be obvious why an index cannot be used. To explain why B LIKE '%AB' is bad, I like to use the analogy of a large dictionary. If you know what letters the word starts with you can find it very quickly. If you only know what letters it ends with you have no option but to read the entire dictionary and check every single word.


You should also avoid using NOT in your WHERE clauses. NOT IN, NOT LIKE and IS NOT NULL perform a scan for exactly the reasons given above. The exception may be NOT EXISTS, which can perform very well for many queries.


One very common mistake is to use functions in such a way that a scan is performed. A condition of the form WHERE Fn(A) = x will not use an index on A, as the function has to be applied to this column in every row before it can be compared with x.


This needs an example to explain properly: suppose you want to match rows added in the last 5 days. I often see this written as follows:


This should be rewritten as follows:


There may be situations in which use of a function is unavoidable. In this case you can add a computed column that uses the function, add an index to the computed column, and refer to the computed column directly in the query.

Another common mistake is due to the way indexes are used in an OR condition. This is described in OR Condition Performance

Friday, July 11, 2014

Lambda Expressions

Lambda expressions are simply functions/methods.

They have a different syntax, primarily so that they can be written in expression context (more on this shortly) instead of as a member of a class.  However, that is all they are.  For instance, the following lambda expression:
c => c + 1
is a function that takes one argument, c, and returns the value c + 1.

Friday, July 4, 2014

Difference Between WebFarm and Web Garden

Web Farm: It is a multi-server scenario and we can keep servers separately. If the load on one server is in excess then the other servers step in to bear the strength. Server Load is based on various following models.
1. Round Robin. (All servers share load equally)
2. Network Load Balancer (economical)
3. HLB (expensive but can scale up to 8192 servers)
4. Hybrid (2 and 3).
5. CLB (Component load balancer).
We can implement web farms in .NET. Open web.config file and add mode options.
i) if mode=inproc (non web farm but fast when you have very few customers).
ii) if mode=StateServer (for web farm)
iii) if mode=SqlServer (for web farm)
Whether to use option (ii) or (iii) depends on situation. StateServer is faster but SqlServer is more reliable and used for critical applications.


Web farms means many Application of Multiple server on different location on the world. for example: www.yahoo.in, www.yahoo.uk



Web Garden:
WebGarden is the scenario in which a single physical machine is used for multiple worker processes running simultaneously. Each worker process is responsible for handling all kinds of requests, responses, session data, cache data, etc. and all the ASP.NET functionality inside IIS runs under the scope of the worker process. By default, every application pool contains a single worker process. A WebSite containing multiple worker processes is called a WebGarden.
Put simply – if you increase the number of worker processes for a given ApplicationPool you get a WebGarden.


Generally it is a multi-processor setup i.e. in case of a web garden we have a one server having more than one processor. You can use web gardens in .Net as: Open web.config file and add webGarden = true in process model tag.


If you enable Web-garden mode by setting the webGarden attribute to true in the processModel element of the application's Web.config file, do not use InProc session state mode. If you do, data loss can occur if different requests for the same session are served by different worker processes.


More than one worker process is a "web garden." In-process session state will not work correctly. You'll need to use either a single worker process for your web app, or use a session state server, or SQL Server for session state.


if we configure an ASP.Net application pool with more than one worker process (web garden), they do not share session object, application object or ASP.net intrinsic cache object. If I want all these processes to share one single cache, is it possible to configure at all some way or the other?


Web Gardens means many application of single server.
for example www.mail.yahoo.com, www.chat.yahoo.com

Friday, June 27, 2014

Difference between Dispose and Finalizer

The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).
The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.
The standard practice is to implement IDisposable and Dispose so that you can use your object in a using statement. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.

Trick to square a number.

If number is divisible by 5. This is very easy to get the square of such number.


Suppose it is a two digit number:
xy = (x* (x+1)) (y*y)


Example:
15 = 1*(1+1)    (5*5) =  (1*2) 25 =  225
25 = 2*(2+1)    (5*5) =  (2*3) 25 =  625
35 = 3*(3+1)    (5*5) =  (3*4) 25 = 4225
45 = 4*(4+1)    (5*5) =  (4*5) 25 = 2025
125 = 12*13     (5*5) = 15625


Trick to get the Square of other numbers that are below than hundred
xy =   x*(xy+y)+Carry + (y*y)


Example
12 = (1*(12+2) +0) (2*2) =( (1*14)+0)  4 = 144
13 = (13+3) (3*3) = 169
14 = (14+4) (16)  = 196 (Carry will be 1 that will add in 18)
15 = (15+5) (25) = 225
21 = 2*(21+1) (1)= 441
22 = 2*(22+2) (2*2) = 484
26 = 2*(26+6) (6*6) =  676
32 = 3*(32+2) (2*2) =  1024

Friday, June 20, 2014

Interview.

1) What are table object?
2) What global variable and temporary variables in SQL server?
3) If two tables related with priamary key and foreign key  and we want to update/insert some column values from primary table that write the query.
4) If we have a same method in child class and base class than.


Chid objChild = new Base();
objChild.Display();


What will be the output?

Ans : Base class method would be called.

Friday, June 13, 2014

Remoting

  1. Describe in detail Basic of SAO architecture of Remoting?
  2. Remoting has at least three sections :
    • Common Interface which will be shared between them.
    • Server.
    • Client.
  3. Here is an explanation of the process:
    • First important section is the common interface between Server and Client. For sample project interface
    • is very simple with only two methods : SetValue and GetValue.
    • Public Interface InterFaceRemoting
    • Sub SetValue(ByVal value As String)
    • Function GetValue() As String
    • End Interface
    • Second important section is the server. In this sample server is using HTTP channel and the server object is singleton.
    • Imports System
    • Imports System.Runtime.Remoting
    • Imports System.Runtime.Remoting.Channels.Http
    • Imports System.Runtime.Remoting.Channels
    • Imports InterFaceRemoting
    • Public Class RemotingServer Inherits MarshalByRefObject
    • Implements InterFaceRemoting.InterFaceRemoting
    • Private strData As String
    • Public Function GetValue() As String Implements
    • InterFaceRemoting.InterFaceRemoting.GetValue
    • Return strData
    • End Function
    • Sub New()
    • strData = "testing.."
    • End Sub
    • Public Sub SetValue(ByVal value As String) Implements
    • InterFaceRemoting.InterFaceRemoting.SetValue
    • strData = value
    • End Sub
    • End Class
    • Module ModuleRemotingStartUp
    • Sub Main()
    • Dim objHttpChannel As HttpChannel
    • Console.WriteLine("Server Started...")
    • objHttpChannel = New HttpChannel(1234)
    • ChannelServices.RegisterChannel(objHttpChannel)
    • RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
    • "RemoteObject", WellKnownObjectMode.Singleton)
    • Console.WriteLine("Server registered and listening waiting for clients...")
    • Console.ReadLine()
    • End Sub
    • End Module
    • In the code above, Channel object is created and registered. Server then hosts the object so that client can connect to it. This is the time when we specify what mode the server object will be created i.e. Singleton or SingleCall. This is done by the following below given code. Note in sample we are hosting the server object in singleton mode that means that the same object
    • will be shared between all clients. Also note the server object is implementing "InterFaceRemoting" and inheriting from "MarshalByRefObject".
    • RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
    • "RemoteObject", WellKnownObjectMode.Singleton)
    • In the last section the client will connect to this hosted remoting object.
    • Imports System
    • Imports System.Runtime.Remoting
    • Imports System.Runtime.Remoting.Channels.Http
    • Imports System.Runtime.Remoting.Channels
    • Imports InterFaceRemoting
    • Module ModuleStartClient
    • Sub Main()
    • Dim objHttpChannel As New HttpChannel
    • Dim objRemoting As InterFaceRemoting.InterFaceRemoting
    • ChannelServices.RegisterChannel(objHttpChannel)
    • objRemoting =
    • CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),
    • "http://localhost:1234/RemoteObject"),
    • InterFaceRemoting.InterFaceRemoting)
    • Console.WriteLine("Referenced the main object.... Now displaying Data")
    • Console.WriteLine("Value on server :- " & objRemoting.GetValue.ToString())
    • Console.WriteLine("Press enter to Terminate")
    • Console.ReadLine()
    • End Sub
    • End Module
    • Finally you need to run server and then client.

Followers

Link