Tuesday, 2 September 2014

Difference between Object Vs Var Vs Dynamic Keyword

Object Vs Var Vs Dynamic Keyword
So right now in C# we have the Object class, and the var and dynamic types. At first look, they all seem to do the same job, but not really.

Then the question is, what is the difference between Object, var and dynamic? And when should we use them?

So here is the answer.

Object

The object class in C# represents the System.Object type, which is the root type in the C# class hierarchy. Generally we use this class when we cannot specify the object type at compile time, which generally happens, when we deal with interoperability.

Let's have an example. The following example explains that the variable amount, of which the type is object, but at run time we can get the actual type of that variable that is stored in the variable.


Object.jpg

Let's perform a mathematical operation on it.

Object1.jpg

Why are we unable to perform a mathematical operation on it and instead get an error message but in the previous example we get the type of Amount as System.Int32. If the amount is a Systme.Int32 type and we can store an integer value in it then why are we unable to apply a simple mathematical operation?

Here is the reason. Actually, an object requires explicit type conversion before it can be used. We can store anything in the object type variable but for performing an operation we must type cast it. Because C# is a statically typed language so it will throw an exception when we start performing any operation on it without proper type casting.

Object2.jpg

Var

The var type was introduced in C# 3.0. It is used for implicitly typed local variables and for anonymous types. The var keyword is generally used with LINQ.

When we declare a variable as a var type, the variable's type is inferred from the initialization string at compile time.

Object3.jpg

We cannot change the type of these variables at runtime. If the compiler can't infer the type, it produces a compilation error.

Object4.jpg

Dynamic

The dynamic type was introduced in C# 4.0. The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only.

Object5.jpg

In the code above we are assigning various types of values in the variable amount because its type is dynamic and dynamic delays determination of the type until execution. All dynamic types variables enjoy the party at runtime.


Sunday, 31 August 2014

Serialization and Types of Serialization in C#.Net

Serialization:

1.Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache.

2.Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily.

Advantage:

Using serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format.

Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.

De-serialization is the reverse; it is the process of reconstructing the same object later.



Types of Serialization

Serialization can be of the following types:

1.Binary Serialization
2.SOAP Serialization
3.XML Serialization

Binary Serialization:

Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically. The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.

Difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not. In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved.

Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object


The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures. In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application. The basic advantage of SOAP serialization is portability. The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message.

XML Serialization:

· According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document.

· XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform." Implementing XML Serialization in .Net is quite simple.

Friday, 2 November 2012

How to highlight text using JQuery


Introduction

                It is common to highlight the searched text, to grab the attention to the searched text. Today I will be explain how to highlight searched text in asp.net page using JQuery.

Description

       When I type some text on textbox say tbSearchText, and press enter on it. This will Call JQuery extended function highlight method.

$("[id$='_ tbSearchText']").keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
$('#divContent').highlight($(this).val(), "highlight");
        }
});
      
                Further in highlight method we search for the form in Div, where the content exists. If Searched text found then, particular text is highlighted with class using css highlight.

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp(str, "gi");
    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function (matched) {
            return "<span class=className'>" + matched + "</span>";
        });
    });
};


Monday, 29 October 2012

How to change width of textbox dynamically using JQuery

Introduction
               In the previous post, I had show how to get Comma seperated values in Sql Server. In this post I will show you how to set textbox width dynamically.

Description                 When I click on search textbox then it checks wheather it has some value if no, then it keeps textbox width at 40px and text color as gray. And if have some text in search box then it will keep width as 80px and text as gray.


if ((tbSearch.val() == null) || (tbSearch.val() == '') || (tbSearch.val() == 'Search')) {
    tbSearch.val('Search');
    tbSearch.css("color", "Gray");
    tbSearch.css("width", 40);
} else {
    tbSearch.css("color", "Gray");
    tbSearch.css("width", 80);
}



               when I click in search box or when textbox gets focus, It will expand with animation from width of 40px to 80px and get fore color as black.


tbSearch.focus(function () {
    if (tbSearch.val() == 'Search')
        $(this).val('');
    $(this).css("color", "black");
    $(this).animate({ width: 80 }, 500);
});

              When I focus out of search box and if it contains some search data then width remains at 80px and fore color as gray, else it animate and shrink to 40px.


tbSearch.focusout(function () {
    $(this).css("color", "Gray");
    if ($(this).val() == '') {
        $(this).val('Search');
        $(this).animate({ width: 40 }, 500);
    }
});

Saturday, 20 October 2012

How to get Comma seperated list of values in SQL Server


Description:
                In SQL Server, we could query table column values into comma separated list. Here I could found two efficient ways to do the same. The first will be used mostly in procedures as it requires temporary variable, while other could be used in single select query with the help of stuff() function and XML FOR PATH() methods.
Data:
We will be having following data to execute Queries.
Employee Table
CREATE TABLE [dbo].[employee](
      [empid] [int] NOT NULL,
      [name] [varchar](100) NULL,
      [salary] [decimal](18, 0) NULL,
      [deptid] [int] NULL)



Department Table
CREATE TABLE [dbo].[department](
      [deptid] [int] NOT NULL,
      [deptname] [varchar](100) NULL)




Method 1:
Query:
DECLARE @list VARCHAR(MAX)
SELECT @list = COALESCE(@list + ',' , '') + name FROM employee
SELECT @list 'Comma Seperated List'

Result:
Comma Seperated List
-----------------------------------------------------------------------
Allyn,Bailey,Becky,Calista,Elisa,Franklyn,Hervey,Jackson,Kimberly,Lecia

(1 row(s) affected)


Method 2:
Query:
SELECT STUFF
((SELECT ',' + NAME
FROM employee
FOR XML PATH(''))
,1,1,'') 'Comma Seperated List'
Result:
Comma Seperated List
-----------------------------------------------------------------------
Allyn,Bailey,Becky,Calista,Elisa,Franklyn,Hervey,Jackson,Kimberly,Lecia

(1 row(s) affected)

Example:
                In example we will be showing employee working in particular department as comma separated values.
Query:
SELECT T1.deptname 'Department Name',
STUFF
((SELECT ',' + name FROM employee T2 WHERE T2.deptid = T1.deptid
FOR XML PATH('')),1,1,'') Employees
FROM
department T1

Result:
deptname                                           Employees
----------------------------------------------------------------------------------------------------
Administration                                            Allyn,Elisa
Marketing                                                  Bailey,Kimberly
Shipping                                                     Jackson
Information Technology                              Becky,Hervey,Lecia
Sales                                                          Calista
Accounting                                                 Franklyn

(6 row(s) affected)




Monday, 15 October 2012

SQL Server - Stuff()


Define:
             Stuff is a TSQL function which is use to delete specified length of Character with in a string and replace with another set of characters.
Syntax:
STUFF(Character_Expression, Start, Length, replaceWith_expresstion)
Character_Expression:
              It is an expression of character data, which can be constant, variable or table column.
Start :
             This indicates the starting position of the character in character_expression.
Length:
              It is the length of characters which need to be replaced.
replaceWith_expresstion:
             It is the string that will be replaced from the start position to the length position.

Return Type:
             Return type will be same as of Character_Expression.
Example:
     SELECT STUFF('Have a good day',8,4,'nice');
Result:
             Have a nice day

Saturday, 13 October 2012

How to use Datasets with Linq in Asp.net


Define:
             Linq to Datasets provides a runtime infrastructure for querying Datable in Datasets as object without losing ability to querying. Linq to Data ships in .Net Framework 4.0.  Lin treats dataset as a Collection of columns which hold relational data. Let’s start with Simple Linq to dataset query and further in deep functionality of query.

Data:
First we will be having data in two data tables which resides in function GetEmployee() and GetDepartment(). Below is brief look at two data tables and structure.



Employee Table



Department Table


These datatables can be further added to datasets in the following ways.
DataSet ds = new DataSet();

       ds.Tables.Add(getEmployee());
       ds.Tables[0].TableName = "Emp";
       ds.Tables.Add(getDapartment());
       ds.Tables[1].TableName = "Dept";

We can even define Foreign key relation between two tables in dataset.
                DataColumn[] dc;
       dc = new DataColumn[1];
dc[0] = ds.Tables["Dept"].Columns["DeptID"];
       ds.Tables["Dept"].PrimaryKey = dc;

ForeignKeyConstraint fkcDept = new ForeignKeyConstraint(ds.Tables["Dept"].Columns["DeptID"],

ds.Tables["Emp"].Columns["DeptID"]);
       ds.Tables["Emp"].Constraints.Add(fkcDept);


Select Linq Query on Dataset
Employee Table
var query = (from a in ds.Tables["Emp"].AsEnumerable()
       select new
       {
EmpId = a["EmpId"],
              Name = a["Name"],
              Salary = a["Salary"],
});
gvData.DataSource = query;
       gvData.DataBind();

Result


Department Table
var query = (from a in ds.Tables["Dept"].AsEnumerable()
       select new
       {
DeptId = a["DeptId"],
              Name = a["DeptName"],
});
gvData.DataSource = query;
       gvData.DataBind();

Result


Select Join Linq Query on Dataset
var query = (from a in ds.Tables["Emp"].AsEnumerable()
join b in ds.Tables["Dept"].AsEnumerable()
on a.Field<Int32>("DeptId") equals b.Field<Int32>("DeptId")
              select new
              {
                     EmpId = a["EmpId"],
                     Name = a["Name"],
                     DeptName = b["DeptName"],
                     Salary = a["Salary"],
});
Result


Where Linq Query on Dataset
var query = (from a in ds.Tables["Emp"].AsEnumerable()
join b in ds.Tables["Dept"].AsEnumerable()
on a.Field<Int32>("DeptId") equals b.Field<Int32>("DeptId")
       where b.Field<String>("DeptName") == "Information Technology"
       && a.Field<Decimal>("Salary") > 15000
       select new
       {
              EmpId = a["EmpId"],
              Name = a["Name"],
              DeptName = b["DeptName"],
              Salary = a["Salary"],
});
Result



ML.NET: Machine Learning for .NET Developers

Machine Learning in .Net ML.NET is a free software machine learning library for the C# and F# programming languages. It also supports Pyth...