Dynamically adding ItemTemplate to the GridView holding controls
The code helps you to add Item template (or any part of templated column) to the Gridview dynamically. We has also set/add desired controls to the Item templates.
We have a class which will be used to set the item template control into the Gridview.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | for (int index = 0; index < allRoles.Length; index++) { Table.Columns.Add(allRoles[index].Replace(" ", "_")); TemplateField tempField = new TemplateField(); tempField.HeaderText = allRoles[index]; tempField.ItemStyle.VerticalAlign = VerticalAlign.Middle; tempField.ItemStyle.HorizontalAlign = HorizontalAlign.Center; //chBox.ID = allRoles[index].Replace(" ", "_"); tempField.ItemTemplate = new GridViewTemplate(ListItemType.Item, allRoles[index].Replace(" ", "_")); if (IsPostBack) { grvManageSecurity.Columns.RemoveAt(1); } grvManageSecurity.Columns.Add(tempField); } |
CLASS: Used to set the controls into Item template and
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; //A customized class for displaying the Template Column public class GridViewTemplate : ITemplate { //A variable to hold the type of ListItemType. ListItemType _templateType; //A variable to hold the column name. string _columnName; //Constructor where we define the template type and column name. public GridViewTemplate(ListItemType type, string colname) { //Stores the template type. _templateType = type; //Stores the column name. _columnName = colname; } void ITemplate.InstantiateIn(System.Web.UI.Control container) { switch (_templateType) { case ListItemType.Header: //Creates a new label control and add it to the container. Label lbl = new Label(); //Allocates the new label object. lbl.Text = _columnName; //Assigns the name of the column in the lable. container.Controls.Add(lbl); //Adds the newly created label control to the container. break; case ListItemType.Item: //Creates a new text box control and add it to the container. CheckBox chkField = new CheckBox(); chkField.ID = _columnName; //Allocates the new text box object. container.Controls.Add(chkField); //Adds the newly created textbox to the container. break; case ListItemType.EditItem: //As, I am not using any EditItem, I didnot added any code here. break; case ListItemType.Footer: CheckBox chkColumn = new CheckBox(); chkColumn.ID = "Chk" + _columnName; container.Controls.Add(chkColumn); break; } } /// <summary> /// This is the event, which will be raised when the binding happens. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void tb1_DataBinding(object sender, EventArgs e) { TextBox txtdata = (TextBox)sender; GridViewRow container = (GridViewRow)txtdata.NamingContainer; object dataValue = DataBinder.Eval(container.DataItem, _columnName); if (dataValue != DBNull.Value) { txtdata.Text = dataValue.ToString(); } } } |
SQL Bulk Copy using SQL Server 2005
The below code help in copying a large amount of data from the local datastore to the sql server database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | protected void Button11_Click(object sender, EventArgs e) { ConnectionStringSettings pubs = ConfigurationManager.ConnectionStrings["PubsData"]; DbConnection connection = new SqlConnection(pubs.ConnectionString); ConnectionStringSettings bulkCopy = ConfigurationManager.ConnectionStrings["PubsData"]; SqlConnection bulkCopyConnection = new SqlConnection(bulkCopy.ConnectionString); DbCommand cmd = connection.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT stor_name FROM Stores"; connection.Open(); bulkCopyConnection.Open(); //make sure that table exists and is empty //in case button is clicked more that once SqlCommand cleanup = bulkCopyConnection.CreateCommand(); cleanup.CommandText = "IF EXISTS ( SELECT * FROM sys.objects " + " WHERE object_id = OBJECT_ID('dbo.StoreList') " + " AND type in ('U')) " + "DROP TABLE dbo.StoreList " + "CREATE TABLE dbo.StoreList(stor_name varchar(40) NOT NULL )"; cleanup.ExecuteNonQuery(); //do the bulkcopy DbDataReader rdr = cmd.ExecuteReader(); SqlBulkCopy bc = new SqlBulkCopy(bulkCopyConnection); bc.DestinationTableName = "StoreList"; bc.WriteToServer(rdr); connection.Close(); bulkCopyConnection.Close(); Label lbl = GetLabel(275, 20); lbl.Text = "Done with bulk copy"; } |
Copy Directory from the file system
There is a missing class in the .net library to copy directory from the file system in the System.io namespace. The below code provide the functionality to copy directory to other location.
It needs two parameters source folders and the destination path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static void copyDirectory(string Src, string Dst) { String[] Files; if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar) Dst += Path.DirectorySeparatorChar; if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst); Files = Directory.GetFileSystemEntries(Src); foreach (string Element in Files) { // Sub directories if (Directory.Exists(Element)) copyDirectory(Element, Dst + Path.GetFileName(Element)); // Files in directory else File.Copy(Element, Dst + Path.GetFileName(Element), true); } } |
Ping the remote system, copy file to the remote system
Below code help you to Ping a remote system to check its status, and copy any file to that remote system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | using System; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.IO; namespace Examples.System.Net.NetworkInformation.PingTest { public class PingExample { // args[0] can be an IPaddress or host name. public static void Main (string[] args) { try { Ping pingSender = new Ping (); PingOptions options = new PingOptions (); // Use the default Ttl value which is 128, // but change the fragmentation behavior. options.DontFragment = true; // Create a buffer of 32 bytes of data to be transmitted. string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes (data); int timeout = 120; PingReply reply = pingSender.Send (args[0], timeout, buffer, options); if (reply.Status == IPStatus.Success) { Console.WriteLine ("Address: {0}", reply.Address.ToString ()); Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime); Console.WriteLine ("Time to live: {0}", reply.Options.Ttl); Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment); Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length); try { string strHostComp = args[0].ToString(); string strHostFilePath = @"\\" + strHostComp + @"\C$\perforce.txt"; if (File.Exists(strHostFilePath)) { File.Delete(strHostFilePath); Console.WriteLine ("Previous version of the File is deleted Successfuly."); } File.Copy(@"C:\perforce.txt",strHostFilePath); Console.WriteLine ("File is Copied Successfuly."); Console.ReadLine(); } catch(System.IO.FileLoadException ex) { Console.WriteLine ("File is locked by another process. Cannot be replaced."); } catch(Exception ex) { Console.WriteLine ("File is Not Copied: " + ex.Source + ex.Message + ex.StackTrace); } } else { Console.WriteLine ("Ping Cannot be reached"); } } catch(Exception ex) { Console.WriteLine ("Ping not reached: " + ex.Message); } } } } |
Check whether the current user have the admin rights
You can check the current user privilege using the identity principal of the current user. Below code helps you to check whether the current user has the Administrator privilege or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public bool CheckAdminRights() { bool IsAdmin; try { AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal; WindowsIdentity identity = (WindowsIdentity)principal.Identity; //check whether the current user principal have admin rights IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); Console.WriteLine("Identity Type: " + identity.ToString()); Console.WriteLine("Name: " + identity.Name); Console.WriteLine("'Users'?: " + principal.IsInRole("adminsys\\users")); Console.WriteLine("'Administrators'?: " + principal.IsInRole(WindowsBuiltInRole.Administrator)); Console.WriteLine("Authenticated: " + identity.IsAuthenticated); Console.WriteLine("AuthType: " + identity.AuthenticationType); Console.WriteLine("Anonymous? " + identity.IsAnonymous); Console.WriteLine("Token: " + identity.Token); Console.ReadLine(); return IsAdmin; } catch (Exception Ex) { return false; } } |








