Category Archives: C#

Change Login Using Windows Authentication

Recently I had a need to allow users to change their login on an MVC site that used Windows authentication.  Of course we did not want the user to log out of their machine to do it.  The trick of course involved sending a 401 response, but how to do that and not get stuck in an endless loop.

The 401 Loop

It seemed simple enough, in fact too simple.  You just return a 401 challenge and have them move on to their previous page.  The 401 response is what presents the user with the Windows login popup.  In reality the 401 response acts like a redirect on itself, so you get two page loads and it forgets any variables you set.

Well that simply would not do. Read the rest of this entry


Application Event Logging

The Art of Logging

Log Book

During my time as a Naval Nuclear Field Machinist Mate I did a lot of logging.  The data points we logged were not for busy work, they had a reason and a purpose.

Logging certain data points around the same time multiple times a day is a lot of data.  As you know this data lets you see trends, maybe detect a potential equipment failure before it happens.

Application logging in the enterprise is not much different.  The hard part is knowing what to log, where to log, and how to log it.  I hope this article will help you answer some of those questions.



Read the rest of this entry

Collection Was Modified; Enumeraton Operation May Not Execute

Some Background

This was a very interesting bug for me to track down.  Initially it did not bubble up as the error that is in this title.  Initially it revealed itself as an out of bounds error when I tried to set IsOpen to true for a ContextMenu in a Silverlight project.  After lots of debugging I finally landed on this culprit.

The Task

The task I was trying to accomplish was pretty straight forward.  Given a List<T> remove any duplicate entries based on a given object.  Again, a straight forward task, or so I thought.

foreach(MyClass item in myListOfMyClass)
    if(item.SomeValue == objectOfMyClass.SomeValue)

Read the rest of this entry

Left or Right Curly Braces

Should you put your curly braces on the left or right?

function foo(){
    //My curly brace is on the right.

function bar()
    //My curly brace is on the left.

Read the rest of this entry

Using LINQ to Sort by Day of Week And Time

So a couple weeks ago I saw a question on the ASP.Net or MSDN forums.  Someone wanted to know how to use LINQ to sort by the day of the week and then by the time for a given datetime.  I did not have a chance to do anything with it, but for some reason it stuck in my head.  So, I came up with the answer, but of course I do not remember where the post was located.  The answer is very simple.

Read the rest of this entry

Using LINQ And Converting DateTime To A String

The problem, I need the DateTime, but I really only need the date and I need to use it for something else.  Something that would like it to be a string.  How can I do this using LINQ?  Well it really isn’t all that hard.  If you try to use any of the .ToString or .To…. DateString you will get an error because it cannot do that in SQL.  Well don’t give up, you just need an extra step.

Basically you are going to get your data out of SQL before you try to convert that DateTime to a string.

First you do your normal LINQ query where you just get that DateTime, here is an example.

var vDates = (from d in oForm.tblSchedule
                      select new { scheduleDate = EntityFunctions.TruncateTime(d.dtSchedule) })

Now here comes the fix.  Use something like the ToList() so that it iterates on it and is no longer in SQL.  Now you can use your .To…String methods.

var vDates = (from d in oForm.tblScheduleIn
                      select new { scheduleDate = EntityFunctions.TruncateTime(d.dtSchedule) })
                      .Select(o => new {scheduleDate = o.scheduleDate.Value.ToShortDateString()});

Now I cannot claim credit for figuring this out on my own. I found an article about it on Stack Overflow.

Viewing Your Proxy Class’ SOAP

Most of us are a bit spoiled with .NET and its lovely ability to take a WSDL (via the WSDL Tool) and create us a proxy class.  We can then use this object to work with the web service.  What if you need to actually see that XML?

Well, Microsoft has a solution.  You can use an extension method to log your SOAP.  Not sure how to do it, don’t worry about that either, Microsoft has already written it for you.

Please go to this link to read the full article.

Custom Validation Controls

Custom validation controls are a nice tool that you can use when the standard validation controls just won’t do the job.  Most examples I found out there only addressed the server side validation aspect.  Don’t get me wrong, you can do that, just use server side, but ideally you want to do both.

Trust me though, if you only want to do one side, do server side.  You will want to always do server side as a minimum just in case the user has javascript disabled or something.  Server side only is kind of old school but it gets the job done very reliably.

Read the rest of this entry

Implementing IDisposable

Here is something I tend to forget from time to time.  How to impliment IDisposable for a class.  While there are many places to find this, I tend to go to my blog first, because usually I will put something in here for what I need.

When declaring you class you need to have it inherit the IDisposable class.

public class MyClass : IDisposable

After that, somewhere in your class you need to implement the methods.

#region IDisposable Methods
        //Implement IDisposable.
        public void Dispose()
        //This is where you will do the cleaning
        protected virtual void Dispose(bool disposing)
            if (disposing)
                // Free other state (managed objects).
            // Free your own state (unmanaged objects).
            // Set large fields to null.

        //MSDN says you can leave the finalizer out if
        //the class does not own unmanaged resources.
            // Simply call Dispose(false).
#endregion// IDisposable Methods

For more information you can see the article on MSDN.

Custom Validation with GridView and EF

This is to document how I do custom validation with a GridView in a website that uses Entity Framework.

Some assumptions:

  • I am using .NET4 with Entity Framework 4
  • I am using an EntityDataSource object
  • My GridView command buttons are templates and have the ID set as a command argument

In this example I will address doing an update from a GridView where we want to make sure a field called someName is unique. The table in question has an identity field that is unique and is called ID. Our model is MyModel and our entity is named MyEntities.

The first thing we need to do is create an OnRowCommand event for our GridView. This event will store the ID of the row we want to update. We will store this in the ViewState. My OnRowCommand event consists of a switch statement which I will put below.

        switch (e.CommandName)
            case "Edit":
                ViewState["editID"] = e.CommandArgument.ToString();
            case "Update":
                ViewState["editID"] = e.CommandArgument.ToString();
            case "Cancel":
                ViewState["editID"] = null;

The next important step is the OnServerValidate event for our custom validation control. This is where the real work happens. My OnServerValidate event puts the value into a string, and the ID into an int. It then calls another private method to set the e.isValid property to the results of the private method. The private method takes the value and ID as parameters. The check is really just counting the number of occurrences of the value in the table that does not equal the ID. Of course in your situation you may not have a string as a value, but you get the idea.

    protected void CV_UpdateUniqueName(object sender, ServerValidateEventArgs e)
        string sName = e.Value;
        int nID = Convert.ToInt32(ViewState["editID"].ToString());
        e.IsValid = IsNameUnique(sName, nID);

    private bool IsNameUnique(string sName, int nID)
        bool isUnique = false;
            using (MyEntities oEntities = new MyEntities())
                int nMatches = (from a in oEntities.tblMyTable where a.someName == sName && != nID select a).Count();
                isUnique = (nMatches <= 0);
        catch (Exception e)
            //Error handling here
        return isUnique;

There you have it, pretty simple.

An Update 6/2/2011
Thinking about it now, perhaps using control state would be better than view state, at least if you tend to turn off view state.