'Auto-tabbing' to next TextBox with asp.net and Javascript

If you have a form that limits characters entered into a textfield, using this simple approach you can automatically jump to the next control, making it easy for your user

Say you have a zip code field that takes in 5 numbers, next you have a state dropdown.  Your user should be able to type in the 5 digit zip code, then boom, the focus is automatically shifts to the dropdown.  It is very simple to implement.  It just requires the following JS function:


function next(currentControl, maxLength, nextControl)
    if(document.getElementById(currentControl).value.length >= maxLength)


and then just call this from a textbox in html:

<input id="Text1" onkeyup="next('Text1', '5', 'Text2')" type="text" />

Or if you are using an asp.net TextBox control:

txt1.Attributes.Add("onkeyup", "next('txt1','5','txt2')");

it's just that easy... here is an example using both asp.net and just html:

Simplified ASP.Net User Role Management Interface

Messing around with .net roles recently and I came up with a completely portable, simple user management tool

As most of my stuff is, this is not a revolution in coding, but it is useful.  This is a simple page that allows you to add and delete members from whatever roles you have defined for your asp.net project on your live project, no need for the Web Management tool (you still have to manage roles with it though).  The file is completely independant of any other code, so you don't need to do anything to get it to work, just stick in the same directory as your application and use it - customize it if you please.

Converting an Excel Spreadsheet to a DataSet, DataTable and Multi-Dimensional Array

A way to easily manipulate data from an excel spreadsheet programmatically

I work in an office environment which is dominated by Microsoft Excel spreadsheets, and so often, people want to use them in programs.  I am a SQL junky myself, but Excel is appropriate in a lot of cases, but integrating them into programs can be a pain.  More specifically, getting the data from the Excel worksheet to a form where it is workable can be a pain. 


With this example, you can see how to take in an Excel Spreadsheet to get the data into commonly manipulatable data types in c#; then you can use/change it however you want to.  This demo shows first how to put the data into a dataset, then datatable (almost the same thing), then takes the same data in puts it into a multi-dimensional array (I prefer to work it arrays).  Since this is a linear progression, the demo only outputs the information from the array into an html table to show that it worked. 


The demo uses the very first row as the column names (as it is used in datatable) and assumes that the Spreadsheet is in default format with Sheet1 as it's first sheet.  The demo only processes Sheet1.  This can be easily customized if you want to process more. 


With this, you can take/change/display the excel data however you want to using asp.net controls like ListView or GridView or just simple c#.  The code is pretty well commented, so you should be able to pull the parts that you may need.  *NOTE: you need full trust enabled for this to work properly.

Simple Mail Classes - Easiest way to send email and/or gmail via asp.net

two classes that you customize and put into your App_Code folder which will allow you to send email with less code and greater ease than ever before

I have all sorts of programs that need to send email, whether its my own project (I use gmail) or a work project (local smtp). I got tired of what was essentially the same code filling up large chunks of my codebehinds.  I had error pages emailing our dev team, registration pages emailing event coordinators, and things such as that - that can turn out to be a lot of code; not even to mention if something needs to be changes on any sort of scale.  So, I made a couple classes that make it even easier to send mail throughout my apps, and this is all you need for code to send an email:

email message = new email();
or, for gmail:
gmail message = new gmail();

It is really that easy, you don't even need to include System.Net.Mail; in your page.  But that is using the default settings which you set the first time you set the code, it is just as easy to define many other aspects of the emails, such as to, from, subject, body, etc.  But the beauty comes with the default settings so you code can be as clean as possible.


Say you usually send your system emails from the address System@awesomeCo.com , the subject/body is usually "System Error", the recipient is most often webmasters@awesomeCo.com, and your SMTP will likely always be the same (as I would assume it would) - simply set that as your default_from, default_subject, default_body default_to, and default_SMTP to those values, and you will need nothing other than the above code to send an email.  But say on the same app, you want to send something to customerservice@awesomeCo.com you want the subject to be "complaint" and the body to be something you collected from a TextBox (txtComplaint) control in your code - that is no problem at all

email message = new email("customerservice@awesomeCo.com", "complaint", txtComplaint.Text);

All the other default settings will still take place unless you override them, and all settings can be overwritten.


There is also a few methods added like .addTo(string emailAddress) and .addCC(string emailAddress) which do exactly what you would think they do.  The gmail class works exactly the same as the email class.


It's no coding breakthrough, but it is convenient!



kick it on DotNetKicks.com

SQL Search Control for your page using asp.net :: code

Providing only keywords, this tool will write a simple search query, run it, and display your results; lightweight and easy to customize; in both control form, and standalone page

I was tired if writing SQL for doing simple queries on my databases, especially when they got loooong... so I ended up writing a program to do it for me.  Now this is in no way a complex search tool, but it does its job.  It does use 'LIKE' as I needed it to search text fields, but you can change that out if you want - this will get you started.


All you need to do to get it running is to provide 3 values: 

  1. Either your DB ConnectionString, or the name of that ConnectionString in your web.config
  2. The name of the table you wish to search
  3. The column names you want to compare to the search terms

And that is it.  The search is delimitted by [space], [comma], [semicolon], and [plus-sign] and each keyword must show up in at least one of the fields in order for the search to return results.


I provided both a standalone page that runs the search on itself, and a control version that consists of a user control that you can insert anywhere, and a search.aspx page that will show the results.  The control is very versatile. 


This is a good starting point if you want to expand on it.  I made a fully customized search at work starting with this with multiple dropdowns, fields and textboxes, all built on this basic architecture.  Play around with it and tell me what you think - I would even write a tutorial on how this thing works if anyone is interested.

Introductory tutorial on using objects to pass information from page to page

Passing asp.net information between pages can get quite messy, unless you clean it up using objects

 Recently on a forum I was asked to help out a user on passing information between pages using asp.net.  After some contemplation, I figured the cleanest way to do this would be through an object passed as a variable.  Basically, take in some information on page one, manipulate it, and regurgitate it on page two.


 For this tutorial, I will be referencing the demo that I have uploaded: passing_with_objects.zip (4.06 kb) Also, this tutorial assumes you are using Visual Studio or the Free version: Visual Web Developer Express


First we need to think of how we are going to pass the information. Since we are going to another page, we have to store it somewhere as html is stateless, and you are using .net controls and not a regular POST. So, we have a few options:

1. Store variables for each value
2. Construct a single object and store that
3. Use a PreviousPage declaration
4. Use a querystring


I vote for 2, as it is cleaner, and more scalable. Next you need to make an object by right clicking in your solution explorer, clicking 'add new item' and choose 'class' - name it what you will, I chose 'employee'. (its going to ask you to put it in the app_code folder, you want to do this).  Now you need to define what the object has for properties, and how you are going to set and access them.  This is what I came up with:

//here you declare all of the properties that each 'employee' object will have
string name;
string id;
public employee() { }
// this one actually builds an employee object - requires 2 strings as of now, but you can add more
public employee(string nameInput, string idInput)
  name = nameInput;
  id = idInput;
// methods - returns what will be pulled from the employee obect here
public string showName() { return name; }
public string showId() { return id; }

With that you can see that an employee has both an ID and a Name property, they are both strings and are set by calling employee(name, id).  So now we have our object class... let's use it.

We have 2 textboxes, txtName and txtId, that will hold, you guessed it, name and id. I also added RequiredFieldValidators to try and make sure we get no errors, requiring the user to enter values before they submit.


Add a submit button and double click on it in design mode, that will auto-populate a Click event in your code behind to tell your page what to do when it is clicked. here you will make an empoyee object, and then set it to a session variable - then kick it to the display page:

protected void btnSubmit_Click(object sender, EventArgs e)
{//builds new employee object
employee newEmployee = newemployee(txtName.Text, txtId.Text);  Session["employee"] = newEmployee; 

  //put it in session state memory
  Response.Redirect("DisplayData_Class.aspx");//sends you to the next page

And then we make the showEmployee() method by calling the methods we made in teh employee class we made earlier:
protected void showEmployeeInfo()
  employee passedEmployee = new employee();//makes the new object
  //copies the one you just made
  passedEmployee = (
employee)Session["employee"];//display info
  lblName.Text = passedEmployee.showName();
  lblId.Text = passedEmployee.showId();

And boom, you are all done. Now just go through and add the properties to the object you need and ways to access and set them and you will be done in no time.


Sending email programmatically with gmail :: tutorial

worry about smtp servers/settings no longer; completely portable code for sending email with gmail and asp.net

I have used a ton of different hosts, and it always seems to be a hassle to find out their information on their smtp servers... not to mention all of your programs are broken if you move them.  With .net, you don't need to use anything but gmail's own protocols in order to make fully portable code that sends emails, and it is oh-so-simple!  I use this from everything from contact pages to email notifications to myself on errors and such - hope it helps.


First thing you need to do is declare you will be using the System.Net.Mail namespace as the System.Web.Mail is deprecated as of the past year or so.


Next, you simply have to make a new MailMessage and set its properties like To, From, Body, Subject, etc.  here is an example with all static input:


MailMessage email = new MailMessage();
MailAddress maFrom = new MailAddress("from@address.com");
email.From = maFrom;
email.Body = txtMessage.Text;
email.IsBodyHtml = true;//this is only if you are sending an html message
email.Subject = txtSubject.Text;


Now that the message is made, all you have to do is set your smtp credentials, and push the message out:

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25);
smtp.EnableSsl = true;

smtp.Credentials = new System.Net.NetworkCredential("address@gmail.com", "password");



That's it!  It is just that easy... 


You can get a fully working example here:


apparently viewstate variables time out?

a peculiar error that didn't make much sense to me...

For the past couple years, I have kept up a website that makes auction ads for sites like eBay if the user simply fills in a few blanks - the website is AuctionConstructor.com (it's free, check it out). Now this isn't just a shameless plug for my awesome and useful website... I was having the most annoying problem with it for the longest time.

If the user filled in the blanks within a decent amount of time, say 2-3 minutes, everything would work just fine. BUT, if the user took a long time to fill them out, they would get this awesome (read: incredibly annoying) error:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
As far as I always knew, ViewState variables in ASP.NET did not timeout? Not to mention that I am not being hosted on a cluster. After digging and digging on forums all over the place I found this: http://connect.microsoft.com/VisualStudio/ feedback/ViewFeedback.aspx?FeedbackID=101988 and it appears that:
It appears because GridView using DataKeyNames requires ViewState to be encrypted. And when ViewState is encrypted, Page adds <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> field just before closing of the <form> tag. But this hidden field might not bet yet rendered to the browser with long-running pages, and if you make a postback before it "gets down", browser initiates postback without this field (in form post collection)

End result is that if this field is omitted on postback, Page doesn't "know" that viewstate is encrypted and causes the prementioned Exception. E.g Page expects to be fully-loaded before you can make a postback. And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form.
And since that is not completely my problem considering this happens prior to the page loading, where my error happened much, much later than that I then made the assumption that the ViewState tiems out therefore the same thing happens where the page doesn't "know" that viewstate is encrypted and causes the error.

So... I after attempting a few different solutions, the final answer to my problem (and over a years worth of errors) is the following change to your web.config file:
<pages enableViewStateMac="false" enableEventValidation="false" viewStateEncryptionMode ="Never" >
Keep in mind, that this could cause some security issues, but I wouldn't see that being a huge problem - basically, your program will not be sure that it is the same computer posting back that opened the page int the first place, but in the case of my site, this is not a concern as I am not dealing with any sensitive information. I would think this error wouldn't rear it's ugly head as often on a page where there is sensitive information, as it usually does not take a huge amount of time to fill out that information.

*This is on a .NET 2.0 server, and hopefully 3.5 has it fixed (my host upgrades February 2008) as it is a recognized problem by Microsoft.
Another great link: http://forums.asp.net/p/955145/1173230.aspx#1173230