C# Simple Password Generator

One of the simplest and easiest approach to generating random passwords, is to use the GetRandomFileName() static method from the Path class.

Snippet below demonstrates this.

   1: using System;

   2: using System.IO;

   3:  

   4: static void Main(string[] args)

   5: {

   6:     // Calls the static method from the Path type

   7:     var randomFolderFile = Path.GetRandomFileName();

   8:  

   9:     // Strips out dot characters

  10:     randomFolderFile = randomFolderFile.Replace(".", ""); 

  11:     Console.WriteLine(randomFolderFile);

  12: }

Happy Coding.


ASP.NET DataView Paging and Sorting.

This post demonstrates the use of the DataView class for simplifying Paging and Sorting operations on a GridView control.

Prior to getting into the workings of it, do note, that I’m using data from Northwind Customers table. Essentially, all I am doing is retrieving the ContactName, CompanyName and Country from all Customers records and returning them as an IEnumerable<T> object in my Data Access Layer.

To begin, I have a GridView control defined with 3 literal controls. Do note, the SortExpression defined on each TemplateField. Also note the OnSorting and OnPageIndexChanging events.

   1: <asp:GridView runat="server" 

   2:               ID="customersGrid" 

   3:               CellPadding="5" 

   4:               CellSpacing="3" AutoGenerateColumns="False" 

   5:               AllowSorting="True" 

   6:               OnSorting="CustomersSorting" 

   7:               AllowPaging="True" 

   8:               PageSize="15" 

   9:               OnPageIndexChanging="CustomersPageChaging" 

  10:               CssClass="gridStyle">

  11:     

  12:     <Columns>

  13:         <asp:TemplateField HeaderText="Name" SortExpression="Name">

  14:             <ItemTemplate>

  15:                 <asp:Literal runat="server" ID="customerName" 

  16:                              Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>'>

  17:                 </asp:Literal>

  18:             </ItemTemplate>

  19:         </asp:TemplateField>

  20:         

  21:         <asp:TemplateField HeaderText="Company" SortExpression="Company">

  22:             <ItemTemplate>

  23:                 <asp:Literal runat="server" ID="customerCompany" 

  24:                              Text='<%# DataBinder.Eval(Container.DataItem, "Company") %>'>

  25:                 </asp:Literal>

  26:             </ItemTemplate>

  27:         </asp:TemplateField>

  28:         

  29:         <asp:TemplateField HeaderText="Country" SortExpression="Country">

  30:             <ItemTemplate>

  31:                 <asp:Literal runat="server" ID="customerCountry" 

  32:                             Text='<%# DataBinder.Eval(Container.DataItem, "Country") %>'>

  33:                 </asp:Literal>

  34:             </ItemTemplate>

  35:         </asp:TemplateField>

  36:     </Columns>

  37: </asp:GridView>

Then on the code-behind, I’ve set up a property called SortOrder. This property keeps track of the ViewState[“SortOrder”] value that is saved on page postbacks.

   1: public string SortOrder

   2: {

   3:     get

   4:     {

   5:         if (ViewState["SortOrder"].ToString() == "DESC")

   6:         {

   7:             ViewState["SortOrder"] = "ASC";

   8:         }

   9:         else

  10:         {

  11:             ViewState["SortOrder"] = "DESC";

  12:         }

  13:  

  14:         return ViewState["SortOrder"].ToString();

  15:     }

  16:     set

  17:     {

  18:         ViewState["SortOrder"] = value;

  19:     }

  20: }

The Page_Load method, sets the SortOrder property to an empty string, then calls a custom method to bind the data to the GridView control.

   1: protected void Page_Load(object sender, EventArgs e)

   2: {

   3:     if(Page.IsPostBack) return;

   4:  

   5:     ViewState["SortOrder"] = "";

   6:     BindCustomersGrid("","");

   7: }

The custom bind method that is called from the Page_Load method takes in 2 string parameters. The parameters define the sort expression and the sort direction.

The method first checks if the sort expression is not an empty string. If it isn’t empty it then proceeds to use the DataView Sort property, prior to binding the data to the GridView control.

   1: private void BindCustomersGrid(string sortExp, string sortDir)

   2: {

   3:     // Custom method is called and DataView object is returned.

   4:     var view = GetCustomerData();

   5:  

   6:     // Check if Sort Expression is available.

   7:     if (sortExp != string.Empty)

   8:     {

   9:         view.Sort = string.Format("{0} {1}", sortExp, sortDir);

  10:     }

  11:  

  12:     // Bind data to GridView control.

  13:     customersGrid.DataSource = view;

  14:     customersGrid.DataBind();

  15: }

The custom method that returns the DataView object as shown in snippet above, is define in snippet below.

   1: private static DataView GetCustomerData()

   2: {

   3:     // Initialise and construct new DataTable

   4:     using (var table = new DataTable())

   5:     {

   6:         table.Columns.Add("Name", typeof(string));

   7:         table.Columns.Add("Company", typeof (string));

   8:         table.Columns.Add("Country", typeof (string));

   9:  

  10:         // Retrieve customer records from database layer

  11:         // and populate DateTable rows.

  12:         foreach (var customer in CustomerData.GetAllCustomers())

  13:         {

  14:             table.Rows.Add(customer.Name, customer.Company, customer.Country);

  15:         }

  16:  

  17:         return table.DefaultView;

  18:     }

  19: }

Now we come to the core part of this post. How do we perform sorting? Well, if you have followed the snippets along you would have noticed the custom bind method takes in 2 parameters. It then checks the sort expression parameter for a value, then uses the DataView Sort property to apply the sorting. Not too complex, but the easier bit is on the GridView OnSorting event as show below. Basically, calling the custom bind method by passing in both, the sort expression and the sort order.

   1: protected void CustomersSorting(object sender, GridViewSortEventArgs e)

   2: {

   3:     // Sorting is performed by calling custom bind method and specifying

   4:     // sort expression as defined in GridView control and the SortOrder

   5:     // property value.

   6:     BindCustomersGrid(e.SortExpression, SortOrder);

   7: }

Now to the next part of the post which is, How do we perform paging?. Well, on the GridView OnPageIndexChanging event, a new page index is set based on the GridViewPageEventArgs passed in, then the custom bind method is called again.

   1: protected void CustomersPageChaging(object sender, GridViewPageEventArgs e)

   2: {

   3:     customersGrid.PageIndex = e.NewPageIndex;

   4:     BindCustomersGrid("", "");

   5: }

Hope the post helps show how easy it is to get Paging and Sorting operations working, through the use of a DataView object.


Error Object cannot be cast from DBNull to other types.

This happens when the database is returning an object of type DBNull. Best approach towards handling this error would be to check if the object is of type DBNull first, before attempting to use it. Sample snippet below demonstrates this, using the Convert.IsDBNull method.

   1: var reader = command.ExecuteReader() // assumes SqlCommand has been initialised

   2:  

   3: if(!Convert.IsDBNull(reader["DateInDatabase"])) // if it is not returning DBNull

   4: {

   5:     // Do Something

   6: }

Hope this helps.


C# Sort DateTime in List<>

Do you need to sort your list of objects/types by DateTime? The snippet sample below shows you how.

UPDATED 21/02/2012

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4:  

   5: static void Main(string[] args)

   6: {

   7:     var times = new List<string>

   8:                     {

   9:                         "18 APR 6:30 AM",

  10:                         "14 MAR 4:50 PM",

  11:                         "17 APR 3:15 PM",

  12:                         "14 MAR 11:25 AM",

  13:                         "22 OCT 11:25 PM"

  14:                     };

  15:  

  16:     #region Appended

  17:     

  18:     var temp = new List<string>();

  19:  

  20:     // Split the string then add in year value into new string.

  21:     // The new string format can be converted to a DateTime type.

  22:     // Add new string into a new collection.

  23:     for (var i = 0; i < times.Count; i++)

  24:     {

  25:         var splitTime = times[i].Split(' ');

  26:         var newTimeFormat = splitTime[0] + " " + splitTime[1] + " 2012 " + splitTime[2] + " " + splitTime[3];

  27:  

  28:         temp.Add(newTimeFormat);

  29:     }

  30:  

  31:     #endregion

  32:  

  33:     #region Updated

  34:  

  35:     var list = temp.Select(Convert.ToDateTime).ToList();

  36:     // The above line is equilevant to the line below.

  37:     // var list = times.Select(t => Convert.ToDateTime(t)).ToList();

  38:  

  39:     #endregion

  40:  

  41:     list.Sort(DateTime.Compare);

  42:     // The above line is equilevant to the line below.

  43:     // list.Sort((d1, d2) => DateTime.Compare(d1, d2));

  44:    

  45:     foreach (var date in list)

  46:     {

  47:         Console.WriteLine(date);

  48:     }

  49: }

Hope this helps.


C# Remove from a collection after comparing another collection.

This post shows you how it’s possible to compare two list collections and remove items/object when they do not match.

I have, for the purpose of this post, created a simple Record entity.

class Record
{
    public int Id { get; set; }
    public string Title { get; set; }
}

Now I instantiate some record objects, and add them to two separate collections. Note how primaryRecords has duplicate objects of Record1? Also, note that secondaryRecords also has an object of Record1.

var primaryRecords = new List<Record>
                         {
                             new Record {Id = 1, Title = “Record1″},
                             new Record {Id = 1, Title = “Record1″},
                             new Record {Id = 2, Title = “Record2″},
                             new Record {Id = 3, Title = “Record3″}
                         };

var secondaryRecords = new List<Record>
                           {
                               new Record {Id = 1, Title = “Record1″},
                               new Record {Id = 4, Title = “Record4″},
                               new Record {Id = 5, Title = “Record5″}
                           };

Now, I compare my secondaryRecords and my primaryRecords to ensure that only unique records within the secondaryRecords is made available.

This is first accomplished by getting unique record objects from primaryRecords, which is achieved through the use of a HashSet<>  object with little bit of lambda sprinkled in.

using System.Collections.Generic;
using System.Linq;

// HashSet is used to eliminate duplicate records from primary record
var recordIds = new HashSet<int>(primaryRecords.Select(r => r.Id));

// remove records that also exist in recordsId
secondaryRecords.RemoveAll(r => recordIds.Contains(r.Id));

A console output of enumerating and displaying secondaryRecords would be as below.

Record4
Record5

Hope this helps you in moments of madness dealing with multiple collections.


SharePoint Web Part Debugging

NOTE: This applies to going through the steps manually using Visual Studio 2010. And the issue in concern, is breakpoints not being hit.

Debugging web parts in SharePoint are not difficult, but they can be annoying. This article on MSDN, (albeit an old one) describes how this can be achieved.

Essentially, ensure that the web part assembly is part of your web.config safe control list. Then, from Visual Studio, select Debug –> Attach to Process. This is where you will need to select the application pool IIS Process, which will be w3wp.exe.

Now you can set your breakpoint and begin debugging….right? Well not exactly, chances are you will run into a problem in which, the breakpoint will currently not be hit.

This is because we are trusting Visual Studio 2010 to determine the type of code being debugged. We’ll have to change this, by selecting Debug –> Attach to Process, then under Attach To, click Select.

Note the option, Automatically determine the type of code to debug

image

Click and Select Debug these code types option. The tick and select Managed (v2.0, v1.1, v1.0), click on OK, then attach the w3wp.exe process.

image

Now set you breakpoint and begin debugging your web part. The issue of not hitting a breakpoint will not occur again.


C# Working with Timer Object

A timer object can be really helpful when there is a need of some form of scheduling. For example, writing entries into a log file hourly. MSDN defines the Timer class as an object that generates recurring events in an application.

The code snippet below shows a simple example using Timer to write out a line every 5 seconds (console application).

   1: using System;

   2: using System.Timers;

   3:  

   4: static void Main(string[] args)

   5: {

   6:     BeginSchedule();

   7:     Console.ReadKey();

   8: }

   9:  

  10: private static void BeginSchedule()

  11: {

  12:     var timer = new Timer

  13:                     {

  14:                         // Gap between each event execution

  15:                         // set to 5 seconds in miliseconds.

  16:                         // Then timer is started.

  17:                         Interval = 5000,

  18:                         Enabled = true

  19:                     };

  20:  

  21:     // Event that is called after each timer interval.

  22:     timer.Elapsed += new ElapsedEventHandler(TimerElapsedEvent);

  23: }

  24:  

  25: static void TimerElapsedEvent(object sender, ElapsedEventArgs e)

  26: {

  27:     Console.WriteLine("5 seconds later.");

  28: }

Code well.


Follow

Get every new post delivered to your Inbox.