28 February 2014

FxCop and StyleCop

It runs on compiled DLLs.
As it runs on compiled IL code, it can be used for C#, VB.NET, in short any language which compiles to IL code.
StyleCop
Keep in mind that it is not a Microsoft product. It is not even a Team System Power Tool. It is a tool developed by a very passionate developer at Microsoft (on evenings and weekends). There's no support, servicing, evolution or anything else beyond what he can get done in his spare time. Style checking is an interesting feature and may show up in an official product at some point down the road.
It runs on actual source code.
Currently it runs only on C#.
The ultimate goal of StyleCop is to allow to produce elegant, consistent code that team members and others who view developer code will find highly readable.
Code Analysis
No spell checking - FxCop uses a dictionary (plus custom dictionary) to check the names of methods, classes, etc. Code Analysis doesn't seem to do that.
Help - FxCop not only complained when something was wrong but provided a great deal of help/hints to resolve the problem. Code Analysis just seems to present the problem with no sign of a hint.
Note that Code Analysis is only available in the Premium and Ultimate editions of Visual Studio 2010 and also Visual Studio 2005 & 2008 Team System.

FxCop analyzes programming elements in managed assemblies, called targets, and provides an informational report that contains messages about the targets, Messages include suggestions about how to improve the source code used to generate them. FxCop represents the checks it performs during an analysis as rules. A rule is managed code that can analyze targets and return a message about its findings. Rule messages identify any relevant programming and design issues and, when possible, supply information about how to fix the target.
Using FxCop, you can perform the following tasks:
Control which rules are applied to targets.
Exclude a rule message from future reports.
Apply style sheets to FxCop reports.
Filter and save messages.
Save and reuse application settings in FxCop projects.
Working in the FxCop Application Window
The FxCop application window displays the targets and rules included in a project, and the messages that are generated when an analysis is performed. The window is divided into three major areas: the configuration pane on the left, the messages pane on the right, and the properties pane at the bottom.

27 February 2014

Define Usage of Lock Keyword in C#

                      The lock keyword may be useful especially when you are using threading in your application. It ensures that only one thread can enter and use the critical section. If another thread needs to use the critical section, it has to wait until the previous object is released.

26 February 2014

Application.Run in C#.Net

  • The Application.Run will run the standard application message loop in the current thread where the Application runs.
  • The Application.Run also takes the parameter of type Form

Descendants vs. Elements in Linq to XML

Starting with Elements(XName).
Returns a filtered collection of the child elements of this element or document, in document order.
Only elements that have a matching XName are included in the collection.
And secondly the Descendants(XName) method.
Returns a filtered collection of the descendant elements for this document or element, in document order.
Only elements that have a matching XName are included in the collection.

24 February 2014

Use Proper Casing for Members

IdentifierCasingExample
Class, StructPascalStrategyManager
InterfacePascal with I prefixIStrategy
EnumerationPascalLoggingLevel
Enumeration ValuePascalInfo
Enumeration Representing Bit FieldPascal in pluralSearchOptions
EventPascalClick
Private FieldCamel with underscore_scheduler
Protected FieldCamel with underscore_scheduler
Constant FieldPascalPi
Constant VariableCameldefinitionKey
Readonly FieldCamel with underscore_listItems
Static Readonly FieldPascalListValues
VariableCamelvalue
MethodPascalComputeValue
PropertyPascalValue
ParameterCamelparameter
Type ParameterPascal with T prefixTValue
NamespacePascalSystem.Drawing
Abbreviation with 2 and less lettersAll CapsUI, IO
Abbreviation with 3 and more lettersPascalXml, Http
Use Proper Class Layout
Use the following order to position all your members inside the class. The resulting layout is the combination of all the lists provided with descending priority. That means that on the top of the file there will be all public const fields followed by internal const fields.
1.     Fields
2.     Delegates
3.     Events
4.     Properties
5.     Indexers
6.     Constructors
7.     Finalizers
8.     Methods
9.     Other stuff
Than follow access modifier.
1.     public
2.     internal
3.     protected
4.     private
After access modifier follow the type of the member.
1.     const
2.     static
3.     readonly
4.     nothing
The least significant sorting attribute is a declaration modifier.
1.     virtual
2.     abstract
3.     override
4.     new

23 February 2014

XSLT Elements

                     The links in the "Element" column point to attributes and more useful information about each specific element.


Element
Description
Applies a template rule from an imported style sheet
Applies a template rule to the current element or to the current element's child nodes
Adds an attribute
Defines a named set of attributes
Calls a named template
Used in conjunction with <when> and <otherwise> to express multiple conditional tests
Creates a comment node in the result tree
Creates a copy of the current node (without child nodes and attributes)
Creates a copy of the current node (with child nodes and attributes)
Defines the characters and symbols to be used when converting numbers into strings, with the format-number() function
Creates an element node in the output document
Specifies an alternate code to run if the processor does not support an XSLT element
Loops through each node in a specified node set
Contains a template that will be applied only if a specified condition is true
Imports the contents of one style sheet into another. Note: An imported style sheet has lower precedence than the importing style sheet
Includes the contents of one style sheet into another. Note: An included style sheet has the same precedence as the including style sheet
Declares a named key that can be used in the style sheet with the key() function
Writes a message to the output (used to report errors)
Replaces a namespace in the style sheet to a different namespace in the output
Determines the integer position of the current node and formats a number
Specifies a default action for the <choose> element
Defines the format of the output document
Declares a local or global parameter
Defines the elements for which white space should be preserved
Writes a processing instruction to the output
Sorts the output
Defines the elements for which white space should be removed
Defines the root element of a style sheet
Rules to apply when a specified node is matched
Writes literal text to the output
Defines the root element of a style sheet
Extracts the value of a selected node
Declares a local or global variable
Specifies an action for the <choose> element
Defines the value of a parameter to be passed into a template

22 February 2014

Define Lambda Expression

Lambda Expression is a function without a name the calculates and returns single value.
Lambda Expression uses to lambda operator => [Goes To].
Syntax:
Inut Parameter) => Expression
Example:
Add Two TestBox into Form.
TxtInput and TxtOutput.
string[] arrName ={"Lakshmi",,"Narayaanan","Sriram","Suresh","Sravan","Srinath"};

Convert int? to int in C#.net

Convert int? to int in C#.net
int? v1;
int v2;
if(v1.HasValue)
v2=v1.Value

21 February 2014

App Config File in C#.net

Read Setting Method
public static string ReadSetting(string key)
{
return ConfigurationSettings.AppSettings[key];
}
Write Setting Method
public static void WriteSetting(string key, string value)
{
XmlDocument doc = LoadConfigDocument();
XmlNode node = doc.SelectSingleNode("//appSettings");
if (node == null)
throw new InvalidOperationException("appSettings section not found in config file.");
try
{
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
if (elem != null)
{
elem.SetAttribute("value", value);
}
else
{
elem = doc.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
doc.Save(GetConfigFilePath());
}
catch
{
throw;
}
}
Remove Setting Method
public static void RemoveSetting(string key)
{
XmlDocument doc = LoadConfigDocument();
XmlNode node = doc.SelectSingleNode("//appSettings");
try
{
if (node == null)
throw new InvalidOperationException("appSettings section not found in config file.");
else
{
node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
doc.Save(GetConfigFilePath());
}
}
catch (NullReferenceException e)
{
throw new Exception(string.Format("The key {0} does not exist.", key), e);
}
}
Load Config Document Method
private static XmlDocument LoadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(GetConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{ throw new Exception("No configuration file found.", e);
}
}
Get Config FilePath Method
private static string GetConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}


15 February 2014

Display ODD or Even using LINQ in C#.net

This is the C# Code for Find display Odd or Even Number using LINQ .
var numbers = from n in Enumerable.Range(1,25)
select new {number = n,OddEven =n %2 ==1? "odd","Even"};
foreach(var n in mubers)
{
listbox1.items.add("The Number is" ,+n.number +n.OddEven);
}

14 February 2014

Define Dynamic Resource

The resource that are referred by using the DynamicResources markup extension are knows as Dynamic Resource.

13 February 2014

Define Static Resource

The resource that are referred by using the staticResources markup extension are knows as static Resource.

12 February 2014

Define XBAPs

  •     XBAPs Stands for XAML Browser  application.
  •     It is a Webserver hosted WPF applications that run in a web browser.
  •     It consists of several pages ,which uses can nativate through in the browser.


Designing Pattern

Designing Pattern

  1. Creational Patterns
  2. Strucutural Patterns
  3. Behavioral Patterns

1. Creational Patterns:
Abtaract Factory:
 Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Builder Patterns:
 Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Factory Method:
 Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Prototype Patterns:
 Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
Singleton Patterns:
   Ensure a class has only one instance and provide a global point of access to it.
2. Strucutural Patterns
Adapter :
  Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Bridge :
   Decouple an abstraction from its implementation so that the two can vary independently.
Composite:
 Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Decorate:
   Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
facade:
  Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
Flyweight:
  Use sharing to support large numbers of fine-grained objects efficiently.
Proxy:
 Provide a surrogate or placeholder for another object to control access to it.
3.Behavioral Patterns
Chain of Responibility:
 Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Command:
 Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Interpreter:
  Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Iterator:
     Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Mediator:
 Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independent.
Memento:
 Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Observe:
    Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
State:
 Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Strategy:
 Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Template Method:
 Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Visitor:
  Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

11 February 2014

Define split entity

An entity type that is mapped to two separate types in the storage model.

Define scalar property


A property of an entity that maps to a single field in the storage model.

Define EntityClient

System.Data.EntityClient is a storage-independent ADO.NET data provider that contains classes such as EntityConnection, EntityCommand, and EntityDataReader. Works with Entity SQL and connects to storage specific ADO.NET data providers, such as SqlClient.

Define VSM

               In WPF 4.0 provides better support to modify the visual state o the control in the control template class with the help o the visualstatemanager class.

10 February 2014

Define LINQ To Entities

LINQ to Entities provides Language-Integrated Query (LINQ) support for querying entities.

LINQ to Entities enables developers to write queries against the database using one of the supported .NET Framework programming languages such as Visual Basic or Visual C#.


Purpose of the MustInherit keyword in VB.NET

MustInherit keyword in VB.NET is used to create an abstract class.

prevent inheritance of a class in .NET

Use the keyword NotInheritable in VB.NET and sealed in C#.

09 February 2014

Define Entity SQL


Entity SQL is a SQL-like storage-independent language, designed to query and manipulate rich object graphs of objects based on the Entity Data Model (EDM).

prevent overriding of a class in .NET

Use the keyword NotOverridable in VB.NET and sealed in C#.

Is it possible to create a shared event in .NET

Yes, but shared events may only be raised by shared methods.

08 February 2014

AddressOf in VB.NET operator do

The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.

07 February 2014

Difference between the Take and Skip clauses


               The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string.

Define use of SqlCommandBuilder

           SQL CommandBuilder object is used to build & execute SQL (DML) queries like select insert update& delete.

Implement inheritance using VB.NET & C#


  • C# Derived Class : Baseclass
  • VB.NEt : Derived Class Inherits Baseclass


Union Used to remove duplicate rows

How many times should a Union be used to Remove duplicate rows
   One Time

06 February 2014

Difference between WindowsDefaultLocation and WindowsDefaultBounds


  • WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. 
  • WindowsDefaultBounds delegates both size and starting position choices to the OS. 

05 February 2014

Create a separator in the Menu Designer

A hyphen ‘-’ would do it. Also, an ampersand ‘&’ would underline the next letter. 

04 February 2014

Allow and Disallow insert into identity field

Set IDENTITY_INSERT ON|OFF.
Example(s)
 Allow insert into identity field:
Set IDENTITY_INSERT tbk=l_Customer_Master ON
DisAllow insert into identity field:
Set IDENTITY_INSERT tbk=l_Customer_Master OFF

03 February 2014

Define DataContext

  • To communicate with a Database a connection must be made. In LINQ this connection is created by a DataContext.
  • Create connection to database.
  • It submits and retrieves object to database.
  • Converts objects to SQL queries and vice versa.


Entity Framework Features

  • EF 3.5 Basic O/RM support with Database First approach.
  • EF 4.0 POCO Support, Lazy loading, testability improvements, customizable code generation and the Model First approach.
  • EF 4.1 First to available of NuGet package, Simplified DBContext API over ObjectContext, Code First approach. EF 4.1.1 patch released with bug fixing of 4.1.
  • EF 4.3 Code First Migrations feature that allows a database created by Code First to be incrementally changed as your Code First model evolves. EF 4.3.1 patch released with bug fixing of EF 4.3.
  • EF 5.0 - Current release Announced EF as Open Source. Introduced Enum support, table-valued functions, spatial data types, multiple-diagrams per model, coloring of shapes on the design surface and batch import of stored procedures, EF Power Tools and various performance improvements.
  • EF 6.0 - Future release EF 6.0 is currently in pre-release state. It will include Task-based async, Stored Procedures & Functions in Code First and Custom Code First conventions.

02 February 2014

LINQ Vs DLINQ Vs XLINQ


S.NoLINQ DLINQXLINQ
1programming model that introduces queries as a first-class concept into any Microsoft .NET languagean extension to Linq that allows querying a database and do object-relational mapping.an extension to Linq that allows querying XML documents, as well as creating or transforming XML.

01 February 2014

Dynamic vs Anonymous types


S.NoDynamicAnonymous types
1Dynamic types work at run time by late binding of object properties.Anonymous types cause the compile time errors.
2Dynamic KeywordVar Keyword