Pages

Thursday, December 22, 2011

Download Multiple file Using Single HTTP Request

Unfortunately HTTP handle single request at a time. That's means Multiple files download is not possible using HTTP single request.
Multiple download can only be possible using following two ways.

1. Using java script where multiple popup can be open to download multiple files.

function callMulipleDownload() {
     fnOpen('1');
     fnOpen('2');
}
function fnOpen(f1) {
     window.open('/Home/Download/?type=' + f1);
}

This way is not recommended as many time popup is blocked on client browser.

2. Using WebClient DownloadFileAsync as follow.

private Queue _downloadUrls = new Queue();

private void downloadFile()
{
   _downloadUrls.Enqueue(Server.MapPath(@"~\Dwonload\Test-debug.apk"));
   _downloadUrls.Enqueue(Server.MapPath(@"~\Dwonload\Test1.apk"));

    DownloadFile();
}

private void DownloadFile()
{
    if (_downloadUrls.Any())
     {
       WebClient client = new WebClient();
       client.DownloadProgressChanged += client_DownloadProgressChanged;

       var url = _downloadUrls.Dequeue();
       Uri uri = new Uri(url);
       string FileName = Path.GetFileName(uri.LocalPath);

       client.DownloadFileAsync(new Uri(url), "D:\\Test4\\" + FileName);
      }
    else
      return;
    DownloadFile();
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    DownloadFile();
}

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    double bytesIn = double.Parse(e.BytesReceived.ToString());
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
    double percentage = bytesIn / totalBytes * 100;
}

Wednesday, November 23, 2011

Creational Pattern - Singleton Design Pattern

Singleton Design Pattern

Singleton Design Pattern
Singleton Design Pattern
You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.
Implementation Strategy

Even though Singleton is a comparatively simple pattern, there are various tradeoffs and options, depending upon the implementation. The following is a series of implementation strategies with a discussion of their strengths and weaknesses.
Singleton

The following implementation of the Singleton design pattern follows the solution presented in Design Patterns: Elements of Reusable Object-Oriented Software [Gamma95] but modifies it to take advantage of language features available in C#, such as properties:

    using System;
    public class Singleton
    {
         private static Singleton instance;
         private Singleton() {}
         public static Singleton Instance
           {
             get
               {
               if (instance == null)
                 {
                  instance = new Singleton();
                 }
               return instance;
               }
           }
    }
This implementation has two main advantages:

Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.

The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:

if (instance == null)

Various approaches solve this problem. One approach is to use an idiom referred to as Double-Check Locking [Lea99]. However, C# in combination with the common language runtime provides a static initialization approach, which circumvents these issues without requiring the developer to explicitly code for thread safety.


Static Initialization

One of the reasons Design Patterns [Gamma95] avoided static initialization is because the C++ specification left some ambiguity around the initialization order of static variables. Fortunately, the .NET Framework resolves this ambiguity through its handling of variable initialization:

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}


In this strategy, the instance is created the first time any member of the class is referenced. The common language runtime takes care of the variable initialization. The class is marked sealed to prevent derivation, which could add instances. For a discussion of the pros and cons of marking a class sealed, see [Sells03]. In addition, the variable is marked readonly, which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.

This implementation is similar to the preceding example, except that it relies on the common language runtime to initialize the variable. It still addresses the two basic problems that the Singleton pattern is trying to solve: global access and instantiation control. The public static property provides a global access point to the instance. Also, because the constructor is private, the Singleton class cannot be instantiated outside of the class itself; therefore, the variable refers to the only instance that can exist in the system.
Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instance property. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton.
The only potential downside of this approach is that you have less control over the mechanics of the instantiation. In the Design Patterns form, you were able to use a nondefault constructor or perform other tasks before the instantiation. Because the .NET Framework performs the initialization in this solution, you do not have these options. In most cases, static initialization is the preferred approach for implementing a Singleton in .NET.

Multithreaded Singleton
Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution. Cases do exist, however, in which you cannot rely on the common language runtime to ensure thread safety, as in the Static Initialization example. In such cases, you must use specific language capabilities to ensure that only one instance of the object is created in the presence of multiple threads. One of the more common solutions is to use the Double-Check Locking [Lea99] idiom to keep separate threads from creating new instances of the singleton at the same time.
Note: The common language runtime resolves issues related to using Double-Check Locking that are common in other environments. For more information about these issues, see "The 'Double-Checked Locking Is Broken' Declaration," on the University of Maryland, Department of Computer Science Web site, at http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.
The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created:

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.
This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient



Friday, November 4, 2011

Telerik Reporting Q2 2011

To create even simple reports you start by creating a class library to contain your report and a web, windows or Silverlight application to display the report.

Caution

It is possible to put the report definition and viewer in the same application but this route is not recommended. See this topic on best practices for more information.

  1. Select File | New | Project from the Visual Studio File menu. Select the Class Library project, give it a name and location. Click the OK button to close the dialog.

    Creating the Class Library
  2. Right-click the project context menu and select Add | New Item | Telerik Report. Enter a name for the report class and click the Add button to close the dialog. In this example we name the report class file "ProductList.cs".
  3. The Telerik Report Wizard will appear automatically to help you select data and design your report quickly. Once you have the basic report layout you can go back to edit the report, add data columns and tweak the format. Click the Next button.
  4. On the Report Choice Page of the Report Wizard, select New Report and click the Next button.
  5. On the Choose Data Source page of the Report Wizard, select Add New Data Source.
  6. The DataSource Wizard is started. Select the SqlDataSource component icon and click the OK button.
  7. On the Choose Your Data Connection page select a connection for the AdventureWorks database from the drop down list. If you do not have it in the dropdown list, click New Connection and create a connection to it. When done click the Next button.
  8. The Save the Connection String step appears, where you can save the connection string in the application configuration file if you want with the name you want. Click Next.
  9. The Configure Data Source Command step will display next.
    • Click the Query Builder button.
    • In the Add Table dialog select "Product", "ProductInventory", "ProductPhoto" and "ProductProductPhoto" from the list of tables. Note: You can hold down the control key and click each of the tables to select them all at one time.
    • Click the Add button to close the dialog.
    • On the Query Builder select the fields shown in the figure below. In the Product table select "Name", "ProductNumber" and "ReorderPoint". In ProductPhoto select the "ThumbNailPhoto" column. In the ProductInventory table select the "Quantity" column.
    • Click the OK button to close the dialog.
    • The Configure Data Source Command step would show the generated statement. Clicking the Next button would lead you to the Preview Data Source Results step, where you can preview the data. Click finish to return to the Choose Data Source page of the Report Wizard. On the next page choose Standard Report Type and click the Next button.
  10. The Design Data Layout page of the Report Wizard allows you to assign database fields to sections of the report. The Report Wizard automatically places and formats the database fields in the appropriate report sections.
    • Select from the Available Fields list on the left side of the page.
    • Select "Name", "ProductNumber", "ReorderPoint" and "Quantity".
    • After selecting each field, click the Detail button to add those columns to the detail listing of the report.
    • Click the Next button.
  11. On the Choose Report Layout page of the Report Wizard unselect the Adjust report items to fit available space checkbox. Click the Next button.
  12. On the Choose Report Style page of the Report Wizard select "Civic" from the Style Sheets list on the left side of the page. Notice the style changes in the Preview portion on the right side of the page.
  13. On the Completing the Wizard page of the Report Wizard you can review the settings for the report and click the Finish button

    The initial report layout appears in the design view in Visual Studio.

    Note

    Notice that the wizard has automatically provided:

    • Data bound fields in the detail section of the report.
    • Styled page and column titles.
    • A page footer with standard date and page number output.
  14. Rebuild the project.
  15. Click the Preview tab of the designer to view your report.

    Source link is here

Thursday, August 25, 2011

FAQ or Q&A

Q: Difference between strategy pattern and factory pattern

A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies.
In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.

Q:Difference between dependency injection and factory pattern
When using a factory your code is still actually responsible for creating objects. By DI you outsource that responsibility to another class or a framework, which is separate from your code.

Q: Returning IEnumerable vs IQueryable
The difference is that IQueryable is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable, that query will be executed in the database, if possible.
For the IEnumerable case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
In code:
IQueryable custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable will cause all of your rows to be loaded in memory.
Click Here

Q: Understanding Garbage Collection in .NET
Wonderful link
http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

Q protected internal
'protected internal' does not mean protected *and* internal - it means protected *or* internal. So a protected internal member is visible to any class inheriting the base class, whether it's in the same assembly or not. The member is also visible via an object declared of that type anywhere in the original assembly.

Q:What is internal set property in c#?
If you have a property with an internal set accessor (and public get accessor) it means that code within the assembly can read (get) and write (set) the property, but other code can only read it.
You can derive the above information by reading about the internal access modifier, the public access modifier and properties.
Also, you can read about Restricting Accessor Accessibility.


Q:Difference between flush() and commit()
Flushing the Session simply gets the data that is currently in the session synchronized with what is in the database. However, just because you have flushed, doesn't mean the data can't be rolled back.
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.Commit does flush the session, but it also ends the unit of work.

Difference between .Net 4.0 and .Net 3.5, 2.0


As we all know, ASP.NET 3.5 has introduced with the following main new features
1) AJAX integration
2) LINQ
3) Automatic Properties
4) Lambda expressions
I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0
Because of space consumption I’ll list only some of them here.

1) Client Data access:

ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods
  1. Pagemethods of script manager
    http://randomactsofcoding.blogspot.com/2007/10/introduction-to-pagemethods.html

    2) ICallbackEventHandler interface
    http://www.codeproject.com/KB/aspnet/ICallbackEventHandler.aspx

    3) XMLHttphanlder component
ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.
1) Client data controls
2) Client templates
3) Client data context
i.e we can access the data through client data view & data context objects from client side.

2) Setting Meta keyword and Meta description:

Meta keywords and description are really useful for getting listed in search engine.
ASP.NET 3.5: It has a feature to add meta as following tag
  &ltmeta name="keywords" content="These, are, my, keywords" />
&ltmeta name="description" content="This is the description of my page" />
ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.
  < %@ Page Language="C#"  CodeFile="Default.aspx.cs"   Inherits="_Default"
Keywords="Keyword1,Key2,Key3,etc"   Description="description" %>

3) Enableviewstage property for each control

ASP.NET 3.5: this property has two values “True” or “false”
ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.
Here inherit is the default value for child controls of a control.

4) Setting Client IDs

Some times ClientID property creates head ach for the programmers.
ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated
ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.
It has following values.
AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control’s ID generation is the same as its parent.

New features in ASP.net 4
http://www.simple-talk.com/dotnet/asp.net/asp.net-4.0-features/

What is MVC?

MVC Overview

Flexibility in large component based systems raise questions on how to organize a project for easy development and maintenance while protecting your data and reputation, especially from new developers and unwitting users. The answer is in using the Model, View, Control (MVC) architecture. An architecture such as MVC is a design pattern that describes a recurring problem and its solution where the solution is never exactly the same for every recurrence.

To use the Model-View-Controller MVC paradigm effectively you must understand the division of labor within the MVC triad. You also must understand how the three parts of the triad communicate with each other and with other active views and controllers; the sharing of a single mouse, keybord and display screen among several applications demands communication and cooperation. To make the best use of the MVC paradigm you need also to learn about the available subclasses of View and Controller which provide ready made starting points for your applications.

In the MVC design pattern , application flow is mediated by a central controller. The controller delegates requests to an appropriate handler. The controller is the means by which the user interacts with the web application. The controller is responsible for the input to the model. A pure GUI controller accepts input from the user and instructs the model and viewport to perform action based on that input. If an invalid input is sent to the controller from the view, the model informs the controller to direct the view that error occurred and to tell it to try again.

A web application controller can be thought of as specialised view since it has a visual aspect. It would be actually be one or more HTML forms in a web application and therefore the model can also dictate what the controller should display as input. The controller would produce HTML to allow the user input a query to the web application. The controller would add the necessary parameterisation of the individual form element so that the Servlet can observe the input. This is different from a GUI, actually back-to-front, where the controller is waiting and acting on event-driven input from mouse or graphics tablet.

The controller adapts the request to the model. The model represents, or encapsulates, an application's business logic or state. It captures not only the state of a process or system, but also how the system works. It notifies any observer when any of the data has changed. The model would execute the database query for example.

Control is then usually forwarded back through the controller to the appropriate view. The view is responsible for the output of the model. A pure GUI view attaches to a model and renders its contents to the display surface. In addition, when the model changes, the viewport automatically redraws the affected part of the image to reflect those changes. A web application view just transforms the state of the model into readable HTML. The forwarding can be implemented by a lookup in a mapping in either a database or a file. This provides a loose coupling between the model and the view, which can make an application much easier to write and maintain.

By dividing the web application into a Model, View, and Controller we can, therefore, separate the presentation from the business logic. If the MVC architecture is designed purely, then a Model can have multiple views and controllers. Also note that the model does not necessarily have to be a Java Servlet. In fact a single Java Servlet can offer multiple models. The Java Servlet is where you would place security login, user authentication and database pooling for example. After all these latter have nothing to do with the business logic of the web application or the presentation.

MVC in Java Server Pages

Now that we have a convenient architucture to separate the view, how can we leverage that? Java Server Pages (JSP) becomes more interesting because the HTML content can be separated from the Java business objects. JSP can also make use of Java Beans. The business logic could be placed inside Java Beans. If the design is architected correctly, a Web Designer could work with HTML on the JSP site without interfering with the Java developer.

The Model/View/Controller architecture also works with JSP. In fact it makes the initial implementation a little easier to write. The controller object is master Servlet. Every request goes through the controller who retrieves the necessary model object. The model may interact with other business entities such as databases or Enterprise Java Beans (EJB). The model object sends the output results back to the controller. The controller takes the results and places it inside the web browser session and forwards a redirect request to a particular Java Server Page. The JSP, in the case, is the view.

The controller has to bind a model and a view, but it could be any model and associated any view. Therein lies the flexibility and perhaps an insight to developing a very advanced dynamic controller that associates models to a view.

The prior sections have concentrated on their being one controller, one model, and one view. In practice, multiple controllers may exist - but only one controls a section of the application at a time. For example, the administrator's functions may be controlled by one controller and the main logic controlled by another. Since only one controller can be in control at a given time, they must communicate. There may also be multiple models - but the controller takes the simplified view representation and maps it to the models appropriately and also translates that response back to the view. The view never needs to know how the logic is implemented.

The case for separating presentation and logic

Decoupling data presentation and the program implementation becomes beneficial since a change to one does not affect the other. This implies that both can be developed separately from the other: a division of labor. The look and feel of the web application, the fonts, the colours and the layout can be revised without having to change any Java code. As it should be. Similarly if the business logic in the application changes, for instance to improve performance and reliability, then this should not cause change in the presentation.

A model-view-controller based web application written with only Java Servlets would give this decoupling. If the presentation changed then the Java code that generates the HTML, the presentation, in the view object only has to change.

Similarly if the business logic changed then only the model object has to change. A web application built with MVC and Java Server Pages would be slightly easier if the business logic is contained only in Java Beans. The presentation (JSP) should only access these beans through custom tag libraries. This means that the Java Beans did not have Java code that wrote HTML. Your beans would only concern themselves with the business logic and not the presentation. The JSP would get the data from the Beans and then display the presentation (the "view"). Decoupling is therefore easy. A change to the implementation only necessitates changes to the Java Beans. A change to the presentation only concern changes to the relevant Java Server Page. With Java Server Pages a web designer who knows nothing about Java can concentrate on the HTML layout, look and feel. While a Java developer can concentrate on the Java Beans and the core logic of the web application.



Source link:- http://www.jcorporate.com/expresso/doc/edg/edg_WhatIsMVC.html

Monday, August 15, 2011

NUNIT for Asp.net

NUnit is a unit-testing framework for all .Net languages.

Official website for NUNIT :- http://www.nunit.org


Installation Step:-

1) In order to include Nunit template in our Visual Studio, download Nunit template from
http://www.dalsoft.co.uk/blog/index.php/2009/11/17/nunit-templates-for-asp-net-mvc-2-0-preview-2/ and Install it.

2) Download Nunit GUI from http://www.nunit.org/index.php?p=download and install it.

Following are the step to create Nunit Test project:-

  • For adding a Nunit test for existing application, right click on the class for which Nunit test need to be create. Click on the create unit test. A pop up will be open which will give two option in dropdown for selecting template. Select Nunit template.

  • Class will be created in separate solution for Nunit test purpose

  • Class will have an attribute [TextFixture] which specify that class is used for Nunit testing purpose

  • All methods under same class will have attributes [Test] which define the particular method is for Nunit test purpose

  • In order to do testing with Nunit GUI, Nunit GUI interface need to be install.

  • After successfully installation of Nunit GUI, open project in Nunit GUI interface (File->Open Project->) by giving path to interface.

  • Nunit interface will show all the test methods on left hand side. To test the method right click on it and run, it will show green progress bar if successful and red in case of failure.


Steps to Install NUNIT



Steps to RUN Test Cases


  • Open the NUNIT tool and give the path of your testing solution (File>OpenProduct)
  • In order to test any class or method select that particular class or method then right click to run.
  • If the selected node icon change to green, code pass the test successfully and if change to red it fails.
How do I run NUnit in debug mode from Visual Studio?

When I need to debug my NUnit tests, I simply attach to the NUnit GUI application using "Debug|Attach to Process" and run the tests from the GUI. Any breakpoints in my tests (or the code they're testing) are hit. Am I misunderstanding your question, or will that work for you?

Thursday, August 4, 2011

How to remove special characters from a string in MS SQL Server (T-SQL)

-- Removes special characters from a string value.
-- All characters except 0-9, a-z and A-Z are removed and
-- the remaining characters are returned.
-- Author: Christian d'Heureuse, www.source-code.biz

create function dbo.RemoveSpecialChars (@s varchar(256))
returns varchar(256) with schemabinding
    begin 
     if @s is null 
        return null
     declare @s2 varchar(256)
     set @s2 = ''
     declare @l int
     set @l = len(@s)
     declare @p int 
     set @p = 1
     while @p <= @l
         begin
           declare @c int
           set @c = ascii(substring(@s, @p, 1))  
           if @c between 48 and 57 or
              @c between 65 and 90 or
              @c between 97 and 122    
           set @s2 = @s2 + char(@c)
           set @p = @p + 1
     end
     if len(@s2) = 0
     return null
return @s2
end

Example of how to use the function:
select dbo.RemoveSpecialChars('abc-123+ABC')
Result:
abc123ABC

Tuesday, August 2, 2011

NHibernate Queries and RestrictionsDisjunction


Source:-http://www.martinwilley.com/net/code/nhibernate/query.html

//criteria

var criteria = session.CreateCriteria<Product>()
//"Restrictions" used to be "Expression"
.Add(Restrictions.Eq("Category.Id", 2))
//ordering
.AddOrder(NHibernate.Criterion.Order.Asc("Id"))
//paging, 2nd page of 10
.SetFirstResult(10) //zero based
.SetMaxResults(10);


RestrictionsDisjunction

http://www.java2s.com/Tutorial/Java/0350__Hibernate/RestrictionsDisjunction.htm

http://stackoverflow.com/questions/4206702/hibernate-criteria-query-nested-condition

Monday, July 25, 2011

Nested Classes in C#


class Demo
{     public static void Main()    
   {
      System.Console.WriteLine("Demo");      
      OuterClass.NestedClass nc = new OuterClass.NestedClass();     
   }
}

class OuterClass
  {
      public OuterClass()
     {
        System.Console.WriteLine("OuterClass");     
      }   
      public class NestedClass 
      {   
       public NestedClass()    
       {   
         System.Console.WriteLine("NestedClass");      
        }
   }
 }

Output

Demo  NestedClass
The above program compiles and runs successfully to give the desired output. An attempt was made to create an object of NestedClass. Therefore the constructor of NestedClass got executed. There is no reason why the constructor of OuterClass should get executed.

Friday, July 15, 2011

Questions Answers

Q:Difference between Clustered and Non-Clustered Index Data Structures?

When you first create a new table, there is no index created by default. In technical terms, a table without an index is called a “heap”. As you would expect, the data we will insert into the table will be returned in the same order. A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
Clustered index is good when you know in which order you will be returning the records in most cases. You can create clustered index and after that you don’t need to use ORDER BY statement. This will be much more faster. If the order is not important for you and will not create clustered index by yourself, then primary key will be clustered index by default. There is nothing bad not to have the clustered index, it can speed up inserting rows.
Source:- http://www.allinterview.com/showanswers/8164.html

Q:Difference between Trace and Debug ?

According to Microsoft Documentation there is not much
difference between Trace and Debug Class.

Debug only works in debug mode and trace works in debug and
release both mode.


Q:Difference between Array and ArrayList?

Array is the collection of values of the same data type
>the variables in an array is called array elements
>Array is a reference type data type
>The array structure in System's Memory

Array list is a class .
>when you want to access the elements of an array through its index value location in an array,use an ArrayList.
>The use of the arraylist is an alternative to the use of th array.
>The Methods Of ArrayList class are
1)Add
2)Remove
3)Clear
4)Insert
5)TrimToSize
6)Sort
7)Reverse

Example: http://stackoverflow.com/questions/459677/c-a-strings-split-method

Question: difference between ref and out

The main difference between the two types is in the rule for definite assignment of them.
When we use the out parameter, The program calling the function need not assign a value to the out parameter before making the call to the function. The value of the out parameter has to be set by the function before returning the value.
The same is not true for the reference (ref) type parameter. For a ref type parameter, the value to the parameter has to be assigned before calling the function. If we do not assign the value before calling the function we will get a compiler error.

Another important thing to note here is that in case of ref parameter, the value passed by the caller function can be very well used by the called function. The called function does not have the compulsion to assign the value to a ref type parameter. But in case of the out parameter, the called function has to assign a value.

nhibernate-mapping-concurrency

Thursday, July 14, 2011

Creating Full Text Catalog and Full Text Search

Object Oriented Programming - Concepts

Object Oriented Programming

OOP is Nothing but Object Oriented Programming.
In OOPs concept is implimented in our real life systems.
OOPs have following features
1. Object - Instance of class
2. Class - Blue print of Object
3. encapsulation - Protecting our data
4. polymorphism - Different behaviors at diff. instances
5. abstraction - Hidding our irrelavance data
6. inheritence - one property of object is aquring to
another property of object

Simple Ex.
Please assume u standing near a car.
How to impliments our OOPs concept for this scenario ?
Simple,
car is a object b'coz it having more functions.
car is a class b'coz it contain more parts and features inside.
car is a Encapsulation B'coz it protected some unwanted parts or
functions to user car is a Polymorphism b'coz it have different
speed as display in same speedometer car is a Abstraction b'coz
it hidding more parts by coverig such as engine,disel tank car
is a Inheritance b'coz one car is a property of more people.
i mean your car is driving bu you, your friend and your relatives.

Wonderful source link for OOPS concepts:-
http://www.desy.de/gna/html/cc/Tutorial/tutorial.html


Q:what is difference between instance and object.?
instance means just creating a reference(copy) .
object :means when memory location is associated with the object( is a runtime entity of the class) by using the new operator

Q:what are the all difference between interface and abstract class?
interface is a set of abstract methods, all of which have to be overriden by the class whichever implements the interface
abstract class is a collection of data and methods which are abstact (not all of them)

Interfaces are essentially having all method prototypes no definition but Abstract class can contain method definations also.

In short Interface is a abstract class having all methods abstract.
Both abstract classes and interfaces are used when there is a difference in behaviour among the sub-types extending the abstract class or implementing the interface.

When the sub-types behaviour is totally different then you use an interface, when the sub-types behaviour is partially common and different with respect to the supertype an abstract class is used. In an abstract class the partially common behaviour is given a concrete implementation. Since there is no common behaviour between an interface and a sub-type an interface does not have an implementation for any of its behaviour.
If you create a abstract class writing the abstract keyword in the declaration part then You only can inherit the class. You can not create an instance of this abstract class but can inherit the class and with creating the instance of the derived class you can access the method of the abstract class.

If you use a virtual keyword in a method then you can override this method in the subclass if you wish..
If you create a abstract method then you must override this method in the subclass other wise it shows error in the program.


1) What is meant by Object Oriented Programming?
OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.

2) What is a Class?
Class is a template for a set of objects that share a common structure and a common behavior.

3) What is an Object?
Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

4) What is an Instance?
An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

5) What are the core OOP’s concepts?
Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP’s concepts.

6) What is meant by abstraction?
Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

7) What is meant by Encapsulation?
Encapsulation is the process of compartmentalizing the elements of an abstraction that defines the structure and behavior. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

What is meant by Inheritance?
Inheritance is a relationship among classes, wherein one class shares the structure or behavior defined in another class. This is called Single Inheritance. If a class shares the structure or behavior from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalized superclasses.
9) What is meant by Polymorphism?
Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.
10) What is an Abstract Class?
Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behavior, typically by implementing its abstract operations.

11) What is an Interface?
Interface is an outside view of a class or object which emphasizes its abstraction while hiding its structure and secrets of its behavior.

12) What is a base class?
Base class is the most generalized class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

13) What is a subclass?
Subclass is a class that inherits from one or more classes
14) What is a superclass?
superclass is a class from which another class inherits.

15) What is a constructor?
Constructor is an operation that creates an object and/or initializes its state.

16) What is a destructor?
Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM.
17) What is meant by Binding?
Binding denotes association of a name with a class.

18) What is meant by static binding?
Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

19) What is meant by Dynamic binding?
Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

20) Define Modularity?
Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

21) What is meant by Persistence?
Persistence is the property of an object by which its existence transcends space and time.

22) What is collaboration?
Collaboration is a process whereby several objects cooperate to provide some higher level behavior.

23) In Java, How to make an object completely encapsulated?
All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

24) How is polymorphism achieved in java?
Inheritance, Overloading and Overriding are used to achieve Polymorphism in java.

25) What is sealed and abstract class?

Source link:- http://msdn.microsoft.com/en-us/library/ms173150%28v=vs.80%29.aspx

Compile time polymorphism is functions and operators overloading.
Runtime time polymorphism is done using inheritance and virtual functions.
eg compile time polymorphism -- method overloding

run time time polymorphism -- method overriding

Static classes and static methods

  1. Static Class occupy memory during compile time.
  1. Static class cannot be instantiated. It calls its data members and member functions itself.
  1. Static class can have static members only as its cannot declare instance members in a static class
  1. Static class constructor get called whenever any static member is called.
  1. General Class can contains static methods but they too called its-self by class name.

Wednesday, July 13, 2011

Extension Methods in C#

using System;

namespace Foo
{
   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(2.DoubleThenAdd(3));
            Console.WriteLine(IntHelper20.DoubleThenAdd(2, 3));
            Console.ReadLine();
        }
    }

    public static class IntHelper20
    {
        public static int DoubleThenAdd(int myInt, int x)
        {
            return myInt + (2 * x);
        }
    }

    public static class IntHelper35
    {
        public static int DoubleThenAdd(this int myInt, int x)
        {
            return myInt + (2 * x);
        }
    }
}



Source: http://www.hanselman.com/blog/HowDoExtensionMethodsWorkAndWhyWasANewCLRNotRequired.aspx