RSS

Read XML Data for datasource

<?xml version=”1.0″ encoding=”utf-8″ ?>
<StatusTypes>
<StatusType Name =”All” value=”0″/>
<StatusType Name =”Over-vote” value=”1″/>
<StatusType Name =”Mixed Status” value=”2″/>
<StatusType Name =”Not Received” value=”3″/>
<StatusType Name =”Over Reported” value=”4″/>
<StatusType Name =”Under Reported” value=”5″/>
<StatusType Name =”In Balance” value=”6″/>
</StatusTypes>

string fullName = HttpContext.Current.Server.MapPath(
“~/Modules/Pxy/StatusDataSource.xml”);
XDocument doc = XDocument.Load(fullName);
return (from d in doc.Root.Elements(“StatusType”)
select new KeyValuePair<string,int>( d.Attribute(“Name”).Value, int.Parse( d.Attribute(“value”).Value))
)
.ToList();

statusDataSource DataSource = new statusDataSource();
if (ddlStatus.Items.Count > 0)
ddlStatus.Items.Clear();

ddlStatus.DataSource = null;
foreach (KeyValuePair<string, int> St in DataSource.Status)
ddlStatus.Items.Add(new ListItem(St.Key, St.Value.ToString()));

 
Leave a comment

Posted by on February 5, 2016 in .NET

 

Shadowing in C#

  • In Method override  both methods (base class method and child class method) have the same name, same number and same type of parameter in the same order with the same return type. The overridden base method must be virtual, abstract or override
  • but without these we can do using new keyword., this mechanism is called Shadowing
  • In the shadowing or method hiding, the child class has its own version of the function, the same function is also available in the base class.
  • Using this concept we can provide a new implementation for the base class method without overriding it.
  • Showing is used to protect against subsequent base class modification, We can change the access modifier
  • There is no control of a base class on shadowing
  • We can also use shadowing and method overriding together using the virtual and new keywords
Public class BaseClass 
{ 
    public string GetMethodOwnerName() 
    { 
        return "Base Class"; 
    } 
} 
public class ChildClass : BaseClass
{
    public new virtual string GetMethodOwnerName()
    {
        return "ChildClass";
    }
}
public class SecondChild : ChildClass
{
    public override string GetMethodOwnerName()
    {
        return "Second level Child";
    }
} 

static void Main(string[] args) 
{ 
    ChildClass c = new ChildClass(); 
    Console.WriteLine(c.GetMethodOwnerName()); 
}

Output: ChildClass

We cannot use the new and override keywords together. If you do then the compiler throws a compilation error

Shadowing  Example (using new keyword in child class method)

static void Main(string[] args) 
{ 
    BaseClass c = new ChildClass(); 
    Console.WriteLine(c.GetMethodOwnerName()); 
}

Output

Shadow

In overriding, the base class can be accessed using the child object’s overridden method.

Overriding Example (using override keyword in child class method)

static void Main(string[] args) 
{ 
    BaseClass c = new ChildClass(); 
    Console.WriteLine(c.GetMethodOwnerName()); 
}

Output

Overriding

 

 
Leave a comment

Posted by on October 7, 2015 in .NET

 

ref vs out in C#

While writing a code, we often come across situations where we need to return multiple values from a single function/method. But a method can only return a single value.The question is how do we overcome such situation.Answer is simple, use reference types.

Parameters are always passed by value to a method by default.If we want to pass them by reference then we can use either out or ref keyword.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Ref keyword will pass parameter as a reference this means when the value of parameter is changed in called method it get reflected in calling method also. There is no “boxing” when a value type is passed by reference

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method

public ActionResult Index()
{
    int val1 = 0; //must be initialized for ref
    int val2 = 0; //optional for out
    Example1(ref val1);
    ViewBag.Message += val1 + "\n"; // val1=0
    Example2(out val2);
    ViewBag.Message += val2 + "\n"; // val1=2
    return View();
}
static void Example1(ref int value) //called method
{
    //value = 1; // optional
}
static void Example2(out int value) //called method
{
    value = 2; //must to assign value
}

These ref and out parameters are useful whenever your method wants to return more than one value.

Both the method definition and the calling method must explicitly use the ref / out keyword

Several inbuilt methods as “TryParse” (one of my favourite) use out and not ref, may be the internal implementation of library mainly uses ref.

Properties/Indexers/Dynamic member access cannot be passed to ref or out parameters since internally they are functions/methods and not members/variables

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

Ref and out in method overloading

Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn’t differentiates between the two while it created IL for ref and out). Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.

class MyClass
{
   public void Method(out int a) // compiler error “cannot define overloaded”
   {
       // method that differ only on ref and out"
   }
   public void Method(ref int a)
   {
       // method that differ only on ref and out"
   }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
          public void Method(int a)
          {
          }
          public void Method(out int a)
          {
                   // method differ in signature.
          }
}

Ex:

public static void Foo()
{
      int val = 0;
      Example1(val);
      Console.WriteLine(val); // Still 0!
      Example2(ref val);
      Console.WriteLine(val); // Now 2!
      Example3(out val);
      Console.WriteLine(val); // Now 3!
}

static void Example1(int value)
{
      value = 1;
}
static void Example2(ref int value)
{
      value = 2;
}
static void Example3(out int value)
{
      value = 3;
}
Ref Out
The parameter or argument must be initialized first before it is passed to ref. It is not compulsory to initialize a parameter or argument before it is passed to an out.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method. A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter. Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
It is not compulsory to initialize a parameter value before using it in a calling method. A parameter value must be initialized within the calling method before its use.
When we use REF, data can be passed bi-directionally. When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.

The out and ref keywords are useful when we want to return a value in the same variables as are passed as an argument

 
Leave a comment

Posted by on September 10, 2015 in .NET

 

.js vs .min.js

They are both the same functionally but the .min one has all unnecessary characters (whitespaces and comments stripped out, shorter variable names, …)  removed in order to make the file size smaller.

Just to point out as well, you are better using the minified version (.min) for your live environment as Google are now checking on page loading times. Having all your JS file minified means they will load faster and will score you more brownie points.

 
Leave a comment

Posted by on September 9, 2015 in .NET

 

Extension Methods in C#.Net

  • Extension methods are a new feature in C# 3.0
  • You can use extension methods to extend a class or interface, but not to override them.
  • Extension methods are static methods of a static class, and the 1st parameter is preceded by the “this” modifier (refers to class/interface/the called value), 2nd onward parameters act as passing parameters as in normal method calling
  • you need to add the “using System.Linq” directive to the top of the code
  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code
  • If the class is sealed than there in no concept of extending its functionality
  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class’s design
  • An extension method must be defined in a top-level static class
  • An extension method is defined as static method but it is called like as instance method
  • Overuse of extension methods is not a good style of programming

Ex: standard and with Multiple Parameters

public static class MyExtensions
{
      static int WordCount(this String str, char[] charArray)
      {
             return str.Split(charArray, 
                        StringSplitOptions.RemoveEmptyEntries).Length;
      }
}

And it can be called from an application by using this syntax:

string str = "Hello Extension Methods";
int i = str.WordCount(new char[] { ' ', '.', '?' });

Extension methods at compile time:

An extension method with the same name and signature as an interface or class method (1st priority) will never be called.

Inherit the class and then implement the functionality in an instance method in the derived class

Use aggregation instead of inheritance.

Aggregation example:

university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.

Ex1: with Interface

public interface IMyInterface
{
        // Any class that implements IMyInterface must define a method 
        // that matches the following signature. 
        void MethodB();
}
public static class Extension
{
    public static void MethodA(this IMyInterface myInterface, int i)
    {
         Console.WriteLine
             ("Extension.MethodA(this IMyInterface myInterface, int i)");
    }
}
public class A : IMyInterface
{
      public void MethodB() { Console.WriteLine("A.MethodB()"); }
}
class ExtMethodDemo
{
    static void Main(string[] args)
    {
        A a = new A(); // Declare an instance of class A
        a.MethodA(1);  //A contains no MethodA, 
        //so it calls the extension method that has a matching signature.
    }
}

Output:

    Extension.MethodA(this IMyInterface myInterface, int i)

Ex2: with class

public class Class1
     {
         public string Display()
         {
             return ("I m in Display");
         }
 
         public string Print()
         {
             return ("I m in Print");
         }
     }
public static class XX
     {
          public static void NewMethod(this Class1 ob)
         {
             Console.WriteLine("Hello I m extended method");
         }
     }
class Program
     {
         static void Main(string[] args)
         {
             Class1 ob = new Class1();
             ob.Display();
             ob.Print();
             ob.NewMethod();
             Console.ReadKey();
         }
     }
 }

Output:

I m in Display
I m in Print
Hello I m extension method

The compiler doesn’t cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.

One of the great reasons for Extension methods is behind LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure

The biggest disadvantage is that there’s no compiler error or warning if you have a regular method and an extension method with the same signature in the same context.

If you create an extension method applying to a particular class. Then later someone creates a method with an identical signature on that class itself.

Your code will compile, and you may not even get a runtime error. But you’re no longer running the same code as before

Extension methods fit very well into an OOP design: consider the simple method

bool empty = String.IsNullOrEmpty (myString)

in comparison to

bool empty = myString.IsNullOrEmpty ();

Ex3: With Multiple parameters in Extension Method

class Program
{
    static void Main(string[] args)
    {
       List<Product> Products = new List<Product>()
       {
            new Product{ProductName = "White Shoe", ProductPrice = 10},
            new Product{ProductName = "Green Shoe", ProductPrice = 5},
            new Product{ProductName = "Black Shoe", ProductPrice = 15}
       };
 
       foreach (Product p in Products)
       {
             Console.WriteLine("{0} costs {1} (VAT: {2})", 
                 p.ProductName, p.ProductPrice, p.CalculateVat());
       }
    }
 }
public static class MyExtensions
{
      public static double CalculateVat(this Product p)
      {
            return (p.ProductPrice * .25);
      }
}
public class Product
{
    public string ProductName { get; set; }
    public double ProductPrice { get; set; }
}

However, you do not own or have control over the Product class since it is owned by someone else. So you can’t add a CalculateVat() method to the product class, And it can be done by using EXTENSION METHODS.

 
Leave a comment

Posted by on September 9, 2015 in .NET, C#.net

 

.xlsx sheet data to datatable in C#

using System.Data.OleDb;

string qry = “Select * from [Sheet1$]”;

string excelConnectionString = @”Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” + _xlsheet_filepath + “;Extended Properties=\”Excel 12.0;HDR=YES;\”;Persist Security Info=False”;
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();

DataTable dt = new DataTable();
OleDbDataAdapter exDA = new OleDbDataAdapter(qry, excelConnection);
exDA.Fill(dt);
excelConnection.Close();

 
Leave a comment

Posted by on August 24, 2015 in .NET

 

Search a column in a table

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE ‘%_ColumnName%’
ORDER BY schema_name, table_name

 
Leave a comment

Posted by on August 18, 2015 in SQL SERVER

 
 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: