VB vs C# experiment - Random shift generator for your employees

Some random programming in both C# and VB, using lists, objects, ternary operators, etc.

Now normally, I would never write anything in VB, it kind of annoys me.  But I was bored this last weekend (nothing to do in Kuwait) and I was helping someone out on Experts-Exchange (it's something I do when I am bored) when I came across a problem that looked kind of fun:  The guy had a bunch of employees, three shifts (24 hours) and weekends were in no way tied to any specific day.  He wanted to randomly generate a schedule (I am assuming this would be to eliminate the idea of favoritism/complaining).  Either way, I was bored and this sounded interesting - it was a request in VB, but since I hadn't done VB in a while, I figured brushing up wouldn't hurt.  I wrote it first in C#, then translated to VB.  Here are the two programs in action (not that there is any functional difference):


Shift Shuffler in C#

Shift Shuffler in VB


I did originally write it in C#, then translated to VB, though some things are a bit different in each, so don't expect a one-for-one comparison, though the logic is the same.   One thing I was really surprised at was the fact that my VB code was considerably shorter (86 vs. 116 lines) than my C# despite my C# being a lot more concise and cleaner.  For example I used ternary operators in C# as opposed to if-thins in the VB which are a lot longer (1 line as opposed to 5).  I did have a 10 line summary in C#, but it was still surprising.  Looking at this, I figured it was due to {'s and }'s as I like to have them on their own lines, but at least half of those could be directly compared the 'End' statements of VB.


I found that the Dim statements in VB got do me a little annoying, and the whole byVal, As, and all that redundant junk seemed to be unnecessary.  I also found it hard to kick the old habit of ending every line with my trusty semi-colon as well.  And I noticed it took about 5 minutes to change 'modes' in my head from one language to the other, but overall, they are really the same thing and knowing one basically means you know the other. 


Either way, I still like my C# better, but doing an exercise like this helps keep even the best programmers sharp, as knowing cross-language translation and even being able to read the 'other' language is often helpful when searching for solutions or helping out a co-worker that has gone to the dark-side. If you ask me C# is better!  It's my site, and what I say goes.


Anyways, here is the code if anyone is interested, it requires you set up your own data access (I used Linq) or just manually add in employees.  It's not perfectly balanced with smaller groups of people, but it does a pretty good job.

Getting the row or sql value/index of the gridview row you just clicked

Getting the row you just clicked is not as obvious as it seems first hand

There are generally two cases that I need information from the row I clicked in a GridView (or listview, etc.).  The first being simply to get the index in the gridview, whether or not it was the first, fifth or 50th row.  That is pretty easy, but the second case, getting the index (or any) value of the SQL entry of the row just clicked is a little less obvious, though still pretty easy.  Here is a better explanation of that second one if it isn't clear: Say you have a GridView bound to a SqlDataSource (or Linq, etc.) and you have an column in that table that is Product_ID.  Your user is going to click on a button in one of those rows, say it is row 15, but the item Product_ID is 547.  You want to get 547 with no other information than the _Click event.


This is how you do it:



protected void btn_Click(object sender, EventArgs e)
   Button btnClicked = (Button)sender;
   // This will get you your GridViewRow
   GridViewRow row = (GridViewRow)btnClicked.NamingContainer;
   // This will get you the actual Index out of your SQL table
   string getIndex = this.GridView1.DataKeys[row.RowIndex].Value.ToString();
   // And this will just print it out to show it works
   Response.Write("Row Index: " + row.RowIndex.ToString() + "<br />");
   Response.Write("Sql Index: " + getIndex);


***IN ORDER FOR THIS TO WORK, you *have to* remember to add DataKeyNames="Product_ID" to the GridView tag, otherwise you will throw an OutOfBounds exception because your program won't know what the hell you are calling with DataKeys. 

Keep in mind this trick will work for any column in your table. I use this in my own app to populate a modal popup depending on what row was clicked, works very slick. 

The non-generic type 'System.Collections.IEnumerable' cannot be used with type arguments

This is an error that was driving me crazy while I was trying to get a recursive LINQ call to work; the fix is ridiculously simple and just an oversight

 First you have to understand that IEnumberable has both generic and not-generic usage.  That was my problem.  In my code, I included the using System.Collections; namespace and in my code I was doing the following:

 IEnumerable <test_order> orders = db.getOrdersByCustomer(1);

Where test_order was type produced with a Linq to Sql Class and getOrdersByCustomer was a Stored Procedure. 

I kept getting the error:

The non-generic type 'System.Collections.IEnumerable' cannot be used with type arguments 

Which basically told me my problem, but I was too blind to see it at first.  Since I was just calling the System.Collections.IEnumerable, and not the System.Collections.Generic.IEnumerable, I was not allowing the use of generics; hence the error.  Simple add the following to you code and you will not have this error any longer: 

using System.Collections.Generic;

Ternary operators simplified

For a while there, I would see mystical things happening in some code I viewed, and I had no idea what was happening - turn out the bla?bla:bla does mean something, and it is useful and simple

These?are:called ternary operators, and they can be very useful, especially when you want to clean up your code.  A lot of people say that they are hard to read, but I think that is merely because they do not understand how simple they really are. I will show you just how simple they are; here is a statement using a ternary operator:



a ? b : c ;



And all this means in simple terms is:



if a is true, then b is the value of the statement, else c is the value of the statement



or if you prefer code:



  return b;
  return c;



That really is it, it is that simple. Ternary operators can save a lot of space, and more important (to me) they can easily be used inline, cutting out chunks of code completely.  Take a look at the following for an example:


string s1 = "party";
string s2 = "crom";
string s3 = "arnold";
bool b1 = true;
bool b2 = false;
string s4, s5;

//All of this code:
if (b2)
  s4 = s1;
  s4 = s2;

if (b1)
  s5 = s1;
  s5 = s2;

//can be replaced by this
s4 = b2 ? s1 : s2;
s5 = b1 ? s1 : s2;

//plus you can easily use it inline
Response.Write("inline = " + (b2 ? s2 : s3).ToString());


You can make them much deeper and more complicated and then they may begin to get difficult to read, but for a lot of everyday tasks, ternary operators are great and space saving!


Intro to Lambda Operators

There has been a lot of buzz about lambda operators, so I decided to check them out; turns out they are pretty useful

Not necessarily epic in thier abilities, but lambdas can be a nice way to clean up code and make your programming better in general (if you use them right).  For a quick show of what they can do, compare this function

public int f1(int x, int y, int z)
  return (x + y) * z;
to this:
Func f2<int, int, int, int> = (x, y, z) => (x + y) * z;
They do basically the same thing, but the second one is much cleaner. It might seem a bit hard to read, but it isn't if you break it down. Think of it like this:
Function with 4 integers (3 in, 1 out) named f2 equals what you get with the inputs x, y and z which go to (x + y) * z
The key here is the 'go to' meaning those variables go into the following function, which in turn, returns to f2... if that makes sense. This is not just a new way to do functions, you can also use lambdas inline which is where they really shine. There is an awesome post here: http://blogs.msdn.com/.../lambda-lambda-lambda.aspx that shows how to use this in an inline generic list sort which chops 5 lines of code down to just 1... that ay not seem like a lot, but it can relly add up.

This is a very basic intro to Lambda Operators and they can do much more, this is just to get your gears turning.
More info: http://msdn2.microsoft.com/.../bb397687.aspx

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.