Monday, December 19, 2011

Differnce Between Actionresult and VewResult in ASP.NET MVC

ActionResult is an abstract class means ViewResult derives from ActionResult. You declare it this way so you can take advantage of polymorphism and return different types in the same method.

Eg:
public ActionResult Foo()
{
   if (someCondition)
     return View(); // returns ViewResult
   else
     return Json(); // returns JsonResult
}
I above example the return type of Foo() is "ActionResult" so now i am not bound to return a specific type of value, i can return a View/Json/PartialView/RedirectResult. If i would have used "ViewResult" then i would be able to return "View" only. So ActionResult provides us facility to take advantage of polimorphism in Type of return.

ActionResult have several subtypes:

a) ViewResult - Renders a specifed view to the response stream

b) PartialViewResult - Renders a specifed partial view to the response stream

c) EmptyResult - An empty response is returned

d) RedirectResult - Performs an HTTP redirection to a specifed URL

e) RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

f) JsonResult - Serializes a given ViewData object to JSON format

g) JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

h) ContentResult - Writes content to the response stream without requiring a view

i) FileContentResult - Returns a fle to the client

j) FileStreamResult - Returns a fle to the client, which is provided by a Stream

k) FilePathResult - Returns a fle to the client

Compiled By: Rajesh Rolen

Read More

Wednesday, November 23, 2011

Principals Of Design

• Use models to design systems
• Use hierarchical, top-down design
• Work on high-risk entities first
• Prioritize
• Control the level of interacting entities
• Design the interfaces
• Produce satisficing designs
• Do not optimize early
• Maintain an updated model of the system
• Develop stable intermediates
• Use evolutionary development
• Understand your enterprise
• State what not how (polymorphism)
• List functional requirements in the use cases
• Allocate each function to only one component
• Do not allow undocumented functions
• Provide observable states
• Rapid prototyping
• Develop iteratively and test immediately
• Create modules (al la Unix)
• Create libraries of reusable entities
• Use open standards
• Identify things that are likely to change
• Write extension points
• Group data and behavior
• Use data hiding
• Write a glossary of relevant terms
• Envelope requirements
• Create design margins
• Design for testability
• Design for evolvability
• Build in preparation for buying
• Do a sensitivity analysis
• Create a new design process
• Search for unintended consequences
• Change the behavior of people
Read More

Tuesday, November 8, 2011

New vision, new version, get ready!

Check out the new look and feel of the Experts Exchange site, as far as 15 years ago you could not dream of a full community of experts at your disposal...

So, get ready to the new and improved Experts Exchange.

Get Answers of you every Tech question and make you life easy.


Large Experts Exchange VIP Badge
Read More

Tuesday, October 25, 2011

Advantages of SQL Server 2008 over SQL Server 2005

Transparent Data Encryption. The ability to encrypt an entire database.
Backup Encryption. Executed at backup time to prevent tampering.
External Key Management. Storing Keys separate from the data.
Auditing. Monitoring of data access.
Data Compression. Fact Table size reduction and improved performance.
Resource Governor. Restrict users or groups from consuming high levels or resources.
Hot Plug CPU. Add CPUs on the fly.
Performance Studio. Collection of performance monitoring tools.
Installation improvements. Disk images and service pack uninstall options.
Dynamic Development. New ADO and Visual Studio options as well as Dot Net 3.
Entity Data Services. Line Of Business (LOB) framework and Entity Query Language (eSQL)
LINQ. Development query language for access multiple types of data such as SQL and XML.
Data Synchronizing. Development of frequently disconnected applications.
Large UDT. No size restriction on UDT.
Dates and Times. New data types: Date, Time, Date Time Offset.
File Stream. New data type VarBinary(Max) FileStream for managing binary data.
Table Value Parameters. The ability to pass an entire table to a stored procedure.
Spatial Data. Data type for storing Latitude, Longitude, and GPS entries.
Full Text Search. Native Indexes, thesaurus as metadata, and backup ability.
SQL Server Integration Service. Improved multiprocessor support and faster lookups.
MERGE. TSQL command combining Insert, Update, and Delete.
SQL Server Analysis Server. Stack improvements, faster block computations.
SQL Server Reporting Server. Improved memory management and better rendering.
Microsoft Office 2007. Use OFFICE as an SSRS template. SSRS to WORD.
SQL 2000 Support Ends. Mainstream Support for SQL 2000 is coming to an end.
Read More

Sunday, October 16, 2011

Design Patterns which are used in .NET Framework base class library

As we know that .net is an OOPs based language so we can easily implement design patterns in our projects but some times it comes to mind that, which all design patters microsoft .NET Base Class Library is using internally.
NOTE: This question also popular in interviews.
Lets walk through few Design patterns used in .NET BCL:

Observer Pattern:
This observer design pattern is used for delegates and events.

Iterator Pattern:
Iterator design pattern used in foreach in C# and For Each in Visual Basic .NET

Decorator Pattern:
System.IO.Stream :Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction.

CryptoStream :System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream.

Adapter Pattern:
By allowing managed classes and COM components to interact despite their interface differences, RCWs are an example of the Adapter pattern. The Adapter pattern lets you adapt one interface to another. COM doesn't understand the System.String class, so the RCW adapts it to something that it can understand. Even though you can't change how a legacy component works, you can still interact with it. Adapters are frequently used like this.

Factory Pattern:
System.Convert: System.Convert class contains a host of static methods that work like factory design pattern.

System.Net.WebRequest:
This class is used to request and receive a response from a resource on the Internet.FTP, HTTP, and file system requests are supported by default. To create a request, call the Create method and pass in a URI. The Create method itself determines the appropriate protocol for the request and returns the appropriate subclass of WebRequest: HttpWebRequest, FtpWebRequest, or FileWebRequest. The caller doesn't need to know the specifics of each protocol, only how to invoke the factory and work with the WebRequest that gets returned. If the URI changes from an HTTP address to an FTP address, the code won't have to change at all.

Strategy Pattern:
Both Array and ArrayList provide the capability to sort the objects contained in the collection via the Sort method. Strategy Design Pattern is used with Array and Arraylist to sort them using different strategy without changing any client code using IComparable interface

Composite Pattern in ASP.NET:
ASP.NET has lots of controls. A control may be a simple single item like a Literal, or it could be composed of a complex collection of child controls, like a DataGrid is. Regardless, calling the Render method on either of these controls should still perform the same intuitive function.

Because the domain of controls is so diverse, there are several intermediate derived classes like WebControl and BaseDataList that serve as base classes for other controls. Though these classes expose additional properties and methods, they still retain the child management functions and core operations inherited from Control. In fact, the use of the Composite pattern helps to hide their complexity, if desired. Regardless of whether a control is a Literal or a DataGrid, the use of Composite means you can just call Render and everything will sort itself out.

Template Method Pattern:
custom controls are example of Template Method Pattern.


Reference: http://msdn.microsoft.com/en-us/magazine/cc188707.aspx

Compiled By: Rajesh Rolen

Read More

Tuesday, September 20, 2011

Features of .net framework 4.5

The .Net framework 4.5 has lots of new features and improvements in existing sections like:

.NET for Metro style apps
-The .NET APIs for Metro style apps provide a set of managed types that you can use to create Metro style apps for Windows using C# or Visual Basic.

Core New Features and Improvements
-features and improvements added to the common language runtime and to .NET Framework classes
-Managed Extensibility Framework (MEF)
-Asynchronous File Operations

Web
- New in ASP.NET 4.5

Networking
-Improved internationalization and IPv6 support.

-RFC-compliant URI support.
See also

-Support for Internationalized Domain Name (IDN) parsing.
What is Internationalize Domain Name?

-Support for Email Address Internationalization (EAI).

See also

-Windows Presentation Foundation (WPF)


-Windows Communication Foundation (WCF)
See Also

-Windows Workflow Foundation (WF)

Compiled By: Rajesh Rolen

Read More

.NET Framework 4.5: Windows Communication Foundation 4.5

Simplification of generated configuration files.

Support for contract-first development.

Ability to configure ASP.NET compatibility mode more easily.

Changes in default transport property values to reduce the likelihood that you will have to set them.

Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.

Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.

New asynchronous streaming support.

New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).

Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.

Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.

Support for configuring services in code.

XML Editor tooltips.

ChannelFactory caching support.

Binary encoder compression support.
Read More

.NET Framework 4.5:Windows Presentation Foundation (WPF)

The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.

The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.

New features for the VirtualizingPanel and Dispatcher classes.

Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.

Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface, and retrieval of data binding information from a binding expression.

Repositioning of data as the values change (live shaping).

Better integration between WPF and Win32 user interface components.

Ability to check whether the data context for an item container is disconnected.

Ability to set the amount of time that should elapse between property changes and data source updates.

Improved support for implementing weak event patterns. Also, events can now accept markup extensions.
Read More

New features in ASP.NET 4.5

Support for new HTML5 form types.

Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.

Support for unobtrusive JavaScript in client-side validation scripts.

Improved handling of client script through bundling and minification for improved page performance.

Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.

Support for WebSockets protocol.

Support for reading and writing HTTP requests and responses asynchronously.

Support for asynchronous modules and handlers.

Support for content distribution network (CDN) fallback in the ScriptManager control.

Read More
Read More

.NET Framework 4.5: Asynchronous File Operations

New asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations. To use this new model, use the asynchronous methods in the I/O classes.
Example of Asynchronous File Operation
Read More

Managed Extensibility Framework (MEF)

The Managed Extensibility Framework (MEF) provides the following new features:

Support for generic types.

Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.

Multiple scopes.
Read More

.NET Framework 4.5: Features and improvements added to the common language runtime and to .NET Framework classes

Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.

Ability to define the culture for an application domain.

Console support for Unicode (UTF-16) encoding.

Support for versioning of cultural string ordering and comparison data.

Better performance when retrieving resources.

Zip compression improvements to reduce the size of a compressed file.

Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.
Read More

What are Metro style apps

Metro style apps are full screen apps tailored to your users' needs, tailored to the device they run on, tailored for touch interaction, and tailored to the Windows user interface. Windows helps you interact with your users, and your users interact with your app.
ReadMore
Read More

Saturday, September 10, 2011

How to Protect email address from spam bots/harvesters

What is spam?

Spam is flooding the Internet with many copies of the same message, in an attempt to force the message on people who would not otherwise choose to receive it. Most spam is commercial advertising, often for dubious products, get-rich-quick schemes, or quasi-legal services. Spam costs the sender very little to send -- most of the costs are paid for by the recipient or the carriers rather than by the sender.

Email spam:

Email spam, also known as junk email or unsolicited bulk email (UBE), is a subset of spam that involves nearly identical messages sent to numerous recipients by email. Definitions of spam usually include the aspects that email is unsolicited and sent in bulk.

E-mail address harvesting:

E-mail harvesting is the process of obtaining lists of e-mail addresses using various methods for use in bulk e-mail or other purposes usually grouped as spam.

There are lots of tricks available which can be used to protect email address from spam bots like:

Using CSS Trick:Using a css, you can completely hide your email address from spam harvesters. The drawback to this approach is that it will only work on sites that read left-to-right as it uses CSS to reverse the direction of text.
span.reverse {
  unicode-bidi: bidi-override;
  direction: rtl;
}
At the point that you are ready to present the email address, code it in your HTML, but just key it in backwards. For example:
moc.liamg@hsejaR
The CSS above will then override the reading direction and present the text to the user in the correct order.

This will work but not for long, cause the pattern still gives the spammer crawlers hints that it's absolutely a reversed email.



HTML Escape Characters: Using javascript we can encrypt the email
function XOR_Crypt(EmailAddress)
{
    Result = new String();
    for (var i = 0; i < EmailAddress.length; i++)
    {
     Result += String.fromCharCode(EmailAddress.charCodeAt(i) ^ 128);
    }
    document.write(Result);
}
Using reCAPTHA: Using reCAPTHA its very easy and better approach then using javascript encryption or using CSS reverse strategy. http://www.google.com/recaptcha/mailhide/
Writing email address like: Contact me
Enkoder: Enkoder is also an option. http://hivelogic.com/enkoder/
Contact Page: its always better, instead of showing email address to contract you, you should provide an form where user can enter his details and send you email.
My Opinion: In my opinion don't bother about spam bots. Normally in our inbox we gets several thousand spams every day. Our spam filter let maybe 1 or 2 a day through. As spam filters are really good, why make it difficult for legitimate people to contact you. So Just don't worry be happy :)

Compiled By: Rajesh Rolen

Read More

Wednesday, September 7, 2011

ASP.NET Interview Questions Page-7

Read More

ASP.NET Interview Questions Page-6

Read More

ASP.NET Interview Questions Page-5

Read More

ASP.NET Interview Questions Page-4

Read More

ASP.NET Interview Questions Page-3

Read More

ASP.NET Interview Questions Page-2

Read More

ASP.NET Interview Questions

Read More

Sunday, September 4, 2011

Constants in .NET


There are two types of constants available in c#:
Compile-time constants and runtime constants. They have different behaviors and
using wrong one will cost you performance or correctness.


But Runtime constants are always preferable over
compile-time constants. Though the compile-time constants are slightly faster
but they are not flexible with compare to runtime constants.


The compile-time constants are preferable when performance
is really required and you don’t have any requirements to change the value of
that constant.


Compile-time constant are declared using “const” keyword:


Eg: public const int a=10;


Run-time constants are declared using “readonly” keyword:


Eg: public readonly int a=10;



compile-time – “Const”


run-time – “readonly”


compile-time
constant
can be declared at class level


Run-time
constant
can be declared at class level


compile-time
constant
can be declared at method level


Run-time
constant
Cannot be declared at method level


A compile-time constant is replaced with the value of that
constant in object code.

Eg:

public const int a=10;

int b=20;

if(b==a)

compiles to the same IL as if you had written this:

if(b==10)// means instead of comparing with variable ‘a’ it
will write its value in compiler-generated IL. Which increase speed but for
various situations its not preferable.


Runtime constants are evaluated at runtime. The IL generated
when you reference a read-only constant references the “
readonly “
variable,
not the value.

Eg:

public const int a=10;

int b=20;

if(b==a)

compiles to the same IL as if you had written this:

if(b==a)// so instead of placing its value as like it do with
“const”,  its place variable for “readonly” variables in compiler-generated
IL.


compile-time constant cannot initialize using the new operator,
even when the type being initialized is a value type.


runtime constants can be of any type, They

must
be initialized using constructor, or using initializer.


Compile-time constants can be used only for primitive types
(built-in integral and floating-point types), enums, or strings.

 

These are the only types that enable you to assign meaningful
constant values in initializers.

 

As we know that for “const” type in compiler-generated IL the
variables get replaces with vales so,these primitive types are the only ones
that can be replaced with literal values. in the compiler-generated IL.


runtime
constants can be of any type.

Read-only values are also constants, in that they cannot be
modified after the constructor

has executed. But read-only values are different in that they
are assigned at runtime.


Compile-time
constants are much more better in performance but less flexible with compare
to run-time constants.


Run-time constants are much more flexible but its performance
is slower with compare to compile-time constants.


Compile-time constants are, by definition,

static
constants.


readonly values can be used for instance constants,
storing different values

for each instance of a class type.


Every
time application assembly need to be rebuilt whenever library assembly which
contains constant gets its constant value changed ( as the compiler-generated
IL contains values of compile-time constants instead of referring variable)


No need to rebuild Application assembly which is referring a
library assembly which contains run-time constants whose value is changed and
its assembly is rebuilt.


 


The final advantage of using const over readonly is
performance: Known constant values can generate slightly more efficient code
than the variable accesses necessary for readonly values.
However, any gains are slight and should be weighed against the decreased
flexibility. Be sure to profile performance differences before giving up the
flexibility.



Compiled By: Rajesh Rolen

Read More

Wednesday, August 24, 2011

Row/Item Count in Repeater



Using below code you can get Repeater's Row/Item Count:

in below code "Container.ItemIndex" is used to get current row number and
"(string[])rpttags.DataSource).Length" is used to get total row/item count.
in above line my datasource for repeater was a string array so i used string[] as datasourcetype and used length to get its count in same way you can get for all other types

eg:-
<%# (Container.ItemIndex < ((yourDataSourceDataType)rpttags.DataSource).Length  - 1?",":"") %>

Compiled By: Rajesh Rolen

Read More

Monday, August 22, 2011

HTML Encode/Decode using JQuery

using below code you can encode/decode html tags using jquery

function htmlEncode(value){
  return $('
').text(value).html(); } function htmlDecode(value){ return $('
').html(value).text(); }

Compiled By: Rajesh Rolen

Read More

Friday, August 12, 2011

SQL Server parameter sniffing



While working on a project which has huge database interaction and i was using stored procedure to get good performance. But even though i was using stored procedure the performance was not so good all the time. I mean it was not consistent, for few queries on same stored procedure it was so good and some times it was going worst.

I have done lots of google for it and finally i got the solution.. The easiest solution which you can apply to any existing stored procedure without doing any major changes in it..

Its mostly helpful in situation where you have a stored procedure and the amount of data returned is varying wildly depending on what parameters are passed in.

Some time you will see that the performance of stored procedure change dramatically depending on how much data is being returned.

Then you could be a victim of SQL Server Parameter sniffing.
[YOU ARE AT RIGHT PLACE TO GET SOLUTION]


Normally we writes procedure like:
CREATE PROCEDURE GetUserData
   @UserName nvarchar(20)
    AS
    BEGIN
        SELECT DisplayName, FirstName, LastName 
        FROM dbo.User
        WHERE UserName = @UserName
    END

Now to get good speed constantly, just do some minor changes in it:
CREATE PROCEDURE GetUserData
        @UserName nvarchar(20)
    AS
    BEGIN
        DECLARE @myUserName nvarchar(20)
         SET @myUserName = @UserName
     
        SELECT DisplayName, FirstName, LastName 
        FROM dbo.User
       WHERE UserName = @myUserName
   END

I have done some minor changes in it.
that is, i have just declared local variables and assigned the values of parameters in it and then used those variables in queries instead of using parameters directly.

Now You must be thinking that how come it affect the performance.
Let me explain:

Here is the Microsoft definition:

“Parameter sniffing” refers to a process whereby SQL Server’s execution environment “sniffs” the current parameter values during compilation or recompilation, and passes it along to the query optimizer so that they can be used to generate potentially faster query execution plans. The word “current” refers to the parameter values present in the statement call that caused a compilation or a recompilation.


So For some strange reason, when you pass the parameters (@UserName in this case) to a local variable (@myUserName) SQL Server will no longer use the value of the parameter (@UserName) to influence the query plan and you will get the performance constantly. :)

Compiled By: Rajesh Rolen

Read More

Thursday, August 11, 2011

How to Query for single value for multiple column in fulltext search




Search a value in multiple column using fulltext search:
select * from productmaster where FREETEXT((productName,productDetails),'Search this text')

Compiled By: Rajesh Rolen

Read More

show multiple jquery scroller in single page



To show multiple jquery scroller in single page just add an extra div on outer side or every scroller. means place every scroller in seperate div and its done..


Compiled By: Rajesh Rolen

Read More

Wednesday, August 10, 2011

What is difference between Dictionary and Hashtable



The fact is that dictionary is a hashtable.
The main difference is that dictionary is a hashtable where as hashtable is not.
That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out.
its almost similar what difference between array list and generic list.

Compiled By: Rajesh Rolen

Read More

When caching is enabled for the XmlDataSource that is not in the page's control tree it requires a UniqueID that is unique throughout the application.

XmlDataSource class internally calls a private method called CreateCacheKey. Now, if you are using XmlDataSource without an ID, after upgrading the solution to ASP.NET 3.5, this might throw an exception - "When caching is enabled for the XmlDataSource that is not in the pages control tree it requires a UniqueID that is unique throughout the application." This is due to the absence of the UniqueID (which is read-only, but my experiment shows that setting the ID handles the same), which is used as part of the caching key, without which all instances would try to use same caching key. Setting a distinct ID solves this problem and the problem goes away

eg:


XmlDataSource XmlSrc = new XmlDataSource();
XmlSrc.ID = "someid";



Compiled By: Rajesh Rolen

Read More

Tuesday, August 9, 2011

Query Xml File with Namespace using XPath



We all know how to get value from xml file in .net but we face issue when there is a namespace with that xml file.

When a xml file contains a namespace then you will have to do some extra efforts to retrieve its value.

Lets say my xml is like:



Videos
119150

207463
somepath
sometitle
somelink
...

http://someurl/standard-and-poors-india-connection/207463

Tue, 09 Aug 2011 6:26:48 IST
1312894608




Now i wants to access value of "url" attribute of "media:thumbnail" tag, so to get it you will have to do :

Dim path As String = "http://api.flickr.com/services/feeds/photoset.gne?set=72157604607980332&nsid=51374889@N00&lang=en-us&format=rss_200_enc"
        Dim xmldoc As New XmlDocument()
        xmldoc.Load(path)
        Dim xnm As New XmlNamespaceManager(xmldoc.NameTable)
        xnm.AddNamespace("media", "http://search.yahoo.com/mrss/")
        Dim nList As XmlNodeList = xmldoc.SelectNodes("//item/media:thumbnail/@url", xnm)

        For Each xNode As XmlNode In nList
            ListBox1.Items.Add(xNode.InnerText)
            TextBox1.Text += TextBox1.Text + xNode.InnerText + vbNewLine
        Next


Now comes to original problem for which i have done google for 2-3 hours and then finally i got the answer.

Problem: I have got a repeater and i wants to show this xml values in it. now 1 option is that you can convert it to a datatable and easily use it.. but it will be extra process to you application. so now we wants to show xml directly to the repeater... to do so see below code:

In code behind file:
XmlDataSource xds = new XmlDataSource();
xds.XPath = "rss/channel/item";
xds.DataFile = sourceXml;// you can write xml path here.
myrpt.DataSource = xds;
myrpt.DataBind();

Now in .aspx file write below code:
< asp:Repeater ID="myrpt" runat="server" >
                < ItemTemplate >
                    < li >
                        < div class="multi_div" >
                            < img src='< %#XPath("*[local-name()='thumbnail' and namespace-uri()='http://search.yahoo.com/mrss/']/@url")% >' class="imgbdr" / >< div class="multi_blkstrip" >
                                < p class="float_l" >
                                    < img src="images/video_icon.gif" / >< /p >
                                < p class="float_r" >
                                    < %#XPath("title")% >< /p >
                            < /div >
                        < /div >
                        < p class="vidcap" >
                            < a href="#" class="fn fl" >< %#XPath("title")% >< /a >< /p >
                    < /li >
                < /ItemTemplate >
            < /asp:Repeater >

so this is the main line (solution):

< %#XPath("*[local-name()='thumbnail' and namespace-uri()='http://search.yahoo.com/mrss/']/@url")% >'

Compiled By: Rajesh Rolen

Read More

Wednesday, August 3, 2011

Handling null values with the Linq Aggregate methods



You can use it like:

var value = (from t in _table
             where t.Id == id
                && t.Time >= intervalStartTime
                && t.Time <= intervalEndTime
             select (int?)t.Value).Average()

Compiled By: Rajesh Rolen

Read More

For translation to SQL, the Math.Round method needs a MidpointRounding parameter. Use 'AwayFromZero' to specify the SQL function ROUND.



Whenever you will try to use Math.Round with LINQ, that time you will face this error:

For translation to SQL, the Math.Round method needs a MidpointRounding parameter. Use 'AwayFromZero' to specify the SQL function ROUND.


To overcome this problem. just do as its saying..
avgRate = Math.Round( (double) rmpd.Average(a => a.reate),1, MidpointRounding.AwayFromZero )

Compiled By: Rajesh Rolen

Read More

Tuesday, August 2, 2011

Find all possible combinations of a string



Using below function we can find all possible combinations of any string.

  static void Combination(string left, string right)
        {
            if (right.Length == 1)
            {
                Console.Write(left);
                Console.Write(right);
                Console.WriteLine();
                return;
            }
            else
            {
                for (var index = 0; index < right.Length; index++)
                {
                    Combination(left + right[index], right.Remove(index, 1));
                }
            }
        }

you can call above function like:

 Combination("", Console.ReadLine());

Compiled By: Rajesh Rolen

Read More

Monday, August 1, 2011

Convert Integers to Binary, Octal or Hexadecimal

Console.WriteLine(Convert.ToString(value, 2));      // Outputs "10101010"
Console.WriteLine(Convert.ToString(value, 8));      // Outputs "271"
Console.WriteLine(Convert.ToString(value, 16));     // Outputs "b9"

Compiled By: Rajesh Rolen

Read More

Friday, July 29, 2011

Send Email from SQL-Server Database

In order to send mail using Database Mail in SQL Server, there are 3 basic steps that need to be carried out. 1) Create Profile and Account 2) Configure Email 3) Send Email.

The following is the process for sending emails from database.

- Make sure that the SQL Server Mail account is configured correctly and enable Database Mail.

- Write a script to send an e-mail. The following is the script.

USE [YourDB]
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'mathew@xyz.com; saadhya@xyz.com;anirudh@pqr.com’ 
@body = ' A warm wish for your future endeavor',
@subject = 'This mail was sent using Database Mail' ;
GO 

References:
http://blog.sqlauthority.com/2008/08/23/sql-server-2008-configure-database-mail-send-email-from-sql-database/

Compiled By: Rajesh Rolen

Read More

How to get @@Error and @ROWCOUNT at the same time?

if @@Rewcount is checked after error checking statement then it will have '0' as the value of @@Recordcount as it would have been reset. and if @@Recordcount is checked before the error-checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable.
select @recCount = @@Rowcount, @Err = @@error

Compiled By: Rajesh Rolen

Read More

Wednesday, July 27, 2011

What is Table Scan?

Table Scan comes to picture when you search for data in a table and you table does't have any index created on it or your query does't take advantage of any existing index of table.
In normal condition Table Scan is not good but in some circumstances its good to use.

A table scan is the easiest and simplest operation that can be performed against a table. It sequentially processes all of the rows in the table to determine if they satisfy the selection criteria specified in the query. It does this in a way to maximize the I/O throughput for the table.

A table scan operation requests large I/Os to bring as many rows as possible into main memory for processing. It also asynchronously pre-fetches the data to make sure that the table scan operation is never waiting for rows to be paged into memory. Table scan however, has a disadvantage in it has to process all of the rows in order to satisfy the query. The scan operation itself is very efficient if it does not need to perform the I/O synchronously.

Now lets understand what exactly happens during Table Scan

Reads all of the rows from the table and applies the selection criteria to each of the rows within the table. The rows in the table are processed in no guaranteed order, but typically they are processed sequentially.

When Table Scan isn't Bad thing

If you are retrieving every row from a table, and plan on using it, it doesn't really matter that you are doing a table scan because there is really no other way to do it. Another time that it doesn't matter so much is when there is very little data in a table, like a type table or a small lookup table, because SQL Server can intelligently cache data when it needs to, and when there is very little data it can actually degrade performance some when it does have an index because of the overhead of maintaining the index. Striking a good balance of indexing vs. non-indexing is a skill that will come with time and experience.

Ex:
SELECT * FROM Employee
WHERE WorkDept BETWEEN 'A01'AND 'E01'
OPTIMIZE FOR ALL ROWS

References:
http://strangenut.com/blogs/dacrowlah/archive/2008/02/24/what-is-a-table-scan.aspx

Compiled By: Rajesh Rolen

Read More

Monday, July 25, 2011

ASP.NET Application and Page Life Cycle



Today we are going to learn complete application and page life cycle of asp.net
Beginning from request sent from browser to process and then response sent back to browser.

In broad way there are only 2 step process

- creation of an environment which can process the request
(creation of application object, request, response and context objects to process the request)

- Once the environment is created, the request is processed through a series of events which is processed by using modules, handlers and page objects. To keep it short, let's name this step as MHPM (Module, handler, page and Module event)


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.


The below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.


Process Request using MHPM Events Fired

Once ‘HttpApplication’ is created, it starts processing requests. It goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections, it invokes different events which the developer can extend and add customize logic to the same.
Before we move ahead, let's understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:

If you want to inject logic based in file extensions like ‘.ASPX’, ‘.HTML’, then you use ‘HttpHandler’. In other words, ‘HttpHandler’ is an extension based processor.

If you want to inject logic in the events of ASP.NET pipleline, then you use ‘HttpModule’. ASP.NET. In other words, ‘HttpModule’ is an event based processor.

Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below:

Step 1(M: HttpModule): Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET HttpModule emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.

Step 2 (H: ‘HttpHandler’): Once the above 6 events are fired, ASP.NET engine will invoke ProcessRequest event if you have implemented HttpHandler in your project.

Step 3 (P: ASP.NET page): Once the HttpHandler logic executes, the ASP.NET page object is created. While the ASP.NET page object is created, many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages Init, Load, validate, event, render and unload. You can remember the word SILVER to remember the events S – Start (does not signify anything as such just forms the word) , I – (Init) , L (Load) , V (Validate), E (Event) and R (Render).

Step4 (M: HttpModule): Once the page object is executed and unloaded from memory, HttpModule provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
The below figure shows the same in a pictorial format.

In What Event Should We Do What?


Section Event Description
HttpModule BeginRequest This event signals a new request; it is guaranteed to be raised on each request.
HttpModule AuthenticateRequest This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.
HttpModule AuthorizeRequest This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.
HttpModule ResolveRequestCache In ASP.NET, we normally use outputcache directive to do caching. In this event, ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.
HttpModule AcquireRequestState This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.
HttpModule PreRequestHandlerExecute This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.
HttpHandler ProcessRequest Httphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.
Page Init This event happens in the ASP.NET page and can be used for:
  • Creating controls dynamically, in case you have controls to be created on runtime.
  • Any setting initialization.
  • Master pages and the settings.

In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.

Page Load In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Page Validate If you have valuators on your page, you would like to check the same here.
Render It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.
Page Unload Page object is unloaded from the memory.
HttpModule PostRequestHandlerExecute Any logic you would like to inject after the handlers are executed.
HttpModule ReleaserequestState If you would like to save update some state variables like session variables.
HttpModule UpdateRequestCache Before you end, if you want to update your cache.
HttpModule EndRequest This is the last stage before your output is sent to the client browser.

ASP.NET Page Events

Any ASP.NET page has 2 parts, one is the page which is displayed on the browser which has HTML tags, hidden values in form of viewstate and data on the HTML inputs. When the page is posted, these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code, you can execute and write your own login on the same and render the page back to the browser.


Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform, we need to put this logic appropriately in those events.
Note: Most of the developers directly use the page_load method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes, etc., everything happens on the page load. So if we can put logic in proper events as per the nature of the logic, that would really make your code clean.

Seq Events Controls Initialized View state
Available
Form data
Available
What Logic can be written here?
1 Init No No No

Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.

2 Load view state Not guaranteed Yes Not guaranteed You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.
3 PostBackdata Not guaranteed Yes Yes You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4 Load Yes Yes Yes This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls, viewstate and their posted values.
5 Validate Yes Yes Yes If your page has validators or you want to execute validation for your page, this is the right place to the same.
6 Event Yes Yes Yes If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.
7 Pre-render Yes Yes Yes If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8 Save view state Yes Yes Yes Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.
9 Render Yes Yes Yes If you want to add some custom HTML to the output this is the place you can.
10 Unload Yes Yes Yes Any kind of clean up you would like to do here.





I wants to give lots of thanks to real author of this article Mr. Shivprasad koirala
References :http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle.aspx
Read More

Monday, July 18, 2011

Will finally blocks be executed if returning from try or catch blocks



Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.

The return value is determined before the finally block is executed though, so if you did this:
int Test()
{
    int result = 4;
    try
    {
        return result;
    }
    finally
    {
        // Attempt to change value result
        result = 1;
    }
}

the value 4 will still be returned, not 1 .

- the assignment in the finally block will have no effect the return result but it will be executed.

A finally block will always be executed and this will happen before returning from the method, so you can safely write code

Compiled By: Rajesh Rolen

Read More

Where is session stored if cookie is disabled on client’s machine

The session cookie is a special non-persistant cookie. It's only stored in memory, so in most cases even when cookies are disabled it still works fine.

It's also possible to enable something called cookieless sesssions where the sessionID is embedded in the URL, like this:

http://yourserver/folder/ (encrypted session ID here) /default.aspx

Here's a link to an MSDN article with more details:
http://msdn.microsoft.com/en-us/library/aa479314.aspx
Read More

Get all column names of datatable into string array



using Linq you can easily get list/array of all column names of a datatable:

string[] columnNames = dt.Columns.Cast< datacolumn > ().Select(x => x.ColumnName).ToArray();
//or in LINQ
string[] columnNames = (from dc in dt.Columns.Cast< datacolumn >() select dc.ColumnName).ToArray();


Compiled By: Rajesh Rolen

Read More

LINQ over Datatable


using below code we can use LINQ to query Datatables:

var res = from p in dt.AsEnumerable()
 where p.Field< string >("YourFieldName") == "Value" || p.Field < string > ("YourFieldName") == "Value"
 select p;

Compiled By: Rajesh Rolen

Read More

The query results cannot be enumerated more than once

While doing LINQ you will face this error to resolve it add a ToList() at end of your LINQ query. This way, the results are retrieved from the server, after which you can do with them whatever you want (since they are now loaded in-memory).

Compiled By: Rajesh Rolen

Read More

Fastest way to extract number from string


To extract numeric values from string you can use below function:

static string ExtractNumbers(string expr)
        {
            return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
        }

Compiled By: Rajesh Rolen

Read More

Wednesday, June 29, 2011

Saturday, June 25, 2011

Why object of abstract class can’t be instantiate

We all knows that object of abstract class can be created but cannot be instantiated, but important question is why its not allowed to instantiate the object of abstract class?

Lets understand it with an example:
 public abstract  class cal
    {
        public cal()
        {

        }
        public cal(int a)
        {

        }
        public abstract int add(int a, int b);

    }

public class c2 
    {
            cal c;// Yes we can create object of abstract class
            c = new cal() // error, we can't instantiate object of abstract class.

       
    }

as we can see in above example that we cannot instantiate the object of an abstract class, this is because if it allows to instantiate the object of abstract class and if you will call its function named "add" (abstract) then what will happen? as there is no function body/functionality is defined for that "add" method, as its functionality will be defined in its child class so CLI not allows us to instantiate the object of abstract class.

An abstract class has a protected constructor (by default) allowing derived types to initialize it.

An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.
Read More

Friday, June 24, 2011

Can we create clustered index on non primary key column

Yes we can create clustered index on non-primary key column but that column must be unique and the primary key column of that table must have non-clustered index.
By default primary key column contains clustered index so its recommended to create such non-primary key clustered index column first and then should create primary key column so in such case the primary key on that column will be with non-clustered.
But its highly recommended to create primary key column as a clustered indexed column.

Compiled By: Rajesh Rolen

Read More

What is use of parameterized constructor in abstract class? As Abstract classes cannot be instantiated



public abstract class ABC
{

int _a;

  public ABC(int a)
  {
    _a = a;

   }

public abstract void computeA();

};
The above question is little bit tricky, it wants to make you confuse by emphasizing on keyword “Abstract”, where as it has got nothing to do with abstract class.
First of all its essential to understand the constructor call chain. Whenever an object of a class created, its constructor gets called and that constructor calls its parent class’s constructor then this calling chain continuous till super most class’s constructor get called, then first the super most class’s constructor gets executed first then its child class’s constructor (of same chain) and at last the constructor of class whose object has been created will execute.
In the above example scenario where we have only parameterized constructor and no default “Non Parameterized” constructor, the child/inherited class will have to call constructor of its parent abstract class and will have to pass parameters in it.
Like:
public class Foo : ABC
{
    // Always pass 123 to the base class constructor
    public Foo() : base(123)
    {
    }
}
So you don't necessarily need to pass any information to the derived class constructor, but the derived class constructor must pass information to the base class constructor, if that only exposes a parameterized constructor. Also the child class have to override all abstract functions of its parent class.

Compiled By: Rajesh Rolen

Read More

Thursday, June 16, 2011

What is difference between Private and Sealed Classes



Sealed Class:

"Sealed" keyword provide us facility to prevent a class to be inherited by other classes, so "Sealed" classes cannot be inherited by any other class.

You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

"Sealed" class can have constructor, and they can only be used by its object (non-static methods).

Private Class:

Private class cannot be used directly under any namespace, means we can only create private class as a nested class, to make it available only to class to whom its nested.

the only/mostly use of Private class/structure is to create a user-defined type, which you wants to be accessible to that class only.

NOTE:Nested/inner class can be public also and that can be accessible to inherited class or by object where as private nested/inner class is only accessible to its outer class .


Compiled By: Rajesh Rolen

Read More

Tuesday, June 14, 2011

Override style of css class for some elements in page

I had to change the image of handle of jquery's slider control for some specific page, i have done that by below style, which i created in the page in which i had to change the image of slider's handel.

< style type="text/css" >
    .ui-slider-horizontal .ui-state-default
    {
        background: white url(../images/sliderhandle.png) no-repeat scroll 50% 50%;
    }
    .ui-slider-horizontal .ui-slider-handle
    {
        top: 0.9em;
        border: 0px;
    }
< /style >


Compiled By: Rajesh Rolen

Read More

Thursday, June 9, 2011

Cast Int to Enum and vice-versa


Many of times we face a situation where we are to cast integer/string value to Enum or vice-versa


Cast Int To Enum

From a string:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

From an int:
YourEnum foo = (YourEnum)yourInt;

From number you can also:
YourEnum foo = Enum.ToObject(typeof(YourEnum) , yourInt);


Cast Enum To Int

int something = (int)Question.Role;

Get Enum type as a string: YourEnumName.ItsOption.ToString()

Compiled By Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates