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.