Wednesday, April 6, 2011

Populate Dropdown lists in GridView in asp.net-II

other than doing in the previous post, we can do it in the following way





protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e)
{
DropDownList ddl = new DropDownList();
ddl = (DropDownList)e.Row.Cells[Cell No].FindControl("Template DropDownId");
//Code to bind the dropdownlist...
}

Populate Dropdown lists in GridView in asp.net

How to do it is :


Write a method which will get the values from the database and it returns a dataset:

--------------------------------------------------------------------------
// This method populates the DropDownList

public DataSet PopulateControls()
{
SqlConnection myConnection = new SqlConnection(GetConnectionString());
SqlDataAdapter ad = new SqlDataAdapter("SELECT [Name] FROM tblPerson",
myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "tblPerson");
return ds;
}
--------------------------------------------------------------------------


Now inside the itemtemplate tag do the following




Thats it........Done.

Sunday, April 3, 2011

Dictionary as a datasource to a dropdown

Wondering how to provide the dictionary object as the datasource to the dropdown:

CODE:
--------------------------------------------------------------
//Setting the dictionary item list

dctLists.Add("hyderabad", 500020);
dctLists.Add("sec-bad", 500009);
dctLists.Add("chikkadpally", 500020);

//poplting the second ddl
ddlListWithValues.DataSource = dctLists;
ddlListWithValues.DataTextField = "Key";
ddlListWithValues.DataValueField = "Value";
ddlListWithValues.DataBind();

--------------------------------------------------------------

Saturday, April 2, 2011

Display more than 1 display values in a dropdown with ',' seperated

Are you looking for displaying more than 12 values in a dropdown with ',' seperated.
It is possible using the generics DICTIONARY class:
CODE::

---------------------------------------------------------------------------------
Dictionary dctLists = null;
//Setting the dictionary item list
dctLists = new Dictionary();
dctLists.Add("hyderabad", 500020);
dctLists.Add("sec-bad", 500009);
dctLists.Add("chikkadpally", 500020);

//Display more than 1 value in the dropdown
ddlMultipleValsDisplaye.DataSource = dctLists;
ddlMultipleValsDisplaye.DataBind();

---------------------------------------------------------------------------------

if you run the above code, then you will see that both the valuees from the dictionary are displayed in the dropdownlist.

Wednesday, March 30, 2011

Types of valid ENUMERATORS

In c# we generally go for the enumerators for the sake of having a better code readability and to achieve code standardization. Below are the various types of enums, from which only few are valid.


Type1:
----------------------------------------------------------------------
public enum enmPosition
{
Scroll=111,
dwn=12,
ug=11,
ch=10
};




Declaring a enum and then giving some elements for it and then assigning some numeric values for that. In this case its totally valid.

From above if you are going to access the enum values, then if we say: enmPosition.Scroll => this will return 111 as the value.



Type2:
-------------------------------------------------------------------

public enum enmPosition1 : int
{
Scroll = 111,
dwn = 12,
ug = 11,
ch = 10
};



Here though we are inheriting the enum from the int, the values can be accessed same as above, but the inheritance is mostly for the sake of the code clarity and redability.

This is also valid.



Type3:
------------------------------------------------------------------

public enum enmPosition2
{
Scroll,
dwn,
ug,
ch
};


In the above enum we can see that there are no user defined values attached or assigned to the enum elements(Scroll, dwn,ug,ch). But the enum has got the ability to assign the values to the elements.

In the below code we get the values a scroll=0; dwn=1;ug=2;ch=3. This is valid.



Type4:
---------------------------------------------------------------------

// Defining a string type enum
public enum enmStringType : string
{
India = "India is great",
XyxCtr = "This contry is not known"
}



In the above we declared a enum of type string, as the enums can return only the numeric types, this type of enum can't be used. So this is not valid.



Type4 -Extension:
-------------------------------------------------------------

In order to use enums which returns the will return the strings can be done in the following way:

first we need to create a custom class which inherits the System.Attributes.



public class StringValueAttribute : System.Attribute
{

private string _value;

public StringValueAttribute(string value)
{
_value = value;
}

public string Value
{ get { return _value; } }

}




In the above we are setting a parameterized constructor and a property for a private variable.



then change the enum to this


public enum Test : int
{
[StringValue("a")]
Xyz = 1,
[StringValue("b")]
Something = 2
}





now add this new method in your class, which is responsible for accessing the value attributes and getting the actual value from the enum.

public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();

//Check first in our cached results...

if (_stringValues.ContainsKey(value))
output = (_stringValues[value] as StringValueAttribute).Value;
else
{
//Look for our 'StringValueAttribute'

//in the field's custom attributes

FieldInfo fi = type.GetField(value.ToString());
StringValueAttribute[] attrs =
fi.GetCustomAttributes(typeof(StringValueAttribute),
false) as StringValueAttribute[];
if (attrs.Length > 0)
{
_stringValues.Add(value, attrs[0]);
output = attrs[0].Value;
}
}

return output;
}



and for performance point of view, we are using the HashTable to store the data.
so add this at the starting of the class.


private static Hashtable _stringValues = new Hashtable();




Then when we try to access the enum, we get the value as well as the attribute (the string value).


GetData:
-------------------------------------------------------------
string tEnumValue=GetStringValue(Test.Something);

Sunday, March 27, 2011

WCF (Windows communication Foundation) tutorial starting

Hi, guys

Are you looking for any quick way for get hands on the WCF of the microsoft WCF!!!!!!
Dont worry I am here for such thing to happen.
This is the stating post of the WCF, and first I am going to give you a brief idea regarding the WCF.


What is WCF????
WCF stands for WINDOWS COMMUNICATION FOUNDATION, it is based in SOA (SERVICE ORIENTED ARCHITECTURE). WCF is totally a revolutionized SOA platform for easy cross platform communication. It has got a lot more features than webservices.

DEF: WCF is a runtime environment for developing, building, configuring and hosting the network based SOA application. It is a package or a combination of webservices, remoting, MSMQ, com+.






There are lot of terminologies to come across in WCF, which will be covered in the next posts...........

Saturday, February 19, 2011

c#

Few Basic And Important things in c#
------------------------------------



For Loop in c#
---------------

Label1.Text = "0";
for (iCount = 0; iCount < 100; iCount++)
{
Label1.Text = Convert.ToString(Convert.ToInt32(Label1.Text) + iCount);
}


ForEach syntax:
----------------

Label1.Text = "0";
ArrayList iArr = new ArrayList { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
foreach (var iCnt in iArr)
{
Label1.Text = Convert.ToString(Convert.ToInt32(iCnt) + Convert.ToInt32(Label1.Text));
}


While Loop:
-----------

while (System.DateTime.Now.Second<50)
{
Label1.Text = Convert.ToString(1 + Convert.ToInt32(Label1.Text));
}


Using String Builder:
---------------------

System.Text.StringBuilder sbFinalString = new System.Text.StringBuilder();
if (Label1.Text.Length <= 0)
{
sbFinalString.Append("The string starts:-");
}
else
{
sbFinalString.Append(System.DateTime.Now.Second.ToString());
}
Label1.Text = sbFinalString.ToString();


Using a Session variable:
-------------------------

Session["User"] = "TestUser";

Label1.Text =Convert.ToString(Session["User"]);


Creating a datatable dynamically and inserting a row and storing in VIEWSTATE:
------------------------------------------------------------------------------

DataTable dtData=new DataTable();

dtData.Columns.Add("Sno");
dtData.Columns.Add("Name");
dtData.Columns.Add("IDNo");
dtData.Columns.Add("Address");

DataRow drNewRow = dtData.NewRow();
drNewRow["Sno"]="1";
drNewRow["Name"]="One";
drNewRow["IDNo"]="01";
drNewRow["Address"]="HYDERABAD";

dtData.Rows.Add(drNewRow);
dtData.AcceptChanges();

ViewState["DumyData"]=dtData;


Getting the data from the viewstate:
------------------------------------

GridView1.DataSource = (DataTable) ViewState["DumyData"];
GridView1.DataBind();

Creating Cookie and storing data in it:
---------------------------------------

HttpCookie ckUser = new HttpCookie("UserLogin");
ckUser.Values["Name"] = "Testuser1";
ckUser.Values["Mode"] = "Today";
ckUser.Values["Role"] = "Admin";
ckUser.Expires = DateTime.Now.AddMinutes(1);
Response.Cookies.Add(ckUser);

Retriving the data

if (Request.Cookies["UserLogin"] == null)
{
Label1.Text = "Cookie not found/ Expired";
}
else
{
Label1.Text= Request.Cookies["UserLogin"]["Name"];
Label1.Text= string.Concat(Label1.Text, " Mode :", Request.Cookies["UserLogin"]["Mode"], "Role: ", Request.Cookies["UserLogin"]["Role"]);
}

Using Switch case:
------------------

string[] tArr = { "1", "2", "5" };
foreach (var tItems in tArr)
{
switch(Convert.ToInt32(tItems))
{
case 1:
Label1.Text=string.Concat(Label1.Text," ",tItems.ToString());
break;
case 2:
Label1.Text = string.Concat(Label1.Text," ", tItems.ToString());
break;
default:
Label1.Text = string.Concat(Label1.Text," Not valid data found");
break;
}
}

Saturday, August 21, 2010

Creating a Setup file/deployment (interface to install a application)

Creation of the interface for installing a windows application or a windows service.
------------------------------------------------------------------------------------

Step1:
--------
Be ready with your .exe file for which you want to create the installation interface/wizard.

Then open VisualStudio and go for new project-->Other projects type -->setup and deployment




Step2:
---------
Then you see the following interface after entering the project............this depends on the version of visual studio you are using.



Step3:
---------



Step4:
--------
Now select the exe file and the config file.
If you dont have any config file then choose only the exe file.


Step5:
---------



Step6:
---------



Step7:
--------



Step8:
--------


Step9:
--------

The final setup exe files are ready in the bin folder.

Creating a perfect sample Windows Service......

Below you can find how to create a windows service and handling all its events for writing a perfect working service and proper CPU consumption by the windows service.


Summary:

The below service is used for creating a file in a specified location and write the time into it at a specific time interval continiously untill you stop the service.




Step1:
-------
Open Visualstudio-->New project-->windows-->service/windowsservice.


Step2:
-------

Now you see the below screen as


step3:
-------
RightClick and choose the add Installer



Step4:
--------
Now you can see the following



Step5:
--------
Now you need to change the properties of the installers..........

Step6:
--------
Now start the coding.


SERVICE1.VB
code:






Imports System
Imports System.IO
Imports System.Configuration

Public Class Service1

'Declaring the global variables
Dim tmTimer As System.Timers.Timer = Nothing

Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service.
' in motion so your service can do its work.
'Declaring the variable here
Dim itimeInterval As Integer = -1
Try
'geting time interval from app.config file
itimeInterval = CType(ConfigurationManager.AppSettings("TimeInterval"), Integer)
'initialiasing
tmTimer = New Timers.Timer(itimeInterval)
'starting the timer
tmTimer.Start()
'calling the function when timer finished
AddHandler tmTimer.Elapsed, AddressOf GenerateFile
'again resetting the properties
With tmTimer
.AutoReset = True
.Enabled = True
.Start()
End With
Catch ex As Exception
WriteEventlog(ex.ToString)
End Try
End Sub

Public Sub GenerateFile()
'Declaring the variables
Dim Fs As FileStream = Nothing
Dim Sw As StreamWriter = Nothing
Try
'Creating the objects to the variables
Fs = New FileStream("D:\NewtextFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
WriteEventlog("Done creating the file")
Sw = New StreamWriter(Fs)
Sw.WriteLine(DateTime.Now)
WriteEventlog("Done writing the data.")
Sw.Close()
Fs.Close()
Catch ex As Exception
WriteEventlog(ex.ToString)
Finally
Sw.Close()
Fs.Close()
If Sw IsNot Nothing Then Sw = Nothing
If Fs IsNot Nothing Then Fs = Nothing
End Try
End Sub

Private Sub WriteEventlog(ByVal tMsg As String)
'--------------------------------------------------------------------------------------------------
'Description : Logs the entries.
'------------------------------------------------------------------------------------------
Dim MyLog As New EventLog() ' create a new event log

Try
' Check if the the Event Log Exists
If Not Diagnostics.EventLog.SourceExists("File Writing") Then
Diagnostics.EventLog.CreateEventSource("File Writing", "File Writing Log")
End If
MyLog.Source = "File Writing"
' Write the Log
Diagnostics.EventLog.WriteEntry("File Writing Log", tMsg, EventLogEntryType.Information)
Catch ex As Exception

Finally
If MyLog IsNot Nothing Then MyLog = Nothing
End Try
End Sub

Protected Overrides Sub OnStop()
'The event is fired when the service is stopped.
tmTimer.Stop()
' Add code here to perform any tear-down necessary to stop your service.
End Sub

Protected Overrides Sub OnPause()
MyBase.OnPause()
'Handling the paused event of the serivce
tmTimer.Stop()
End Sub
Protected Overrides Sub OnContinue()
MyBase.OnContinue()
''Handling the on continue action of service
tmTimer.Start()
End Sub

Protected Overrides Sub OnShutdown()
MyBase.OnShutdown()
tmTimer.Stop()
End Sub
End Class






*Make sure you write all the events like the onshutdown, onpaused, onstop, onstart for the proper usage of the CPU memory.




The app.config file entry:
---------------------------



here the time is in milliseconds.................so to convert it into minutes, multiply the time with * 60000 and give the value in the below config key


< key ="TimeInterval" value="1">






now build the service. Now your service is ready for installing in services.