h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Visual Studio Productivity Power Tools Update

Visual Studio Productivity Power Tools Update

Microsoft has updated the free Productivity Power Tools for Visual Studio 2010.
These are add-ins that provide very useful additional functionality for Visual Studio.
New in this release:

  • No More Extension Resets
  • Find 
  • Enhanced Scrollbar
  • Middle-Click Scrolling
  • Organize Imports for Visual Basic
Visual Studio Productivity Power Tools Update link

Happy New Year Wishes To All


  • A Little key can open big locks Simple words reflect great thoughts Your smile can cure heart problems So keep on smiling more and more Have a happy new year full of smile. 
  • Peace In Your Heart, Health In Your Body, Wealth In Your Life, Joy In Your Home, May U Always Be Blessed With These Priceless Treasures Happy New Year.
Happy New Year  to All Readers and friends.

C# Internal Interface

C# Internal Interface

          you can not declare Encapsulation in the Interface like Public
Example for Internal Interface.
Here , One class and Two Interface in the coding.
Class Name:MyClass
Interface Names :IMyPublicInterface,IMyInternalInterface

Create  Normal  interface

public interface IMyPublicInterface
{
    void MyPublicMethod();
}
Create  Internal  interface
internal interface IMyInternalInterface
{
    void MyInternalMethod();
}
Inherited two interface into One class using Colon(:)
public class MyClass :
    IMyPublicInterface, IMyInternalInterface
{
/// Called interface methods in the Class
    public void MyPublicMethod() { }
    void IMyInternalInterface.MyInternalMethod() { }
}

Explicit interface member implementations

Explicit interface member implementations
             An explicit interface member implementation is a method, property, event, or indexer declaration that references a fully qualified interface member name.

Example for Explicit interface member implementations
interface IControl
{
   void Paint();
}
interface ITextBox: IControl
{
   void SetText(string text);
}
class TextBox: ITextBox
{
   void IControl.Paint() {...}
   void ITextBox.SetText(string text) {...}
}

Zoom the View in Visual Studio

Zoom the View in Visual Studio

Keyboard Shortcuts

  • To make the font larger, press CTRL+SHIFT+PERIOD
  • To make the font smaller, press CTRL+SHIFT+COMMA


Dictionary initializer in C# 6.0

Dictionary initialize in C# 6.0
            Adds a new ability to use the Key / indexer to map with the Values directly during the initialization itself.

Dictionary<int, string> students = new Dictionary<int, string> {
[1] = "Student 1" ,
[2] = "Student 2",
[3] = "Student 3",
[4] = "Student 4",
};

Dictionary initializer in C#

Dictionary initialize in C# 

  You can easily initialize a Dictionary Object using a Collection Initialize, which is there since C# 3.0.
  Collection initialize adds one of the  parameter as Key and another as  Value corresponding to the assigned Key.

Dictionary<int, string> students = new Dictionary<int, string> {
{1, "Student 1" },
{2, "Student 2" },
{3, "Student 3" },
{4, "Student 4" }
};
Find Public Key Token  for dll in Visual Studio

Use .Net Framework Tool sn.exe
Open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to
get the public key,

Use the following command,
sn –T myDLL.dll
This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.

New Features of C# 6.0

New Features of C# 6.0

  • Initialization of Dictionary – Dictionary initializer in C# 6.0
  • Null – Conditional Operators in C# 6.0
  • Using nameof Operator in C# 6.0
  • Conditional Exception Handling – Exception Filters in C# 6.0
  • Using await in a catch or finally block – in C# 6.0
  • Expression – Bodied Methods in C# 6.0
  • Simplify Static Member Access – Using Statement With Static Classes in C# 6.0
  • Easily format strings – String interpolation in C# 6.0
  • Initialize Auto-Property in C# 6.0
  • Getter Only Auto-Property in C# 6.0


Tips to improve performance of C# code

Tips to improve performance of C# code

  • Choose your data type before using it
  • Use For loop instead of foreach
  • Choose when to use a class and when to use a structure
  • Always use Stringbuilder for String concatenation operations
  • Choose best way to assign class data member
  • Boxing and UnBoxing
  • ‘as’ versus type casting
  • Control overflow checking
  •  Using readonly versus const
  • Avoid producing a lot of garbage
  • Avoid using finalizers when possible
  • Recycle and/ or cache objects
  • Reduce class hierarchy
  • Avoid explicitly calling the Garbage Collector
  • Avoid synchronization
  • Use Lazy Evaluation
  •  Optimized classes
  •  Explicitly close resources
  • Limit number of threads
  • Ternary Operator (?:)
  •  Null-Coalesce Operator (??)
  • Namespace Alias Qualifier
  • Object Initializers
  • Nullable Types
  • Type Inference
  • Lambda Expressions



Volatile -- C# Keyword

volatile -- C# Keyword


  • The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.
  • The volatile keyword can be applied to fields of these types:
  • Reference types.
  • Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a "pointer to volatile."
  • Types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
  • An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
  • Generic type parameters known to be reference types.
  • IntPtr and UIntPtr.

public volatile <data type> <Var Name>;

virtual -- C# Keyword

virtual -- C# Keyword
         The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.

 public virtual <Data Type> <Method Name>()
{
///Code
  return <Value>
}

unsafe -- C# Keyword

unsafe -- C# Keyword
           The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.

Without  Parameter
unsafe
{
    // Unsafe context: can use pointers here.
}
With Parameter(s)
unsafe static void <Method Name>(<data Type> <var name>)
{
    // Unsafe context: can use pointers here.
}

static -- C# Keyword

static  -- C# Keyword


  • Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.
  •  The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
static class <Class Name>
    {
        public static void <Method Name>() { /*...*/ }
        public static void <Method Name>() { /*...*/  }
    }

sealed -- C# Keyword

sealed  -- C# Keyword

  •  When applied to a class, the sealed modifier prevents other classes from inheriting from it.
  •   In the following example, class B inherits from class A, but no class can inherit from class B.


class A {}  
sealed class B : A {}

readonly -- C# Keyword

readonly -- C# Keyword
  •  The readonly keyword is a modifier that you can use on fields.
  •   When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
readonly <data Type> <var Name>;

override -- C# Keyword

override -- C# Keyword


  •  The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
  • An override declaration cannot change the accessibility of the virtual method.
  • Both the override method and the virtual method must have the same access level modifier.
  • You cannot use the new, static, or virtual modifiers to modify an override method.

out -- C# Keyword

out -- C# Keyword

  • This keyword implemented from VS 2010
  •  The out keyword specifies that the type parameter is covariant.
  • You can use the out keyword in generic interfaces and delegates.

interface <interface Name><out R> { }

extern -- C# Keyword

extern -- C# Keyword

  •  The extern modifier is used to declare a method that is implemented externally.
  • A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code.
  • In this case, the method must also be declared as static, 

[DllImport("<dll Name>.dll")]
private static extern void <dll Method Name>();

const -- C# Keyword

const  -- C# Keyword
  • You use the const keyword to declare a constant field or a constant local.
  •  Constant fields and locals aren't variables and may not be modified.
  •  Constants can be numbers, Boolean values, strings, or a null reference.
const <Data Type> <Var Name> = <Set Value>;

Protected -- C# Keyword

Protected  -- C# Keyword:


  • The protected keyword is a member access modifier.
  • A protected member is accessible within its class and by derived class instances.

 protected <Data Type> <Variable Name>;

async -- C# Keyword

async  -- C# Keyword


  • This Keyword is implemented from VS 2012.
  •         Use the async modifier to specify that a method, lambda expression, or anonymous method is asynchronous.
  •         If you use this modifier on a method or expression, it's referred to as an async method.

public async Task<int> ExampleMethodAsync()
{
    // . . . .

}

in -- C# Keyword

in -- C# Keyword


  •    This Keyword is implemented from VS 2010.
  •    The in keyword specifies that the type parameter is contravariant.
  •    You can use the in keyword in generic interfaces and delegates.

// Contravariant interface.

interface <Interface Name><in A> { }

Insert ,Update ,Delete and Display in Datagridview using LINQ To SQL in C#.Net

Insert ,Update ,Delete and Display in Datagridview using LINQ To SQL in C#.Net

Create tables in SQL server
tbl_department_master
depId  int -- Primary Key -- Set Identify is true
DepName -- varchar(Max)

tbl_Position_Master
PatId int -- Primary key
Patname-- varchar(Max)

Add LINQ To SQL in the your project
Go To Server Explore
Add Data Connection
Drag Tables into LIQToSQL Class
Create user Control

Add User Control in your Project.
Add Datagridview and Two buttons on the User Control
Declare Variables ,Data Context  and Events
 DataClasses1DataContext objDC = null;
 tbl_Department_Master objDM = null;
 tbl_Position_Master objPM = null;
public event EventHandler SaveClicked;
public event EventHandler CloseClicked;
/// To Display Data
 public void Displaydata(string mode)
        {
            switch (mode)
            {
                case "Department":
                    DisplayData("Department");
                    break;
                case "Position":
                    DisplayData("Position");
                    break;
            }
        }
 private void DisplayData(string mode)
        {
            objDC = new DataClasses1DataContext();
            switch (mode)
            {
                case "Department":
                    var query = from q in objDC.tbl_Department_Masters
                                select q;
                    dataGridView1.DataSource = query;
                    break;
                case "Position":
                    var Posquery = from Pq in objDC.tbl_Position_Masters
                                   select Pq;
                    dataGridView1.DataSource = Posquery;
                    break;
            }        
        }
/// Delete Data
 private void DeleteData(string mode)
        {
            objDC = new DataClasses1DataContext();
            switch (mode)
            {
                case "Department":
                    objDM = new tbl_Department_Master();
                    if (objDM != null)
                    {
                        var Delet = from d in objDC.tbl_Department_Masters
                                    select d;
                        foreach (var details in Delet)
                        {
                            objDC.tbl_Department_Masters.DeleteOnSubmit(details);
                        }
                        objDC.SubmitChanges();
                    }
                    break;
                case "Position":
                    objPM = new tbl_Position_Master();
                    if (objPM != null)
                    {
                        var Delet = from d in objDC.tbl_Position_Masters
                                    select d;
                        foreach (var details in Delet)
                        {
                            objDC.tbl_Position_Masters .DeleteOnSubmit(details);
                        }
                        objDC.SubmitChanges();
                    }
                    break;
            }
        }
/// Save Data
public void SaveData(string mode)
        {
            switch (mode)
            {
                case "Department":
                    DeleteData("Department");
                    objDC = new DataClasses1DataContext();
                    for (int index = 0; index < dataGridView1.Rows.Count - 1; index++)
                    {
                        objDM = new tbl_Department_Master();
                        objDM.depId = Convert.ToInt32(dataGridView1.Rows[index].Cells[0].Value);
                        objDM.DepName = Convert.ToString(dataGridView1.Rows[index].Cells[1].Value);
                        objDC.tbl_Department_Masters.InsertOnSubmit(objDM);
                        objDC.SubmitChanges();
                    }
                    DisplayData("Department");
                    break;
                case "Position":

                    DeleteData("Position");
                    objDC = new DataClasses1DataContext();
                    for (int index = 0; index < dataGridView1.Rows.Count - 1; index++)
                    {
                        DataGridViewRow objRowIndex = new DataGridViewRow();
                        objPM = new tbl_Position_Master();
                        objPM.PatId = Convert.ToInt32(dataGridView1.Rows[index].Cells[0].Value);
                        objPM.Patname = Convert.ToString(dataGridView1.Rows[index].Cells[1].Value);
                        objDC.tbl_Position_Masters.InsertOnSubmit(objPM);
                        objDC.SubmitChanges();
                    }
                    DisplayData("Position");
                    break;
            }
        }

Call this User Control in your form:

Add the code in your code Page

private void DisplayData(string mode)
        {
          switch (mode)
            {
                case "Department":
                    ucDepartment1.Displaydata("Department");
                    break;
                case "Position":
                    ucDepartment1.Displaydata("Position");
                    break;
            }

        }

        private void FrmDepartment_Load(object sender, EventArgs e)
        {
            DisplayData("Position");
        }

        private void ucDepartment1_Load(object sender, EventArgs e)
        {

        }

        private void ucDepartment1_CloseClicked(object sender, EventArgs e)
        {
            ((Form)this.TopLevelControl).Close();
        }

        private void ucDepartment1_SaveClicked(object sender, EventArgs e)
        {
            ucDepartment1.SaveData("Position");

        }

do -- C# Keyword

do -- C# Keyword

  •   The do statement executes a statement or a block of statements repeatedly until a specified expression evaluates to false.
  •       The body of the loop must be enclosed in braces, {}, unless it consists of a single statement.
  •       In that case, the braces are optional.
        do
        {
              ///Write your Code        

        } while ();

Abstract -- C# Keywords

Abstract Classes and Abstract Methods in C#.NET

Abstract Classes:

  •   Provide default functionality to its sub classes.
  •   Contain methods with complete implementation, besides abstract methods.
  •   Contains at least one abstract method, then the class must be declared as abstract class.


//Abstract class
    abstract class <Class Name>
    {

        protected float <Var Name>;

        //Abstract methods can have only declarations
        public abstract <DataType> <Method Name>();
         ///Method with Paramenter
        public abstract <DataType> <Method Name>(<DataType> obj);

    }

class  <Class Name(child Class)> : <Class Name(Parent Name)>
{
        public Override <DataType> <Method Name>();
{
/// Write your Code
}

        public Override <DataType> <Method Name>(<DataType> obj);
{
/// Write your Code
}

}

Tips to improve Entity Framework Performance

Tips to improve Entity Framework Performance


  • Avoid to put all the DB Objects into One Single Entity Model
  • Disable change tracking for entity if not needed
  • Use Pre-Generating Views to reduce response time for first request
  • Avoid fetching all the fields if not required
  • Choose appropriate Collection for data manipulation
  • Use Compiled Query wherever needed
  • Retrieve only required number of records
  • Avoid using Contains
  • Avoid using Views
  • Debug and Optimize LINQ Query

ADO.NET Entity Framework Version

ADO.NET Entity Framework Version

Version : 3.5
  This release provided basic O/RM support using the Database first development.
Version: 4.0

  • Model-first development
  • POCO support
  • Lazy Loading
  • T4 Code Generation

Version :4.1

  • Code First development
  • Introduced DbContext API
  • Data Annotations and Fluent API Validation

Version: 4.2
The EF 4.2 release included the bug fixes to EF 4.1
Version: 4.3

  • Code First Migrations
  • Automatic Migrations

Version 5.0

  • Enum Support in Code First and EF Designer
  • Spatial Data Types in Code First and EF Designer
  • Table-Valued Functions
  • Multiple Diagrams per Model

Version 6.0:

  • Async Query and Save
  • Code-Based Configuration
  • Dependency Resolution
  • Interception/SQL logging
  • Improved Connection Management
  • Improved Transaction Support


Difference between Lazy Loading and Eager Loading

Difference between Lazy Loading and Eager Loading

Lazy/Deferred Loading
       In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested.
       By default LINQ supports lazy loading.

Eager loading

      In case of eager loading, related objects (child objects) are loaded automatically with its parent object. To use Eager loading you need to use Include() method.

Type of Inheritance in Entity Framework

Type of Inheritance in Entity Framework

1) Table-Per-Hierarchy(TPH):

The TPH inheritance states that all entities, in a hierarchy of entities, are mapped to a single table in storage schema. It means, there is only one table in database and different Entity types in Entity model
public class Employee
{
 public int EmployeeID { get; set; }
 public string EmployeeName { get; set; }
}
public class EmployeeDetails : Employee
{
 public string EmployeeAddress { get; set; }
 public string EmployeeMobile { get; set; }
}
public class EmployeeLogin : Employee
{
 public string UserName { get; set; }
 public string Password { get; set; }
}
Entity Framework Code First Mapping for TPH
modelBuilder.Entity<Employee>()
 .Map<EmployeeDetails>(m => m.Requires("Type").HasValue("EmployeeDetails"))
 .Map<EmployeeLogin>(m => m.Requires("Type").HasValue("EmployeeLogin"));

2) Table-per-Type (TPT)
        The TPT inheritance states that each entity in the hierarchy of entities is mapped to a separate table in storage schema. It means, there is separate table in database to maintain data for each Entity Type.
public class Employee
{
 public int EmployeeID { get; set; }
 public string EmployeeName { get; set; }
}
public class EmployeeDetails : Employee
{
 public string EmployeeAddress { get; set; }
 public string EmployeeMobile { get; set; }
}
public class EmployeeLogin : Employee
{
 public string UserName { get; set; }
 public string Password { get; set; }
}
Entity Framework Code First Mapping for TPT
modelBuilder.Entity<Employee>().ToTable("Employee");
modelBuilder.Entity<EmployeeLogin>().ToTable("EmployeeLogin");
modelBuilder.Entity<EmployeeDetails>().ToTable("EmployeeDetails");
Table-per-Concrete-Type (TPC)
          The TPC inheritance states that each derived entity (not base entity) in the hierarchy of entities is mapped to a separate table in storage schema.
          It means, there is separate table in database to maintain data for each derived entity type.
          This inheritance occurs when we have two tables with overlapping fields in the database like as a table and its history table that has all historical data which is transferred from the main table to it.
public abstract class Employee
{
 public int EmployeeID { get; set; }
 public string EmployeeName { get; set; }
}
public class EmployeeDetails : Employee
{
 public string EmployeeAddress { get; set; }
 public string EmployeeMobile { get; set; }
}
public class EmployeeLogin : Employee
{
 public string UserName { get; set; }
 public string Password { get; set; }
}
Entity Framework Code First Mapping for TPC
modelBuilder.Entity<EmployeeDetails>().Map(m =>
{
 m.MapInheritedProperties();
 m.ToTable("EmployeeDetails");
});
modelBuilder.Entity<EmployeeLogin>().Map(m =>
{
 m.MapInheritedProperties();
 m.ToTable("EmployeeLogin");
});

XAML

Introduction to XAML
XAML stands for Extensible Application Markup Language.
Its a simple language based on XML to create and initialize .NET objects with hierarchical relations.
All classes in WPF have parameterless constructors and make excessive usage of properties.
Advantages of XAML
All you can do in XAML can also be done in code.
XAML is just another way to create and initialize objects.
You can use WPF without using XAML.
It's up to you if you want to declare it in XAML or write it in code.

Declare your UI in XAML has some advantages:
XAML code is short and clear to read
Separation of designer code and logic
Graphical design tools like Expression Blend require XAML as source.
The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.

Properties as Elements
Properties are normally written inline as known from XML <Button Content="OK" />.
we can use the property element syntax. This allows us to extract the property as an own child element.
Syntax:
<Button>
  <Button.Content>
     <Image Source="Images/OK.png" Width="50" Height="50" />
  </Button.Content>
</Button>

Implicit Type conversion
A very powerful construct of WPF are implicit type converters.
They do their work silently in the background. When you declare a BorderBrush, the word "Blue" is only a string.
The implicit BrushConverter makes a System.Windows.Media.Brushes.Blue out of it.
The same regards to the border thickness that is beeing converted implicit into a Thickness object.
WPF includes a lot of type converters for built-in classes, but you can also write type converters for your own classses.
Syntax:
<Border BorderBrush="Blue" BorderThickness="0,10">
</Border>

Markup Extensions
Markup extensions are dynamic placeholders for attribute values in XAML.
They resolve the value of a property at runtime.
Markup extensions are surrouded by curly braces
(Example: Background="{StaticResource NormalBackgroundBrush}").
WPF has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension.
These are the built-in markup extensions:
Binding
To bind the values of two properties together.
StaticResource
One time lookup of a resource entry
DynamicResource
Auto updating lookup of a resource entry
TemplateBinding
To bind a property of a control template to a dependency property of the control
x:Static
Resolve the value of a static property.
x:Null
Return null
Syntax
<TextBox x:Name="textBox"/>
<Label Content="{Binding Text, ElementName=textBox}"/>

Namespaces
At the beginning of every XAML file you need to include two namespaces.
The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all wpf controls in System.Windows.Controls.
The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markup that defines the XAML keywords.
The mapping between an XML namespace and a CLR namespace is done by the XmlnsDefinition attribute at assembly level. You can also directly include a CLR namespace in XAML by using the clr-namespace: prefix.
Syntax:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Window>

Disable UAC

                As most have found out if you disable the UAC (User Account Controls) the desk top gadgets don't work. I found the registy edit that lets you disable UAC and keep the desktop gadgets. I did reboot to see if it works and it does!

using Registry Editor

1. Open Registry Editor (regedit.exe)
2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Sidebar\Settings
3. Create a new DWORD Value called AllowElevatedProcess
4. Set the value of the new DWORD to 1
5. Close the registry editor. Your gadgets should work now. No reboot or anything necessary.

using Command Line

C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f


Code Sign Vs SSL Certificate

Basically, a code-signing cert gives you a private key that can be verified against a public key certified by a known authority. You make a digital signature with that key, and the other end can verify you had a cert from a trusted source when you signed it.

An SSL cert is just a signed "document" that can be verified as coming from a trusted source. You can't encrypt or sign with it because it doesn't have any key material that's yours alone; it's just a signed document saying "I certify that I trust who this guy says he is."

n SSL Certificate is used for authentication of your website/application server.
A Code Signing Certificate is used for integrity/authentication of the exe,dll,... you deliver.

Get Connectionstring from app.config

Get Connectionstring from app.config



<connectionStrings>
    <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
  </connectionStrings>

Output

 string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            MessageBox.Show(connStr);

Get User settings

Get User settings

Input
<userSettings>
        <TestSetting.Properties.Settings>
            <setting name="CompanyName" serializeAs="String">
                <value>Gantec</value>
            </setting>
        </TestSetting.Properties.Settings>
    </userSettings>

Output
MessageBox.Show(Properties.Settings.Default.CompanyName);

Get AppSettings.config File in C#.net

Get AppSettings.config File


Input


<configuration>
  <appSettings>
    <add key="ShowQuery" value="true"/>
  </appSettings>
</configuration>

Output

ConfigurationManager.AppSettings["ShowQuery"];

Prevent Multiple Instance Running

Prevent Multiple Instance Running

In Program.cs file add the below code.
 static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process[] process = Process.GetProcessesByName(Application.ProductName); //Prevent multiple instance
if (process.Length > 1)
{
MessageBox.Show("{Application Name}  is already running. This instance will now close.", "{Application Name}",
MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();
}
else
{
Application.Run(new <Initial Form>());
}
}

Visual Studio 2013 New Features

Visual Studio 2013 New Features

  • Roaming Settings
  • CodeMap – Visual Debugging
  • Peek Definition – Alt+F12
  • Code Lens
  • New Blue Theme
  • UI Icons
  • Feedback & Notifications
  • Enhanced Scrollbar
  • Navigate To (Ctrl+,)
  • Auto Brace Complete
  • Move Line Up/ Down (Alt Arrow-Up/ Arrow-Down)
  • Minor Tweaks

Using Overloading method via Interface in C#.Net

Here the Example for Using Overloading method via Interface in C#.Net

Interface Name: IFamily
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FactoryPattern
{
    interface IFamily
    {
        string DisplayName(string str);
    }
}
Interface Name: IFamilyMember
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FactoryPattern
{
    interface IFamilyMembers
    {
        string DisplayFamilyMembers(string str);
        string DisplayName();

    }
}
ClassName: ClsFamily
Interface Name(s):IFamily ,IFamilyMembers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FactoryPattern
{
    class ClsFamily :IFamily ,IFamilyMembers
    {
        public string DisplayName(string str)
        {
            return str;
        }
        public string DisplayFamilyMembers(string str)
        {
            return str;
        }
        public string DisplayName()
        {
            return "Good";
        }
    }
}
Class Declaration and Call Methods
  ClsFamily obj = new ClsFamily();
   MessageBox.Show(obj.DisplayName("Naraayanan"));
   MessageBox.Show(obj.DisplayFamilyMembers("Naraayanan"));            MessageBox.Show(obj.DisplayName());


Visual Studio 2012 New Features

Visual Studio 2012 New Features


  • Dark Color Theme for code editor and IDE windows
  • Quick Launch – search the Visual Studio commands/menu options you need and locate it quickly
  • Pin Tabs(files) that you use often to the left side of the Tab-well
  • Search option in IDE windows
  • Find and Replace window changes
  • Preview Tab
  • Browser Drop Down
  • Create Multiple Solution Explorer Instances
  • Page Inspector
  • IIS Express replaces the ASP.NET Development server
  • HTML5 & CSS3 support
  • Unmodified Visual Studio 2010 project files
  • Single compact toolbar for common commands
  • Code Editor Enhancements
  • New Explorers: Solution, Test, Team and SQL
  • Expression Blend
  • LightSwitch



Visual Studio 2010 New Features


Visual Studio 2010 New Features
  • Multi-targeting Application Development
  • Faster Intellisense Support
  • Editor Zoom Functionality
  • Faster Assembly loading in “Add Reference”
  • Detach Window outside IDE
  • Reference Highlight
  • Faster Code Generation
  • Box Selection
  • Easy Navigation
  • Better Toolbox Support
  • Breakpoints
  • IntelliTrace
  • Hiding the Selected Part of Code
  • DataTips
  • String.IsNullOrWhiteSpace
  • Named and Optional Parameters
  • Highlighting
  • Intelligence Generated as Per Usage
  • Predictable
  • Inherit
  • ClientID Generation using ClientIDMode
  • Dynamic Language Support
  • URL Routing

Add and Remove a assembly from GAC

To install assembly in Cache use  Gacutil.
Goto "Visual Studio Command Prompt" and type "gacutil -i <assembly_name>", where (assembly_name) is the DLL name of the project.
To uninstall assembly, type gacutil –u <assembly name> in  Visual Studio Command Prompt.

Global Assembly Cache

While using shared assemblies, to avoid Assembly being overwritten by a different version of the same assembly , shared assemblies are placed in a special directory subtree in the file system, known as the global assembly cache (GAC).
Placing shared assemblies can be done by special .Net Utilities Only.

assembly version information stored

In the Manifest.

Assembly in Net

Define Assembly 
An assembly is a fundamental unit of any .NET application. It contains the code that is executed by CLR (common language runtime).
I would like to limit the details to what is required to create and use an assembly.
However, it is important to know a few details about assemblies before we delve into creating and using it.
An assembly contains name, version, types (classes and others) created in it and details about other assemblies it references.
An assembly may be either an executable file - .EXE or a dynamic link library - .DLL


Type of Assembly:

  1. Private Assembly
  2. Shared Assembly

Private Assembly:
By default every assembly is a private assembly.
If we add a reference to a private assembly to any project, a copy of the assembly is given to the project.
So each project maintains a private copy of the assembly.

Shared Assembly:
A shared assembly is an assembly that resides in a centralized location known as the GAC (Global Assembly Cache) and that provides resources to multiple applications.
If an assembly is shared then multiple copies will not be created even when used by multiple applications.

View an Assembly Information

By using  Ildasm.exe  which is an MSIL Disassembler one can view attributes,references to other modules and assemblies.

Define SOLID

SOLID are five basic principles which help to create good software architecture. SOLID is an acronym where:-


  • S stands for SRP (Single responsibility principle).
  • O stands for OCP (Open closed principle)
  • L stands for LSP (Liskov substitution principle)
  • I stands for ISP ( Interface segregation principle)
  • D stands for DIP ( Dependency inversion principle)

Solve First Chance Exception in .NET

You most likely see these messages in Immediate Window because you have set Redirect all Output Window text to the Immediate Window in Tools - Options... - Debugging - General. That's why when you right-click in Immediate Window, you cannot see any option to disable messages. It's Output Window text and thus you need to set it in the Output Window. So open Output Window, right-click and uncheck Exception Messages from context menu. Simple but it took me one hour to find it.

Define First Chance Exception in .NET

              When an application is being debugged, the debugger gets notified whenever an exception is encountered  At this point, the application is suspended and the debugger decides how to handle the exception. The first pass through this mechanism is called a "first chance" exception.
               In Visual Studio, you may see a message in the output window that looks like this:
              A first chance exception of type 'System.ApplicationException' occurred in myapp.exe
              First chance exception messages most often do not mean there is a problem in the code. For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled.

differences between UNION and JOINS

A join selects columns from 2 or more tables. A union selects rows.

difference between an XML "Fragment" and an XML "Document."

An XML fragment is an XML document with no single top-level root element. To put it simple it is a part
(fragment) of a well-formed xml document. (node) Where as a well-formed xml document must have only
one root element.

anchoring different from docking

Anchoring treats the component as having the absolute size and adjusts its location relative to the parent
form. Docking treats the component location as absolute and disregards the component size. So if a status
bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but
change its position with the form being resized, use anchoring.

create a separator in the Menu Designer

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

Define Lambda Expression With LINQ

LINQ queries can be written in two syntaxes:

  •  General Query Syntax
  •  Lambda Expression Syntax

Syn for Lambda Expression:
DataSource.Clause(DataAliasName => Expression)

difference between Move and LocationChanged? Resize and SizeChanged?

Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

Define Mandatory Clause in LINQ

1) from clause 2)in clause3) select clause

Define Clause in LINQ

1) from clause 2)in clause 3)let clause 4)where clause 5) orderby clause 6)select clause 7)group by clause

Define Thread life cycle

1.Ready: This is the initial state. The thread object is created.
2.Running: The thread is currently being executed.
3.Sleeping: The thread is temporarily paused. .NET framework offers automatic switching between ―Running and ―Sleeping states, when other threads are executed.
4.Suspended: The thread is temporarily suspended (paused). It will be continued, when you call ―Resume() method.
5. Dead: The thread was closed; it can‘t be restarted or continued.

Define FileStream

To write / read the content to / write the file, you require file streams.
 A file stream acts as a pointer for the file, which contains the memory address of the file on the disc.
 There are two types of file streams.
1) Reading Streams 2) Writing Streams
Using Namespace for FileStram

  • System.IO.StreamReader (to read the content of the file)
  • System.IO.StreamWriter (to write the content into the file)


Define “Random” class

Library: System.Random

  •  This class is used to generate a random number, at any time.
  •  In future, while performing different programming logics, this random number generation concept may be required.


Define Modifier

new : Methods only : The method hides a base class method with same signature.
static : All members : The member does not depends / instantiates with any of with its class‘s objects. It can be accessed with its class name.
virtual : Methods only :The member can be overridden by a derived class.
abstract :Classes and Methods only : The abstract class can‘t be instantiated. The abstract method is nothing but a virtual method that contains only declaration with no definition. It should be implemented with override keyword in the derived class.
override : Methods only : The member overrides an inherited virtual or abstract member of the base class.
sealed  : Classes  only :The class can‘t be inherited.

Define Types of Inheritance

1) Single Inheritance
  This is the simplest type of inheritance.
  An inheritance relationship, with only one super class and one sub class.
2) Hierarchical Inheritance
 An inheritance relationship, with only one super class and multiple sub classes.
3) Multi-Level Inheritance
  An inheritance relationship, with only one super class and multiple sub classes, and also extended with another sub class from the first sub class.
  In other words, one class acts as super class and sub class simultaneously.
4) Multiple Inheritance
  An inheritance relationship,with only multiple super classes and only one sub class.
  Multiple Implementation Inheritance is not supported by C#, but Multiple Interface Inheritance is supported by C#.
5) Hybrid Inheritance
   An inheritance relationship that contains a combination of any other two types of inheritances.

Define Classification of Inheritance supported by C#:

1) Implementation Inheritance:

  •  This is commonly used inheritance.
  •  Whenever a class is derived from another class, it can be called as ―Implementation Inheritance.
  •  As said above, all of the members of the super class are adopted by sub class.

2) Interface Inheritance:

  •  This type of inheritance is taken from ―Java.
  •  Whenever a class is derived from an interface, it can be called as ―Interface Inheritance.
  •  The interface is similar to the class, but doesn‘t contain the method definitions; it contains the method declarations only. We discuss about the interfaces in-depth later.


Define Indexer in C#.net

This is used to access the object like an array.
Syntax: object[index]
           When you use the above syntax, a field can be accessed.
Syntax for Indexer:
public datatype this[int index]
{
get
{
return arrayname[index];
}
set
{
arrayname[index] = value;
}
}

Define Auto Implemented Properties

This is introduced in C#.NET 3.0.

  •  To simplify the syntax of property declaration that contains no extra logic in ―set accessor and ―get accessor, this concept is introduced.
  •  According to this, no code for ―set and ―get accessors needed to write.
  •  No extra variable is needed to be declared.
  •  Syn: accessmodifier datatype propertyname { get; set; }
  •  Ex: public string Name { get; set; }


Define Write Property in C#.net

Simply implement ―set accessor only, don‘t implement ―get accessor.
 Syn:
private datatype variablename;
accessmodifier datatype propertyname
{
set
{
variablename = value;
}
}

Define Read only Property in C#.net

Simply implement 
         get accessor only, don‘t implement ―set accessor.
 Syn:
private datatype variablename;
accessmodifier datatype propertyname
{
get
{
return (variablename);
}
}

Define Set and Get Accessor in Property

The “Set” Accessor:
1. This gets called automatically, whenever a value is assigned to the property in the client code. Ex: obj.property = value;
2. The value that is assigned in the client code is available as ―implicit parameter,named value in this set accessor.
3. This accessor can‘t return any value.
The “Get” Accessor:
1. This gets called automatically, whenever the property value is requested in the client code. Ex: obj.property
2. No implicit parameters are available.
3. This accessor should return the value of the property.

Define Types of Generics

 Generic Classes: 
            The generic represents a data type, during the object‘s life time of the class.
 Generic Methods: 
           The generic represents a data type, during the method execution.

Define Generics


  • Generics are similar to ―templates in C++.
  •  A generic is an identifier, which automatically identifies the data type of a variable.
  •  This is designed to represent a particular data type, during an object life time or a method execution.

 Two types of generics. 

  •  Representing a data type during an object life time.
  •  Representing a data type during the method execution time.


Define rules of Destructor


  • Its name must be defined as class name.
  •  It' name must be started with "~" character.
  •  Access modifier can‘t be specified for this.
  •  No arguments.
  •  No return value.
  •  Destructor overloading is not possible. That means multiple destructors can't be defined inside of a class.


Define Types of Constructors

Implicit constructor:

  •  A constructor, offered by the compiler implicitly is called as "Implicit constructor".
  •  But the compiler automatically offers an implicit constructor, for "constructor-less class" only.

Explicit constructor:

  •  A constructor, defined by the programmer.
  •  It always overrides the implicit constructor.


Define rules of Constructors


  • Its name must be same as "classname".
  •  It must be defined as "public method".
  •  It can be defined with/without arguments.
  •  It can't return any value. So, no return type specification is required.
  • "Constructor overloading" is possible. Writing multiple constructors in the same class is called as "Constructor overloading".

Define “this” Keyword

This is similar to ―this pointer in C++.
 It represents current working object.
 It is used to access the members of current working object.

  • this.field
  • this.property
  • this.method()

Current object: The object, with which object, the method is called.
this” keyword can‘t be used in the static methods, because static methods doesn‘t have current object.

Define Variable Scopes


  •  A variable scope simply is something, which decides the lifetime of the variable.
  •  The variable scope depends on the place, where the variable is declared in the program.

 For example,
     a variable is declared in if block, is available only within the if block itself.  To have a better idea on this, we discuss about all available scopes in C#.

Define Variables

 Variable declaration:
Syn: datatype variable;
Ex: int x;
Variable declaration along with initialization:
Syn: datatype variable=value;
Ex: int x=10;
Multiple Variable declaration:
Syn: datatype variable1, variable2, variable3,…;
Ex: int x,y,z;
Note:
     When we declare any variable, it should be assigned to a value before its usage.Otherwise, it causes a compile time error.

Define string[] args

   To receive the command like arguments. A command line argument is nothing but an argument, which can be passed from the command window, before the application execution is started.

Define void

It can‘t return any value unlike other methods. So that, it should be defined with void keyword.

Define Memory Manager

 The Memory Manager component of CLR, allocates necessary memory for the variables and objects that are to be used by the application.

Define Exception Manager


  •  An exception means Run time error.
  •  This component redirect the processor to execute the catch block or finally block,whenever an exception is occurred at run time.
  •  We can learn how to write these catch and finally blocks in C#.NET and VB.NET languages later.


Define .NET Framework Types

The .NET Framework is available in 3 different types:
 .NET Framework: 
         This is the general version, required to run .NET applications on Windows operating system.
 .NET Mono Framework: 
         This is required to run .NET applications on other operating systems like UNIX, LINUX and Solaris etc.
 .NET Compact Framework:
            This is required to run .NET applications on other devices like PDA (Personal Digital Assistants), Mobile phones and Smart phones.

Define Web Services

Web Services

  •  Web Services are simple and easy to understand.
  •  These can be developed using again ASP.NET.
  •  The web services are used to implement SOA(Service Oriented Architecture) in web applications.
  •  The main purpose of SOA is to implement some interaction between two applications.
  •  Examples:
  •   Online shopping requires credit card authentication, from back web site.

Modules of .NET

VC#.NET (Visual C Sharp.NET) –(Language)

  •  It is highly used .NET programming language, used by most of the .NET programmers.
  •  It borrows some programming features from C and some other programming features from C++. In addition to these, it borrows few of the good features of java language.
  •  It is the object oriented programming language.

VB.NET (Visual Basic.NET) –(Language)

  •  It is the Microsoft‘s recommended language for beginners of windows programming.
  •  But in fact, it is used in very few of the projects in the real-time development world, because most of the programmers usually comes with C and C++ background; hence they feel comfortable with C#.
  •  It borrows some programming features from VB (Visual Basic) language.
  •  It is the object oriented programming language.

ASP.NET (Active Server Pages.NET) – (Web Technology)

  •  It is the Microsoft‘s web technology.
  •  It is used for web sites development.
  •  It offers much attractive and user friendly user interfaces in the server side applications.
  •  It is the new version to another Microsoft‘s technology called ASP (Active Server Pages), which is a famous web technology before introducing ASP.NET.
  •  It requires HTML for web page designing.
  •  It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for server side logic implementation.

ADO.NET (ActiveX Data Objects.NET) – (Database Technology)

  •  It is the Microsoft‘s database technology.
  •  It offers necessary programming libraries to access the local / server databases.
  •  It is the new version to another Microsoft‘s technology called ADO (ActiveX Data Objects), which is a famous database technology, used with VB, VC++ and ASP languages.
  •  It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for logic implementation.


Languages Supported by .NET Framework

Languages from Microsoft : Visual C#.NET,Visual Basic.NET,Visual C++.NET
Languages from other vendors:
VJ#.NET,Python.NET,IronPython.NET,APL.NET,Cobol.NET,Perl.NET,Pascal.NET,Component Pascal.NET,Curriculum.NET,Eiffel.NET,Forth.NET,Fortran.NET,Haskell.NET,Mercury.NET,Mondrian.NET,Oberon.NET,RPG.NET,Scheme.NET,Small Talk.NET,Standard ML.NET

Get Total Quantity from Datagridview in C#.NET

Today , we will see "Get Total from Quantity Column in DataGridView in C#.Net"

Code
private double ADDCoulmnValue(int ColIdx, DataGridView dgv) { for (int idx = 0;idx <dgv.Rows.Count;idx++)
{ tot += Convert.ToDouble(dgv.Rows[idx].Cells[ColIdx].Value);
} }
     

Microsoft Team Foundation Server

Microsoft Team Foundation Server- TFS Source Control System
Its some kind of tool like SVN/GIT etc source version control system.But, version control is only a part of this.Team foundation server(in short, TFS), is a great innovation of Microsoft,that is integrated with Visual Studio and provide a easy/effective way to manage a software development project completely.
Installing:
If you are using visual studio 2008, then you must need to have service pack 1 installed before you can install team foundation client software.
you can download the team system client for vs 2008 from this microsoft download link.
If you are a visual studio 2010 user, then you won’t have to do anything and its already a part of visual studio 2010.
Configuring:
         First we will have to connect to TFS server and setup the initials.
        On visual studio menu, you should see a menu named ‘Team’, which will include only one option titled ‘Connect To Team Foundation Server’.From here, you will get an ‘Connect To Team Project’ dialogue.
This originally contains the listing of team projects on a selected server. As we don’t have any server configured, there will be nothing here at this moment.
Click on the ‘Servers’ button.
         Here, you can provide the url, port, extra uri path,protocol(http/https). However, instead of giving individual details, if you give a complete url that contains all info, will work also. This can be like “http://yourtfsserver.com:8080/uripath”.
           After you have added the server. select it on “Connect to Team Project” dialogue.
Now, select proper ‘Project Collection’ and then select your specific project.Then you should be prompt to select a local pc directory where you wish to save all the files.it will perform a complete ‘checkout’ operation that will download all latest files from the server.
Browse Server Contents:
           There are two windows to get you see the server files.
           First, On ‘View -> Team Explorer’ you will see the team foundation server’s all items like Work       Items,Documents,Reports,Builds and Source Control.The main concern for us at this moment is to use the ‘Source Control’ part.If you click on that option, you will get to another new window, which actually shows you all server files inside your team foundation server project.
Adding/Deleting Files/Directories To Source Control:
            You should be able to see some options on the top bar of source control explorer window.
Similar options will be found if you right click of your mouse inside the area.
To add one/more file(s)(or directories), just use the ‘Add Items To Folder’ option to do so. Here,
I want to add a suggestion that, although you will be able to select files from other directories as well,it will be best to, first add items to your local file system (relatively) where you want them to be placed on server. then add the add option on source control explorer to add them from there.
           After you perform the addition, those files/directories won’t be committed to server yet.
You will then have to perform another operation named ‘Check In Pending Changes’ to add them permanently to tfs server(its similar to the commit option on SVN).
          Similarly you can delete files/folders from server using the ‘delete’ option and then finally checking in the pending changes.Here, just to mention, remove something using the source control explorer will not necessarily remove them from your local file system.You can do it manually.
Edit File:
          To Edit a file, you should first use the option ‘Checkout for edit’ to acknowledge server that you are going to edit this file.This will be notified to other developers also and they will see this in edit mode through source control explorer.Also, until you checkout a file for edit, files will be in ‘read only’ mode.
As a result, you won’t be able to edit it externally(However its still possible to do so from within visual studio).
So, checking out for edit is kind of must for binary files(like doc file etc) at least.
Also, if you edit a file in offline mode(not connected to tfs server), it will detect the edited files and will convert them to ‘edit’ mode after you get to online.
Merging And Branching:
           TFS has merging and branching facility as well.If your local version doesn’t fit with server version, in short, if any conflicts occurs, you can either manually merge them in merge tool or you can command tfs to do auto merge(you will only get this option if TFS thinks that it can be merged automatically).
            If you have to work on several files and all are related to a single feature, its best to create a branch of the project or code file(s) and work on them. After finishing your task. you can again use the TFS merge command with the main branch and it will automatically incorporate those changes itself.Finally, you will have to commit as well.
Shelve Set:
         If you are a earlier SVN user, then you may be new to this term.Team foundation server has this feature, which allows you to save your local edit as a separate item in server,which can be retrieved and reviewed by other developers of your team. After approval suggestions, it can be deleted or check in to the main version control stream.
Refer

Create Constructor in VB.Net

This is code for Constructor in VB.Net
private idx As Integer
    Public Sub Class1(ByVal id As Integer)
        Me.idx = id
    End Sub

.NET Framework Application Essentials


  • Working with Base Types
  • Collections and Data Structures
  • Generics in the .NET Framework
  • Handling and Raising Events
  • Handling and Throwing Exceptions
  • File and Stream I/O
  • Dates, Times, and Time Zones
  • Programming with Application Domains and Assemblies
  • Serialization [from BPUEDev11]
  • Resources in Desktop Apps
  • Globalizing and Localizing .NET Framework Applications
  • Accessibility
  • Extending Metadata Using Attributes
  • 64-bit Applications


Override ToString Method in VB.Net

This is a Example for Override ToString Method in VB.Net

Public Class Class1
    Public idx As Integer
    Public Overrides Function ToString() As String
        Return Me.idx.ToString() + " " + "VB.Net"
    End Function
End Class
Paste this following code in your main form  
        Dim cl As Class1 = New Class1
        cl.idx = 100
        MessageBox.Show(cl.ToString())
Result:
100 VB.Net

Override ToString Method in C#.Net

This is a Example for Override ToString Method in C#.Net

To Create a Class File for Convert a integer into string

        private int idx;
        public Class1(int idxs)
        {
            this.idx = idxs;
        }
        public override string ToString()
        {
            return this.idx.ToString() + " " + "Good";
        }
Paste this following code in your main form
   Class1 cls = new Class1(10);
            MessageBox.Show(cls.ToString());

Output:
10 Good

Aware of the Body Language you should know before your next job interview

Aware of the Body Language you should know before your next job interview
Here are 11 basic facts on body language which might help you a lot while preparing yourself for job interviews.
Most of us aren't aware of our body language, especially when we're in a stressful situation — but interviewers are trained to read it.
It is important to have body awareness before you go into an interview, In fact, there are many actions and habits that we should consider doing or avoid doing to tell the right story during the interview setting.
1. Feel good about your wardrobe and wear clothes that 'show you in your best lighting'.
2. Place your feet on the floor.
3. Sit still or you'll come off as a nervous person.
4. Place your hands on your knees.
5. Sit a bit forward to show that you're interested and serious about the interview.
6. Folding your arms will make you seem unfriendly.
7. Playing with your hair or cracking your knuckles can be extremely distracting to your interviewer.
8. Putting your hands in your pockets makes you look 'messy'
9. Don't invade the interviewer's space and keep your hands and body parts on your side of the desk
10. Use props to help you look more comfortable
11. Staring will make you look too intense and unnatural.
In a conversation, never fully lock eyes with people. Bentley said. We talk, we look people in the eyes, we have a thought, and we look away. We look to the right, and we look to the left. When you start staring at them, you start "to look a little crazy. If you feel like you are looking the person in the eye too long, hold it one more second and break away.
The above are only a few basic tips on body language "Do's and Don'ts" for a job interview. You can easily acquire them if you take a little conscious step ahead.
Hope, you enjoyed reading this post.
Have a great day

From FB.

Add DataGridView Column Value in C#.net

Today, we will discuss about Add DataGridView Column Value in C#.net
private double  ADDCoulmnValue(int ColIdx, DataGridView dgv)
        {
            double d = 0;
            for (int idx = 0;idx <dgv.Rows.Count;idx++)
            {
                tot += Convert.ToDouble(dgv.Rows[idx].Cells[ColIdx].Value);
            }
            return tot;
        }

Add DataGridView Column Value in VB.Net

Today,We will see "How to Add DataGridView Column Value in VB.NET?"
Private Function ADDCoulmnValue(ColIdx As Integer, dgv As DataGridView) As Double Dim d As Double = 0 For idx As Integer = 0 To dgv.Rows.Count - 1 tot += Convert.ToDouble(dgv.Rows(idx).Cells(ColIdx).Value) Next Return tot End Function

Fetch Text File data into Datagridview in VB.Net

Today we will see Fetch Text file Data into Datagridview in VB.net
Text file Data Format
111;222
333;444
555;666
777;888
Code:
private Sub DispaydatafromTextFile(txtFilePath As String) '1st you must create columns to dgv, like: dataGridView1.Columns.Add("col1", "Column1") dataGridView1.Columns.Add("col2", "Column2") 'and so on... Using sr As New StreamReader(txtFilePath) Dim row As Integer = 0 Dim line As String While (InlineAssignHelper(line, sr.ReadLine())) IsNot Nothing Dim columns As String() = line.Split(";"C) dataGridView1.Rows.Add() For i As Integer = 0 To columns.Length - 1 dataGridView1(i, row).Value = columns(i) Next row += 1 End While End Using End Sub
Private Sub button1_Click(sender As Object, e As EventArgs) DispaydatafromTextFile("C:\Test.txt") textBox1.Text = Convert.ToString(dataGridView1.CurrentRow.Cells(0).Value) textBox2.Text = Convert.ToString(dataGridView1.CurrentRow.Cells(1).Value) End Sub
Private Sub dataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) textBox1.Text = Convert.ToString(dataGridView1.Rows(e.RowIndex).Cells(0).Value) textBox2.Text = Convert.ToString(dataGridView1.Rows(e.RowIndex).Cells(1).Value) End Sub

Fetch Text File Data into Datagridview in C#.Net

Today ,we will discuss about how to fetch data from Text File into Datagridview in C#.net
Text File Data Format
111;222
333;444
555;666
777;888
Code 
private void DispaydatafromTextFile(string txtFilePath)
 {
 //1st you must create columns to dgv, like:
 dataGridView1.Columns.Add("col1", "Column1");
 dataGridView1.Columns.Add("col2", "Column2");
 //and so on...
 using (StreamReader sr = new StreamReader(txtFilePath))
 {
 int row = 0;
 string line;
 while ((line = sr.ReadLine()) != null)
 {
 string[] columns = line.Split(';');
 dataGridView1.Rows.Add();
 for (int i = 0; i < columns.Length; i++)
 {
 dataGridView1[i, row].Value = columns[i];
 }
 row++;
 }
 }
 }
 private void button1_Click(object sender, EventArgs e)
 {
 DispaydatafromTextFile(@"C:\Test.txt");
 textBox1.Text = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value);
 textBox2.Text = Convert.ToString(dataGridView1.CurrentRow.Cells[1].Value);
 }
 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
 {
 textBox1.Text = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
 textBox2.Text = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[1].Value);
 }

Find existing Item in ComboBox in C#.net

Today we will see "Find Existing Item in ComboBox in C#.net"

Code
private void ComboBox1_Leave(System.Object sender, System.EventArgs e)
{
int resultIndex = -1;
resultIndex = ComboBox1.FindStringExact(ComboBox1.Text);
if (resultIndex > -1) {
MessageBox.Show("Found It");
}
else
{
MessageBox.Show("Did Not Find It");
}
}

Find existing item in ComboBox in Vb.net

Today we will discuss about Find existing item in Combobox in VB.Net

Private Sub ComboBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.Leave
Dim resultIndex As Integer = -1
resultIndex = ComboBox1.FindStringExact(ComboBox1.Text)
If resultIndex > -1 Then
MessageBox.Show("Found It")
Else
MessageBox.Show("Did Not Find It")
End If
End Sub

Define ViewBag in MVC

Define ViewBag in MVC
ViewBag is used to pass data from a controller to the view.ViewBag object holds the data.

Define Helper Classes

Define Helper Classes
There are several Helper classes in MVC frame work. 
1.Form Helper- Radio buttons, textboxes,list boxes etc.
2.URL helpers
3.HTML helpers- Encode, Decode, AttributeEncode, and RenderPartial.

Define Non-Action Methods

Define Non-Action Methods

  • All action methods in a Controller are defined as public method.
  •  If you want some method as non action method,mark the method with NonAction Attribute.

Define Action Methods Parameters

Define Action Methods Parameters

  • Request and Response methods can be called from the action method of the controller.
  • If the parameter to an action method is passing through the URL, there are several ways to access it into our action method.

Define MVC Attributes

Define MVC Attributes

  1. Attribute is a class which inherites from the abstract class System.Attribute.
  2. All attributes should end with the name "Attribute".

Define ActionResult Return Type

Define ActionResult Return Type

  1. Creating new controllers, they will come with one or more actions by default.
  2.  The Empty controller includes an Index action with a return value of type ActionResult.
  3.  ActionResult class is the base class for all action results.

Define Action methods

Define Action methods

  • User gives request to the controller via URL. 
  •  The Controller processes the requests using the action methods defined by the Controller. 

Define Types of Action Filters

Define Types of Action Filters
1. Authorization filters 
       Implements the IAuthorizationFilter attribute. This filter is always executed first. 
2. Action filters
       Implements the IActionFilter attribute. You can use this filter to modify the viewdata that an action returns.
3. Result filters 
       Implements the IResultFilter attribute. Eg You might want to modify the view result before view is redered to the browser.
4. Exception filters
       Implements the IExceptionFilter attribute. Can be used to log errors, raised by your controller action or controller action results.

Use Row_number() in SQL Server

SQL Scenario -I

Table A Table B
Id Id
1 1
2 -
- 3
4 4
Expected Output:
Id Description
1 1 Has both in tables
2 2 Has in A table Only
3 3 Has in B table Only

4 4 Has both in tables.

create view UV_Result
as
select a.id,a.id + '  ' + 'Has both in tables' as [DESCRIPTION] from table1 a,table2 b where a.id=b.id and a.id<>'-'

Create view UV_TestA
as
select Distinct id as [TableAID],
      RowNum = row_number() OVER (ORDER BY (SELECT 0))
from  table1 a
   
Create view UV_TestB
as
 select   id,
     RowNum = row_number() OVER (ORDER BY (SELECT 0))
from     table2


create view uv_Final
as
select id,DESCRIPTION from UV_Result
union ALL
select rownum,CONVERT(varchar(50),CONVERT(bigint,rownum)) +' ' + 'HAS TABLE B'  from UV_TestA where TableAId='-'
UNION ALL
select rownum,CONVERT(varchar(50),CONVERT(bigint,rownum)) +' ' + 'HAS TABLE A'  from UV_TestB where Id='-'

select * from uv_Final order by id

Define MVC Action Filters

Define MVC Action Filters
Action Filters are used in cases where we need to perform some logic either before an action method is called or after an action method runs.

Use of System.XML.XLINQ

It contains classes to provide functionality to LINQToXML

Use of System.Data.DLINQ

Provide functionality to Work with LINQToSQL.

Qualifiers in LINQ

They are LINQ Extension Methods return Boolean Value.

  1. All
  2. Any
  3. Contains
  4. SquenceEqual



Main Components in LINQ

There are three Main Components in LINQ

  1.  Standard Query Operator
  2.  Language Extension
  3.  LINQ Provider

add Minutes to DateTime in Sql Server

We can use DATEADD() function like below to add minutes to DateTime in Sql Server. DATEADD() functions first parameter value can be minute or mi or n all will return the same result. Below example shows how we can add two minutes to Current DateTime in Sql Server:

SELECT GETDATE() 'Now',
           DATEADD(minute,2,GETDATE()) 'Now + 2 Minutes'
SELECT GETDATE() 'Now',
           DATEADD(mi,2,GETDATE()) 'Now + 2 Minutes'
SELECT GETDATE() 'Now',
           DATEADD(n,2,GETDATE()) 'Now + 2 Minutes'

add Hours to DateTime in Sql Server

                We can use DATEADD() function like below to add hours to DateTime in Sql Server.                
                DATEADD() functions first parameter value can be hour or hh all will return the same result. Below example shows how we can add two hours to Current DateTime in Sql Server:

SELECT GETDATE() 'Now',
           DATEADD(hour,2,GETDATE()) 'Now + 2 Hours'
SELECT GETDATE() 'Now',
           DATEADD(hh,2,GETDATE()) 'Now + 2 Hours'