SQL Select records by the hour or the half hour

Here is a handy SQL snippet to select records by the half hour in a certain date range.

SELECT DATEADD(mi, DATEDIFF(mi,0,[LoginTime])/30*30,0) as LoginHour, Count(*) as NumberOfUsers FROM[my_db].[dbo].[MyTable] WHERE [LoginTime] BETWEEN '{0} 00:00:00.00' AND '{0} 23:59:59.999' GROUP BY DATEADD(mi, DATEDIFF(mi,0,[LoginTime])/30*30,0) ORDER BY DATEADD(mi, DATEDIFF(mi,0,[LoginTime])/30*30,0)

The result set will look something like this:

 

Here is a code to select by the hour if you don’t need to go down to the half hour

SELECT datepart(HH, [LoginTime]) as LoginHour, Count(*) as NumberOfUsers

FROM[my_db].[dbo].[MyTable]

WHERE[LoginTime] BETWEEN '09/07/2017 00:00:00.00' AND dateadd(dd, 1, '10/20/2017 23:59:59.999')

GROUP BY datepart(HH, [LoginTime])

ORDER BY datepart(HH, [LoginTime])

 

And the result set will resemble this:

 

Here is a snipped to get a all records regardless of the date, and count by the half hour.

SELECT substring(CONVERT(VARCHAR, DATEADD(mi, DATEDIFF(mi,0,[LoginTime])/30*30,0), 108),0,6) as LoginHour, Count(*) as NumberOfUsers FROM[my_db].[dbo].[MyTable]  GROUP BY substring(CONVERT(VARCHAR, DATEADD(mi, DATEDIFF(mi,0,[LoginTime])/30*30,0), 108),0,6) ORDER BY substring(CONVERT(VARCHAR, DATEADD(mi, DATEDIFF(mi,0,[LoginTime])/30*30,0), 108),0,6)

Error checking with ASP classic VbScript

Here is a handy snippet for those rare occasions when you bother to error check.

 

If Err.Number <> 0 Then
subject = "Error creating early alert"
email_message = "There was the following error while creating an early alert record: " & Err.Number & " : " & Err.Description
sendEmail adminEmail, email_message, from_email, subject
End If

Can deliver a helpful error message such as:

There was the following error while creating a record: -2147217900 : Unclosed quotation mark after the character string ‘Failed a quiz/test’.

Prepend text “Select Value” to a databound dropdown list c#

You have a dropdown list, populated via sql data source, and you want it to have “Select a value” as the first selected option.

protected void DropDownList2_DataBound(object sender, EventArgs e)
        {
            DropDownList list = sender as DropDownList;
            if(list != null)
            {
                list.Items.Insert(0, "--Select Date--");
            }
        }

Loop through Visual Studio checkbox list c#

Its a bit easier using Javascript, but here is how to use c# and loop through the variables in a checkbox list control from Visual Studio.

You have a Checkbox List control on your page: CheckBoxList1. You  loop through the list of items and use the data…

In your codebehind, you are in a function to gather the data from objects:

myFunction(){...
// doing stuff
// need to get the data from the check box list checked items
string selectedItems = "";

for(int i = 0; i < CheckBoxList1.Items.Count; i++)
   {
      if (CheckBoxList1.Items[i].Selected)
                {
                  selectedItems += CheckBoxList1.Items[i].Value + ", ";
                 }
    }


...}

If the checkbox list had selected values of SUN, WED and FRI then the string selectedItems would contain the text : “SUN, WED, FRI, ”

I would use  a trim to remove the trailing comma.

 

Here is another method that casts the Checkbox items as a list and uses for each to loop through.

string FoundScholAppSport = "";
 foreach (ListItem val in CheckBoxListSports.Items)
 {
      if (val.Selected)
      {
          FoundScholAppSport += val.Value + " ";
      }
 }

Create Data Table C# datatable

Sometimes need to hand craft a data table for use.

DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new System.Data.DataColumn("EventTitle", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("EventID", typeof(String)));
        dr = dt.NewRow();
        dr[0] = "Emergency Alert";
        dr[1] = "Event Id";

      dt.Rows.Add(dr);

Here is how you could use that in a function to return the datatable:

 private DataTable GetDummyData()
 {





DataTable dt = new DataTable();
 DataRow dr;
 dt.Columns.Add(new System.Data.DataColumn("EventTitle", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("EventID", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("Start_Time", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("End_Time", typeof(String)));
 dt.Columns.Add(new System.Data.DataColumn("EventDetails", typeof(String)));


dr = dt.NewRow();
 dr[0] = "Christmas Party";
 dr[1] = "1";
 dr[2] = "12/23/2017 12:00:00";
 dr[3] = "12/23/2017 14:00:00";
 dr[4] = "Please drop by our Christmas party and bring gifts!";
 dt.Rows.Add(dr);

return dt;
 }

Custom command button in ASP gridview C#

A powerful feature to add your own button to the gridview and have custom commands. Most basic is you would want to pass the id of the record so you can do stuff to it.

In your gridview add a templatefield with a button as so…

<asp:TemplateField HeaderText="Actions">
     <ItemTemplate>
            <asp:Button runat="server" CssClass="btn btn-sm btn-danger" Text="Do Something" CommandName="CustomFunction" CommandArgument='<%# Eval("Id") %>'  /> 
     </ItemTemplate>
</asp:TemplateField>

 

Then you use the RowCommand event of the gridview to do what you need to…

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CustomFunction")
            { string recordId = e.CommandArgument.ToString(); 
               // do what ever you need to do with the record id
             }
        }

Validate a textbox entry c# using tryParse

In strongly typed language, there is no room for error when a user enters data that is expected to be put into a data storage system.

For example, I need to covert an input from textbox1 that is supposed to be a number to be used in a total:

 int fundAmt = Convert.ToInt32(TextBoxPersonalFundAmt.Text);

 

If the user enters unexpected non numeric characters, this conversion will fail and make your app error out. Instead of directly trying to convert, we can cast a Boolean on our input data using TryParse to parse the number into an integer…

bool isNumeric = int.TryParse(TextBoxPersonalFundAmt.Text, out n);

Now we can validate the input and perform the necessary calculations with the numbers.

 

int fundAmt;
bool isNumeric = int.TryParse(TextBoxPersonalFundAmt.Text, out fundAmt);
       if (!isNumeric)
            {
              errInfo += "Error: Its not a valid number in the amount box ";
               lblLogErr.Text = errInfo;
                 pageValid = false;
                } else
                {
                    // calculate the total
                }

 

Another good example is the date field. A user is expected to enter  a valid date for their birthday. There are many ways that a user would normally express that date. We of course use a client side validation to ensure that the format is entered correctly, but we need to have a server side validation of that data as well.

 

DateTime SponsorSigDate;
            if(!DateTime.TryParse(TextBoxSponsorDate1.Text, out SponsorSigDate))
            {
               
                pageValid = false;
                errInfo += "Error: Enter a valid date. ";
            }