Pages

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