Aug 22

I recently had to make a method that creates a random generated password in C#.
So, I looked at the web for such a function and I found this one. It was really
simple and short and just what I was looking for. But, there is always a but, it
didn’t work. So I modified it a bit, and it now looks like this and it works.

private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = “abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQR
STUVWXYZ0123456789!@$?_-”;
char[] chars = new char[passwordLength];
Random rd = new Random();

for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}

It’s that simple.

Aug 22
he first thing we need to do is to add encryption to the ViewState. This is done by editing the web.config only. We need to tell the web application to enable ViewStateMac. This will generate a hashed code and add it to the ViewState. If the hashcode is tampered with, any postback will fail. It is still not secure before we add encryption. That is also done in the web.config by telling the application to use the 3DES encryption algorithm. Add these two lines to the web.config’s section:

<pages enableViewStateMac="true" />

<machineKey validation="3DES" />

The ViewState is now encrypted on an application wide basis
Aug 22

I recently had to make a dropdownlist populated with fonts. Luckily, .NET allows you to use the installed fonts very easy.
First, add a drowdownlist to your ASP.NET page like this:

Then call this method to do the actual databinding of the fonts:

//using System.Drawing.Text;

private void BindFontsToDropdownlist()
    {
        InstalledFontCollection col = new InstalledFontCollection();

        foreach (System.Drawing.FontFamily family in col.Families)
        {

            ddlFonts.Items.Add(family.Name);
        }

    }

That’s all there is to it. Be aware that the fonts are the ones installed on

the server hosting your web page.

Aug 22

All spreadsheet applications (Excel, Calc etc.) understand semicolon separated files natively, so everyone can use this method – you don’t even have to use Excel for it to work.

public static void ExportToExcel(DataTable table, string name)

{

HttpContext context = HttpContext.Current;

context.Response.Clear();

foreach (DataColumn column in table.Columns)

{

context.Response.Write(column.ColumnName + “;”);

}

context.Response.Write(Environment.NewLine);

foreach (DataRow row in table.Rows)

{

for (int i = 0; i <>

{

context.Response.Write(row[i].ToString().Replace(”;”, string.Empty) + “;”);

}

context.Response.Write(Environment.NewLine);

}

context.Response.ContentType = “text/csv”;

context.Response.AppendHeader(”Content-Disposition”, “attachment; filename=” + name + “.csv”);

context.Response.End();

}

>

Then just call this method and pass the DataTable and the filename as parameters.

ExportToSpreadsheet(table, “products”);

The method is static so you can use it anywhere in a web application. Put it on a page, a HTTP Handler, add it to the App_Code folder or stick it in a separate assembly. As long as you call it from a web application it will work.

Aug 22

Consider that you have the following dropdown list declared in an ASP.NET page:

<asp:DropDownList id=”ddlCountry” runat=”server”/>

Then from code-behind, call this method which binds the countries alphabetically
to the dropdown:

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;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            BindCountries();
        }

    }

    public void BindCountries()
    {
        StringDictionary dic = new StringDictionary();
        System.Collections.ArrayList col = new System.Collections.ArrayList();
        foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures
        & ~CultureTypes.NeutralCultures))
        {
            RegionInfo ri = new RegionInfo(ci.LCID);
            if (!dic.ContainsKey(ri.EnglishName))
                dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());

            if (!col.Contains(ri.EnglishName))
                col.Add(ri.EnglishName);
        }

        col.Sort();

        ddlCountry.Items.Add(new ListItem("[Not specified]", ""));
        foreach (string key in col)
        {
            ddlCountry.Items.Add(new ListItem(key, dic[key]));
        }

        if (ddlCountry.SelectedIndex == 0 && Request.UserLanguages != null
        && Request.UserLanguages[0].Length == 5)
        {
            ddlCountry.SelectedValue = Request.UserLanguages[0].Substring(3);
        }
    }
}

The method first adds all the countries from the CultureInfo class to a dictionary
and then sorts it alphabetically. Last, it tries to retrieve the country of the
browser so it can auto-select the visitors country.
There might be a prettier way to sort a dictionary, but this one works.

Aug 22

Set up Internet Explorer

Internet Explorer has disabled the possibility to debug scripts by default, so the first thing to do is to enable it. In the top menu, go to Tools -> Internet Options -> Advanced. Here you need to remove the checkboxes in Disable script debugging. This is needed for Internet Explorer to tell Visual Studio about the JavaScript running in the browser.
Start debugging

In included ?js files you are now able to set break points as you normally would in C# or VB.NET. The execution stops at the break point and you are able to see the values of the variables and to move forward by hitting F10 and F11 like normal. The experience ??

exactly the same as debugging C# code.
For inline JavaScript you cannot set break points, but Microsoft did provide us with an alternative? If you add the word debugging wherever you want in the script code, the execution will stop at the word and you can debug exactly the same way as setting a break point.
For this to work, you must run Visual Studio in debug mode. That’s it, extremely powerful and easy to do. The only thing I don’t like about this is that I didn’t know about it before now. C’est la vie.

Aug 22
This is one of those little code snippets you can pull your hair out trying to find.And no help file nor book I've come across actually gives reference to it.So, surely it can't be that important? Imagine you've created an ASP.NET Web page with a search button. The user taps a phrase into a text box and presses Enter.On most regular Web pages (think: Google), the form would be submitted and the results returned. In other words, the search button is automatically "clicked" for you.However on an ASP.NET Web page, pressing Enter resubmits the form to the server,but actually does nothing .. which is pretty useless, really.So, how do you set a default button to be clicked when the user presses Enter? Simply add the following line to your page's Load event, replacing "btnSearch" with the name of your button. It uses a hidden Page method called RegisterHiddenField and works splendidly:
Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")
Aug 22
The ASP.NET web controls provide a TabIndex property, but this property only applies to Internet Explorer and can't be used to programmatically set the focus to a control of your choice. To perform this task, you'll need the help of some JavaScript code. In this case, you need to find the JavaScript object that corresponds to the control, and call its focus() method.The easiest way to handle this task is to create a function that accepts a control, extracts its client-side ID, and uses it to generate the JavaScript function required to set the focus to that control. You can then register this function so it will set the focus the next time the next time the page is sent to the user.
Here's the function you will need in C#:

private void SetFocus(Control ctrl)
{
// Define the JavaScript function for the specified control.
string focusScript = "<script language='javascript'>" +
"document.getElementById('" + ctrl.ClientID +
"').focus();</script>";

// Add the JavaScript code to the page.
Page.RegisterStartupScript("FocusScript", focusScript);
}
Aug 22
Pop-up windows, often used for advertisements and promotions, are a hallmark of the
Internet. But ASP.NET doesn't provide any mechanism for showing pop-up windows,
because your code can't interact directly with the client's browser.
The only solution is to use JavaScript, which provides the useful window.open()
function.
The window.open() function requires three parameters:
o The link for the new page.
o The frame name of the window.
o A comma-separated string of attributes that will configure the style and size
of the pop-up window. These can include the height and width attributes
(with pixel values); the toolbar, menuBar, and scrollbar attributes (set to yes or
no, depending on whether you want to display these elements); and the resizable
attribute (set to yes or no, depending on whether you want a fixed or resizable
window border).
The following C# code defines the JavaScript code for showing the PopUp.aspx web
page in a new window, and registers it to execute immediately upon the page being
posted back the next time.

string popupScript = "<script language='javascript'>" +
"window.open('PopUp.aspx', 'CustomPopUp', " +
"'width=200, height=200, menubar=yes, resizable=no')" +
"</script>";

Page.RegisterStartupScript("PopupScript", popupScript);
Aug 22
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Counter.aspx.cs"
Inherits="Counter" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>

  <script type="text/javascript">
function textCounter(field, countfield, maxlimit)

{
/*
* The input parameters are: the field name;
* field that holds the number of characters remaining;
* the max. numb. of characters.
*/
if (field.value.length > maxlimit) // if the current length is more than allowed
field.value =field.value.substring(0, maxlimit); // don't allow further input
else
countfield.value = maxlimit - field.value.length;

}

  </script>

</head>
<body>
  <form id="form1" runat="server">
      <div>
         <textarea name="message" cols="25" rows="4"
wrap="PHYSICAL" id="message" onkeydown="textCounter(this.form.message,
this.form.remLen,50);"
           onkeyup="textCounter(this.form.message, this.form.remLen,50);
"></textarea>
          <input name="remLen" type="text" id="remLen" value="50" size="3"
maxlength="3" readonly />
      </div>
  </form>
</body>
</html>