Category Archives: C#

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()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        //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.
        ~MyClass()
        {
            // Simply call Dispose(false).
            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();
                break;
            case "Update":
                ViewState["editID"] = e.CommandArgument.ToString();
                break;
            case "Cancel":
                ViewState["editID"] = null;
                break;
            default:
                break;
        }

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;
        try
        {
            using (MyEntities oEntities = new MyEntities())
            {
                int nMatches = (from a in oEntities.tblMyTable where a.someName == sName && a.id != 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.

The Conditional Operator (?:)

I don’t use this thing too much, so I often forget it when I need it.  In a nut shell it is a nice one line if statement.  You can view the MS page here.

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

condition ? first_expression : second_expression;

Let me provide a realistic example.  Lets say you have a method to generate a random number from 1 – 4, and you want to see if the number is odd or even.


private int RandomNumber(int min, int max)
{
    Random random = new random();
    return random.Next(min, max);
}

private string NumberIs()
{
    string sNumberIs = (RandomNumber(1, 4) % 2 == 0) ? "Even" : "Odd";
    return sNumberIs;
}

Web User Control Events

Ever want to have an event for a Web User Control that the parent page can consume?  Well you can, and it is fairly simple.

I am not an expert since I just figured this out myself so here we go.

There are three basic things you need to do for each event.

  1. Create a public delegate variable in your User Control
  2. Create a public event event for the type of delegate
  3. Create a protected virtual method

So lets see some code.

//Public variables and methods
public delegate void ItemClickEvent(object sender, EventArgs e);
public event ItemClickEvent ItemClick;

//Protected Methods
protected virtual void OnItemClicked(object sender, EventArgs e)
{
    if (ItemClick != null)
    {
        ItemClick(this, e);
    }
}

The property in the page with this user control will be called OnItemClick.  Notice I do not have anything named OnItemClick.  The only public names are ItemClickEvent, which is a delegate and the event itself, ItemClick.  So I assume that .NET adds the On to the front of your event name.

Session Variables As Objects

Or you could think of this as session objects.  Either way the end result is the same.  Everyone uses session variables at some point in their career.  What I am doing is offering what I feel is a better way to deal with session variables.
When I have used session variables in the past I had two main issues; having to remember names and converting them when they were other than string.  Not to mention using Session[“SomeName”] was just too much typing without intellisense.  Some people have wrapped their session variables with getters and setters.  That is a nice idea, but still a bit too much work for what I want to do.  After all I want my code to work for me, not just work.  What if we save a class as a session object, and have the class save itself seamlessly as a session variable.  This works great because you access the class thus giving you intellisense, strongly typed variables and you don’t need to worry about checking the session since it is all in the class.
To demonstrate this lets create a class that we will use for session information.  Our example class will want to store a name, an age, and a birthday.  First, I will write it as a normal every day class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary> /// Simple class to track some /// user information. /// </summary> public class NormalUserInfo {
    #region Variables
    private string myName;
    private int myAge;
    private DateTime myBirthday;
    #endregion #region Constructors
    public NormalUserInfo()
    {
        Name = "";
        Age = 0;
        Birthday = DateTime.Now;
    }
    #endregion//Constructors #region Public Methods
    public string Name
    {
        get { return this.myName; }
        set { this.myName = value; }
    }

    public int Age
    {
        get { return this.myAge; }
        set { this.myAge = value; }
    }

    public DateTime Birthday
    {
        get { return this.myBirthday; }
        set { this.myBirthday = value; }
    }
    #endregion//Public Methods #region Private Methods

    #endregion//Private Methods }
Now we have a normal class that we would use in a normal website.  We have private variables, public getters and setters to access the variables, and a constructor.  Lets turn this class into something we can use as a session object.
First we want to decorate it with the Serializable attribute.  While this does not impact the use of this as a session object it allows us to store this class in other ways in the future if we desire it.
/// <summary> /// Simple class to track some /// user information. /// </summary> [Serializable]
public class NormalUserInfo {
Next we need to add a couple of private methods for maintenance and a string constant.  One is to save our object to the session; we will call this method often.  The other is to check for our object already existing and initialize our object to the existing one.  The string constant will be our session variable name.
Now our variables region should look like this.
#region Variables
    private const string mySessionName = "_MyUserInfo_";    //Our session name private string myName;
    private int myAge;
    private DateTime myBirthday;
#endregion 
Our private methods region should look like this.  Notice how we have moved the initialization of default variable values from the constructor to the area where we create our session if it does not already exist.  Note too that if the session does already exist we set our current values equal to those in the session.
#region Private Methods
    private void CheckExisting()
    {
        if (HttpContext.Current.Session[mySessionName] == null)
        {
            //Save this instance to the session HttpContext.Current.Session[mySessionName] = this;
            Name = "";
            Age = 0;
            Birthday = DateTime.Now;
        }
        else {
            //Initialize our object based on existing session NormalUserInfo oInfo = (NormalUserInfo)HttpContext.Current.Session[mySessionName];
            this.Name = oInfo.Name;
            this.Age = oInfo.Age;
            this.Birthday = oInfo.Birthday;
            oInfo = null;
        }
    }
    private void Save()
    {
        //Save our object to the session HttpContext.Current.Session[mySessionName] = this;
    }
#endregion//Private Methods 
We are almost finished.  The next step is to modify our setters.  After we set the variable to the value, we need to call the Save() method.  Now our public methods should look like this.
#region Public Methods
    public string Name
    {
        get { return this.myName; }
        set { this.myName = value; Save(); }
    }

    public int Age
    {
        get { return this.myAge; }
        set { this.myAge = value; Save(); }
    }

    public DateTime Birthday
    {
        get { return this.myBirthday; }
        set { this.myBirthday = value; Save(); }
    }
#endregion//Public Methods 
The last step is checking for an existing session and initializing to it.  We do this in our constructors, or in our case constructor.  We make a call to the CheckExisting() method as shown below.
#region Constructors
    public NormalUserInfo()
    {
        CheckExisting();
    }
#endregion//Constructors 
The easiest part is using this class.  In your code behind you should declare a global variable of type NormalUserInfo.  In your page load you should instantiate this variable to a new NormalUserInfo object.
public partial class _Default : System.Web.UI.Page {
    NormalUserInfo objInfo;
    protected void Page_Load(object sender, EventArgs e)
    {
        objInfo = new NormalUserInfo();
    }
}
Because we declare our objInfo variable globally, and initialize it on the Page_Load event it will be available to us most anywhere else we plan to use it.  I hope this helps you to make better use of session variables when you need to use them.
I would just like to note that I had originally published this on C-SharpCorner.