Thursday, 28 March 2013

IEnumerable and IQueryable

IEnumerable is inherited by IQueryable, hence it has all the features of it and except this, it has its own features

IEnumerable<T> is great for working with sequences that are iterated in-memory, but IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.
 
 
IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.

The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements (or even do other things) based on a query. In the case of the IQueryable, the LINQ query gets used by IQueryProvider which must be interpreted or compiled in order to get the result. I.e., the extension methods defined for IQueryable take Expression objects instead of Func objects (which is what IEnumerable uses), meaning the delegate it receives is an expression tree instead of a method to invoke.

for example:
IEnumerable ->

IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

The above statement represents the below query:

SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0WHERE [t0].[EmpName] LIKE @p0

IQueryable->

IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list = list.Take<Employee>(10); 
The above statement represents the below query:

SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
WHERE [t0].[EmpName] LIKE @p0



    Wednesday, 27 February 2013

    Immutable String

    All strings in .NET are immutable. You never can change a content of any string. All string operations create a brand-new string

    We know that strings are reference type in .net. Due to this fact, they are allocated on heap and when in the scope their pointer come on to the stack. When we try and assign a new value to a string variable, we can get the new value assigned to our variable, but in the background, a new memory location is allocated and its reference is copied to out string variable making us feel that the value of the original one is changed. This feature is referred as immutable. Thus all string in .net are immutable.
    Due to this behavior of string we should always use StringBuilder class present in System.IO.Text namespace. System.Text.StringBuilder.Append does this thing much more effectively, because already available data is never copied again, the instance of StringBuilder mutates instead.

     if you have any repeated operation to compose a string, always use StringBuilder. Basically, using more than one string "+" in one expression is not very effective; string.Format function is much better, faster and more readable.


    string myString = "Immutable";
    char charI = myString[0];
    //you can do it
    //myString[0] = ' '; myString[1] = ' '; no way; it is immutable
    //
    array of char can be considered as some kind of string; it is mutable:
    char[] myText = new char['M', 'u', 't', 'a', 'b', 'l', 'e', ' ', ];
    myText[7] = '!';
    //you can do it! The result will be "Mutable!"

    Difference Between 'Ref' and 'Out'

    The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. For example:

    OUT Example:

    class OutExample
    {
        static void Method(out int i)
        {
            i = 44;
        }
        static void Main()
        {
            int value;
    Method(out value);
            // value is now 44    }
    }

    REF Example:

    class RefExample
        {
            static void Method(ref int i)
            {
                // Rest the mouse pointer over i to verify that it is an int.            // The following statement would cause a compiler error if i            // were boxed as an object.            i = i + 44;
            }
            static void Main()
            {
                int val = 1;
                Method(ref val);
                Console.WriteLine(val);
                // Output: 45        }
        }


    Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

    The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile.

    Sunday, 17 February 2013

    Open XMl :Get the value from the excel depending on some row value

    Using Open Xml, I have extracted the data from the excel sheet depending on a value, wherever there exist the value "CLOSED" in the "Status" column, I need its whole row and display in the grid. For example lets my excel looks like this: 


    The column "Current Status" is in G column which contains some values, I need to extact the values from the excel where current status is closed and display. The code is as follows, where I have used open Xml :

    the page designed with one fileuploader, ane button and a gridview to display the result. the code goes like this:

    protected void Button1_Click(object sender, EventArgs e)
    {

    DataTable dt= ReadXml();GridView1.DataSource = dt;
    GridView1.DataBind();
    }


    private DataTable ReadXml(){

    string val = null;
    DataRow rw = null;
    int j = 0;
    DataTable dt = TableStruc();
    //get the path of the excel sheetusing (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(FileUpload1.PostedFile.FileName, false)){

    //open the sheetvar sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>().First();
    WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheets.Id);
    Worksheet worksheet = worksheetPart.Worksheet;
    //Get the first sheet of the excelSheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
    SharedStringTablePart stringTable = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
    //get the total rows in the sheet to loop over the sheet to check the dataint rowCount = worksheet.Descendants<Cell>().Count<Cell>();
    uint rowind = 2;
    for (int i = 0; i < rowCount; i++){

    //get the value of cell G where the status of CMR is being written(Closed,Open,worked...)Cell cell = GetCell(worksheet, "G", rowind);
    if (cell != null){

    //Get the text value of that cell in a variableval = cell.CellValue.Text;
    //check the datatype of the value,if it is sting---if (val != null && cell.DataType.Value == CellValues.SharedString){

    var tableEntry = stringTable.SharedStringTable.ElementAt(int.Parse(val));
    if (tableEntry != null){
    val = tableEntry.InnerText;

    //Do Something if the status is CLosedif (val =="CLOSED"){

    //a new row is added to the datatable to add the values of rw = dt.NewRow();
    Row r= GetRow(worksheet, rowind);
    foreach (Cell c in r.Elements<Cell>()){
    val = c.CellValue.Text;

    if (c.DataType!=null){

    if(c.DataType.Value== CellValues.SharedString)tableEntry = stringTable.SharedStringTable.ElementAt(
    int.Parse(val));val = tableEntry.InnerText;
    }

    elseval = c.CellValue.Text;
    rw[j++]= val;
    }
    dt.Rows.Add(rw);
    j = 0;
    }

    }
    }
    rowind++;
    }
    }

    }
    return dt;}



    private static Cell GetCell(Worksheet worksheet,string columnName, uint rowIndex){

    Row row = GetRow(worksheet, rowIndex);
    if (row == null)
    return null;
    return row.Elements<Cell>().Where(c => string.Compare(c.CellReference.Value, columnName +
    rowIndex,
    true) == 0).First();}



    private static Row GetRow(Worksheet worksheet, uint rowIndex){

    try{
    return worksheet.GetFirstChild<SheetData>().Elements<
    Row>().Where(r => r.RowIndex == rowIndex).First();}

    catch (Exception){

    return null;}
    }


    private DataTable TableStruc(){

    DataTable dt = new DataTable();
    DataColumn dc1 = new DataColumn() { ColumnName = "requestno", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc1);

    DataColumn dc2 = new DataColumn() { ColumnName = "group", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc2);

    DataColumn dc3 = new DataColumn() { ColumnName = "changedate", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc3);

    //DataColumn dc4 = new DataColumn() { ColumnName = "changetime", DataType = System.Type.GetType("System.String") };//dt.Columns.Add(dc4);DataColumn dc8 = new DataColumn() { ColumnName = "changetype", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc8);

    DataColumn dc11 = new DataColumn() { ColumnName = "description", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc11);

    DataColumn dc9 = new DataColumn() { ColumnName = "requester", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc9);

    DataColumn dc10 = new DataColumn() { ColumnName = "status", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc10);

    DataColumn dc5 = new DataColumn() { ColumnName = "closuredate", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc5);

    //DataColumn dc6 = new DataColumn() { ColumnName = "closuretime", DataType = System.Type.GetType("System.String") };//dt.Columns.Add(dc6);DataColumn dc7 = new DataColumn() { ColumnName = "approval", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc7);

    return dt;}



    The above code when executed looks like :


    As seen above only those data are displayed where the current status is "Closed".

    Use of Generic Dictionary<>

    Dictionary contains a key and a value. Each key is correspond to one value. It is very useful, when u have some value according to another value, and u need to keep track of which one is correspond to which value.
    I had certain situations where Dictionary was valuable for me. here I would post one of those:

    Declare:

    public Dictionary<string, string> GridVal = new Dictionary<string, string>();


    Use To Filter Data :

    The Design is as follows:

    According to the selected item we need to filter the data and show it in the gridview. here I have used Dictionary to form the condition, to select the data from the database, according the the section user makes.

    Code:

    protected void btnFilter_Click(object sender, EventArgs e){

    try{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();GetSelectedValues();
    GetConditions();

    //ds= TMBL.GetGridValue(Convert.ToInt32(ddlGenerateYear.Text.Trim()));//ViewState["Dataset"] = ds;ds = (DataSet)ViewState["Dataset"];
    if (ds.Tables[0].Select(TMUtil.queryCondition).Any()){
    dt = ds.Tables[0].Select(TMUtil.queryCondition).CopyToDataTable();
    gvTMInitialForecast.DataSource = dt;
    gvTMInitialForecast.DataBind();
    }

    else{
    gvTMInitialForecast.DataBind();
    LblError.Visible =
    true;LblError.Text =
    "No Data Found As Per Your Search";}
    }

    catch{
    //gvTMInitialForecast.Visible = false;LblError.Visible = true;LblError.Text =
    "No Data Found As Per Your Search";}
    }



    private void GetConditions(){
    TMUtil.queryCondition =
    "";
    foreach( KeyValuePair<string, string> value in TMUtil.GridVal){

    if (TMUtil.queryCondition != "")TMUtil.queryCondition = TMUtil.queryCondition +
    " and ";TMUtil.queryCondition = TMUtil.queryCondition+value.Key +
    " = '"+ value.Value +"'";
    }
    }
    // Get the values selected by the user and store it in Dictionary<>


    private void GetSelectedValues(){
    if (ddlProjectLOB.Text != "")TMUtil.GridVal[
    "ProjectLOB"] = ddlProjectLOB.Text.Trim();//Gridval is the dictionary having "ProjectLOB" as key and the ddl text as its value
    if (ddlPortfolio.Text != "")TMUtil.GridVal[
    "Portfolio"] = ddlPortfolio.Text.Trim();
      if (ddlProjectID.Text != "")
    TMUtil.GridVal[
    "ProjectID"] = ddlProjectID.Text.Trim();
      if(ddlLocation.Text!="")
    TMUtil.GridVal[
    "Region"] = ddlLocation.Text.Trim();
      if (ddlRole.Text != "")
    TMUtil.GridVal[
    "[Role]"] = ddlRole.Text.Trim();
      if(ddlEmployeeID.Text!="")
    TMUtil.GridVal[
    "ResourceID"] = ddlEmployeeID.Text.Trim();
      if (ddlYear.Text != "")
    TMUtil.GridVal[
    "ForecastYear"] = ddlYear.Text.Trim();
      if(ddlMonth.Text!="")
    TMUtil.GridVal[
    "Month"] = ddlMonth.Text.Trim();
    }



    The Viewstate already contains the dataset having the total value from the database, and then the filter is done on this dataset,according to the condition. the condition is framed with the help of DICTIONARY<>. Dictionary contails the name of the column as its key and the value selected by the user as its value. now while framing the condition, we use the key and the value both. this condition is just use to filter data from the dataset.

    Friday, 4 January 2013

    Comparing two Datasets using LINQ

    let there be two  datasets (oldds, newds) having similar columns and data, we need compare the two and detect whether any new records has been added in the new dataset, whether any data has been deleted from the new dataset and whether there is any modification in the data of the new dataset. To do so I have used LINQ to compare the datasets seperately for different scenarios, then convert the result of the LINQ back to a dataset to bind it with the gridview. The code is as follows:

    private DataSet CompareDatasets(DataSet Oldds, DataSet Newds)
    {
    //Result Dataset

    DataSet res= new DataSet();DataTable dt = new DataTable();//Create the structure of the datatable same as the source table
    dt = CreatTableStructure();

    DataTable dtOld = new DataTable();
    dtOld = dt.Clone();

      try
    {
    //make the datasets enumerable to loop through itvar orig = Oldds.Tables[0].AsEnumerable();
    var updated = Newds.Tables[0].AsEnumerable();
    //Using LINQ to loop through the data//Any New Record Addedvar newRec = from u in updated
    where !(from o in orig
    select o.Field<double>("Primary Key")).Contains(u.Field<
    double>("Primary Key"))
    select u;
    //Data Updated var updRec = from u in updated
    join o in orig
    on u.Field<doublePrimary Key")
    equals o.Field<double>("Primary Key")
    where (u.Field<double>("Project ID") !=o.Field<
    double>("Project ID")) ||(u.Field<
    string>("Description") !=o.Field<
    string>("Description")) ||(u.Field<
    string>("City") !=o.Field<
    string>("City"))
    //|| (u.Field<DateTime>("*Start Date") !=//o.Field<DateTime>("*Start Date")) ||//(u.Field<DateTime>("*End Date") !=//o.Field<DateTime>("*End Date"))select u;
    //Any Record deletedvar delRec = from o in orig
    where !(from u in updated
    select u.Field<double>("Primary Key")).Contains(o.Field<
    double>("Primary Key"))
    select o;
    //Transfer the values to datatable and check which data has been updated :foreach (var item in updRec){
    dt.Rows.Add(item.Field<double>("Project ID"), item.Field<double>("*Team Member"), item.Field<string>("Name"), item.Field<string>("Description"), item.Field<string>("Cust Ref#"), item.Field<string>("City"), item.Field<DateTime>("*Start Date"), item.Field<DateTime>("*End Date"), "Updated");}

    //Transfer the added records to a datatable :foreach (var item in newRec){
    dt.Rows.Add(item.Field<
    double>("Project ID"), item.Field<double>("*Team Member"), item.Field<string>("Name"), item.Field<string>("Description"), item.Field<string>("Cust Ref#"), item.Field<string>("City"), item.Field<DateTime>("*Start Date"), item.Field<DateTime>("*End Date"), "Added");// item.rec_type);}
    //Transfer the deleted records to a datatable :foreach (var item in delRec){
    dt.Rows.Add(item.Field<
    double>("Project ID"), item.Field<double>("*Team Member"), item.Field<string>("Name"), item.Field<string>("Description"), item.Field<string>("Cust Ref#"), item.Field<string>("City"), item.Field<DateTime>("*Start Date"), item.Field<DateTime>("*End Date"), "Deleted");// item.rec_type);}
    res.Tables.Add(dt);
    return res;}

    catch{
    throw;}
    }


    private DataTable CreatTableStructure()
    {
    DataTable t = new DataTable();
    t.Columns.Add(
    "Project ID", typeof(double));
    t.Columns.Add(
    "Primary Key", typeof(double));
    t.Columns.Add(
    "Name", typeof(string));
    t.Columns.Add(
    "Description", typeof(string));
    t.Columns.Add(
    "Cust Ref#", typeof(string));
    t.Columns.Add(
    "City", typeof(string));
    t.Columns.Add(
    "Start Date", typeof(DateTime));
    t.Columns.Add(
    "End Date", typeof(DateTime));
    t.Columns.Add(
    "Rec_Type", typeof(string));
    return t;}

    

    Wednesday, 26 December 2012

    Add News Feed in Web Page

     Write the below Javascript code in the source code of your web page :

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <
    script src="http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js"type="text/javascript"></script><
    style type="text/css">@import
    url("http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css");#feedControl {margin-top : 10px;margin-left: auto;margin-right: auto;width : 205px;font-size: 12px;color: #9CADD0;}
    </style><
    script type="text/javascript">function
    load() {
    var feed = "http://rss.cnn.com/rss/edition_world.rss";new GFdynamicFeedControl(feed, "feedControl");}
    google.load(
    "feeds", "1");google.setOnLoadCallback(load);
    </script>

    ---The variable Feed conatins the site from where the news are fetched. We can give some other sites too such as :
    1. var feed =”http://feeds.bbci.co.uk/news/world/rss.xml”;
    2. var feed =”http://rss.cnn.com/rss/edition_world.rss”;
    3. var feed =”http://feeds.reuters.com/Reuters/worldNews “;
    Now where ever you need the news feed in your page just write the below code :


    <div id="feedControl" align="left" dir="ltr">Loading...&nbsp; </div>


    You can see the page with active news feeds along with the link :