Custom Validation Controls

January 31, 2012 Leave a comment

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.

O.K.  On to my example.  I have a web form and lets say I have a field that I want to make sure is a Float so I can save it into my database.  It is nothing special, just a text box.  Also for this, lets pretend I already have a required field validator in place.  I always use those for fields I require, although you probably could set it to validate empty text, I just always use required field validators for required fields.

<asp:TextBox ID="txtMyFloat" runat="server" Text="" />

Next we need to create the methods to do our validation.  First the easy one, the code behind.  We are going to call this method cv_ValidFloat.

protected void cv_ValidFloat(object sender, ServerValidateEventArgs e)
{
    bool bValid = false;
    try
    {
        float fCheck = float.Parse(e.Value);
        bValid = true;
    }
    catch (Exception ex)
    {
        ex = null;
        bValid = false;
    }
    finally
    {
        e.IsValid = bValid;
    }
}

Now that we have that, lets create our client side function in javascript.

function ValidFloat(sender, args) {
    var vParse = parseFloat(args.Value);
    args.IsValid = !isNaN(vParse);
}

You see we still have our familiar sender and args variables. You can use the args just like you normally do in the code behind, mainly to get the Value and set the IsValid. So lets see what our custom validation control looks like.

<asp:CustomValidator ID="valcMyFloat" runat="server" ControlToValidate="txtMyFloat"
    Text="*" ErrorMessage="Your Float entry does not appear valid." SetFocusOnError="true"
    Display="Dynamic" ClientValidationFunction="ValidFloat" OnServerValidate="cv_ValidFloat"
    ValidateEmptyText="false" EnableClientScript="true">
</asp:CustomValidator>

Categories: .NET, C# Tags: , ,

Encrypt That ViewState!

January 11, 2012 Leave a comment

Something that is probably over looked from time to time unless you are just always that secure is encrypting your ViewState.  While SSL may prevent some things you will may want to make it a bit harder for an end user to see the information stored in ViewState.

Luckily this is very simple.  You can set it in the @Page directive (<%@ Page Language=”C#” ViewStateEncryptionMode=”Always” %>) or in the web.config file (<pages viewStateEncryptionMode=”Always” />).

Of course, like many things .NET there are many ways to do this depending on your specific situation.  For that amount of detail you should read the ViewState Overview.

Categories: .NET

WCF Over SSL

October 25, 2011 Leave a comment

While this seems like it would be a simple task, there are a few minor things you need to do to get things going.  I will not go into all of the various details, there are plenty of walk throughs out there to do that.  I am going to focus specifically on the web.config settings.  For me this is where my trouble lived.

I created a very simple WCF.  It has the interface named IService and the svc named Service.  It consisted of several methods to add, subtract, and divide.  Like I said, it was very simple.  It ran great on non-SSL, but then I went to SSL and the trouble started.

I received this error message:

Service ‘WCFTest.Service’ has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

The fix was to properly setup the binding and behaviors, and most importantly the service name and contract.  In my non-SSL version I named the service MyService and the contract pointed at IService.  In the end for the SSL one of the things I did was use the namespace and the service name for the service and the interface name for the contract.  I will put the web.config file below so you can take a look.  I will also include some links that helped me find my way.

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
      <customErrors mode="Off"></customErrors>
  </system.web>
  <system.serviceModel>
    <services>
        <service name="WCFTest.IService">
            <endpoint address="" binding="wsHttpBinding" bindingConfiguration="sslBinding" contract="WCFTest.IService" />
            <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior>
                <serviceMetadata httpsGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
      <bindings>
          <wsHttpBinding>
              <binding name="sslBinding">
                  <security mode="Transport">
                      <transport clientCredentialType="None" />
                  </security>
              </binding>
          </wsHttpBinding>
      </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

My post to ASP.NET Forums
Beginner’s Guide to WCF
Categories: WCF Tags:

I Have Access – Team Foundation Service Preview

October 19, 2011 Leave a comment

Yesterday I received an email for the Team Foundation Service Preview!  I am so excited to start playing with this product.  I have added a couple of friends as team members and asked coworkers if they would like to help test it.

My thinking is to have us test creating projects that use the Northwind sample database.  At this time I cannot do much.  My personal machine is at home, and to connect you need at least a hotfix as long as you have VS2010 SP1.  I will update more as I do more.

So far…  Not bad.  I would like an easier interface to add new team members, but that could be a lack of familiarity on my part.  I am also using Chrome to access it.

For more information on what I am talking about, go read Learning About the Team Foundation Service Preview.

Implementing IDisposable

October 12, 2011 Leave a comment

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.

Categories: C#

Format A Databound Control In A GridView

September 1, 2011 Leave a comment

This is just a little bit that I keep forgetting for some reason.  Lets say I have a gridview, and in it I want to display the date.  Just the date, but I do not want to use the SQL method to format the date.  You just add the format string to the binding.


Text='<%# Bind("myDate", "{0:MM/dd/yyyy}") %>'

This really would work with any kind of formatting that you needed to do.  I just felt that date would make an easier example.

Categories: Bits

Model-First in the Entity Framework

August 30, 2011 Leave a comment

So I finally had the situation come up to do a model-first approach to Entity Framework (EF).  It was shockingly simple.  Normally I design my databases first and go from there, this time I did my EF model.  Now this was just a simple four entity deal but I thought it would be a great Hello Model-First.

You simply create your entities in the designer, adding properties and adjusting their properties.  You know, like indicating someNum is an int32 instead of the default string, if something can be null, default values and so on.  You also add your associations.  Then you generate database from model.  I did this by right clicking the design surface and clicking on Generate Database from Model…   This will create a SQL script that you can run against your database.  In my case I did create an empty database with a SQL user before hand that I used in my connection information for generating the database.

If you still think it is harder than that, you can read this great article by Microsoft.  I wanted to look it up and make sure I did not leave something out and found that article.  I still suggest you look over the article.  It goes into much more detail than my short text, and they include screen shots.

One thing I did go back and do was change the name of that connection.  Visual Studio named it MyPartModelObjectContainer (or something close to that), where MyPart was basically what I named the Model.  This was simple to do as well.  You rename it int eh connectionString area of your web.config and in the properties of the model.edmx file.  You can see its properties by just clicking on the design surface, not an entity or anything, just on the empty space.

Categories: Entity Framework

Entity Framework 4 Quickstart

August 19, 2011 Leave a comment

Wanting to get started with Entity Framework 4?  Microsoft has a nice simple quickstart for it.  I am thinking of writing my won series of posts for using Entity Framework 4 for the practical developer.

http://msdn.microsoft.com/en-us/library/bb399182.aspx

Categories: Entity Framework, Learning

Odd IIS Error – Entity Too Large

August 4, 2011 Leave a comment

I ran into this error today with users uploading images as part of a webform over https. I did some searching and found a few links that I will list below. Basically all of these suggested increasing the UploadReadAheadSize in ApplicaitonHost.config.

http://forums.iis.net/t/1169257.aspx

http://blogs.msdn.com/b/jiruss/archive/2007/04/13/http-413-request-entity-too-large-can-t-upload-large-files-using-iis6.aspx

http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits

Categories: Bits, IIS Tags:

SQL Server Date Formats

July 7, 2011 Leave a comment

I found this information several years ago and saved it to a wiki at work.  I thought I would put it out here to share with others and for me to access when away from the office.

I must apologize for not remembering where I found this information.

Date Formats
Date Formats

SQL Server Date Formats

One of the most frequently asked questions in SQL Server forums is how to format
a datetime value or column into a specific date format.  Here’s a summary of
the different date formats that come standard in SQL Server as part of the CONVERT
function.  Following the standard date formats are some extended date formats
that are often asked by SQL Server developers.

It is worth to note that the output of these date formats are of VARCHAR data types
already and not of DATETIME data type.  With this in mind, any date
comparisons performed after the datetime value has been formatted are using the
VARCHAR value of the date and time and not its original DATETIME value.

Standard Date Formats
Date Format Standard SQL Statement Sample Output
Mon DD YYYY 1
HH:MIAM (or PM)
Default SELECT CONVERT(VARCHAR(20), GETDATE(), 100) Jan 1 2005 1:29PM 1
MM/DD/YY USA SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY] 11/23/98
MM/DD/YYYY USA SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY] 11/23/1998
YY.MM.DD ANSI SELECT CONVERT(VARCHAR(8), GETDATE(), 2) AS [YY.MM.DD] 72.01.01
YYYY.MM.DD ANSI SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD] 1972.01.01
DD/MM/YY British/French SELECT CONVERT(VARCHAR(8), GETDATE(), 3) AS [DD/MM/YY] 19/02/72
DD/MM/YYYY British/French SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY] 19/02/1972
DD.MM.YY German SELECT CONVERT(VARCHAR(8), GETDATE(), 4) AS [DD.MM.YY] 25.12.05
DD.MM.YYYY German SELECT CONVERT(VARCHAR(10), GETDATE(), 104) AS [DD.MM.YYYY] 25.12.2005
DD-MM-YY Italian SELECT CONVERT(VARCHAR(8), GETDATE(), 5) AS [DD-MM-YY] 24-01-98
DD-MM-YYYY Italian SELECT CONVERT(VARCHAR(10), GETDATE(), 105) AS [DD-MM-YYYY] 24-01-1998
DD Mon YY 1 - SELECT CONVERT(VARCHAR(9), GETDATE(), 6) AS [DD MON YY] 04 Jul 06 1
DD Mon YYYY 1 - SELECT CONVERT(VARCHAR(11), GETDATE(), 106) AS [DD MON YYYY] 04 Jul 2006 1
Mon DD, YY 1 - SELECT CONVERT(VARCHAR(10), GETDATE(), 7) AS [Mon DD, YY] Jan 24, 98 1
Mon DD, YYYY 1 - SELECT CONVERT(VARCHAR(12), GETDATE(), 107) AS [Mon DD, YYYY] Jan 24, 1998 1
HH:MM:SS - SELECT CONVERT(VARCHAR(8), GETDATE(), 108) 03:24:53
Mon DD YYYY HH:MI:SS:MMMAM (or PM) 1 Default +

milliseconds
SELECT CONVERT(VARCHAR(26), GETDATE(), 109) Apr 28 2006 12:32:29:253PM 1
MM-DD-YY USA SELECT CONVERT(VARCHAR(8), GETDATE(), 10) AS [MM-DD-YY] 01-01-06
MM-DD-YYYY USA SELECT CONVERT(VARCHAR(10), GETDATE(), 110) AS [MM-DD-YYYY] 01-01-2006
YY/MM/DD - SELECT CONVERT(VARCHAR(8), GETDATE(), 11) AS [YY/MM/DD] 98/11/23
YYYY/MM/DD - SELECT CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD] 1998/11/23
YYMMDD ISO SELECT CONVERT(VARCHAR(6), GETDATE(), 12) AS [YYMMDD] 980124
YYYYMMDD ISO SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD] 19980124
DD Mon YYYY HH:MM:SS:MMM(24h) 1 Europe default + milliseconds SELECT CONVERT(VARCHAR(24), GETDATE(), 113) 28 Apr 2006 00:34:55:190 1
HH:MI:SS:MMM(24H) - SELECT CONVERT(VARCHAR(12), GETDATE(), 114) AS [HH:MI:SS:MMM(24H)] 11:34:23:013
YYYY-MM-DD HH:MI:SS(24h) ODBC Canonical SELECT CONVERT(VARCHAR(19), GETDATE(), 120) 1972-01-01 13:42:24
YYYY-MM-DD HH:MI:SS.MMM(24h) ODBC Canonical
(with milliseconds)
SELECT CONVERT(VARCHAR(23), GETDATE(), 121) 1972-02-19 06:35:24.489
YYYY-MM-DDTHH:MM:SS:MMM ISO8601 SELECT CONVERT(VARCHAR(23), GETDATE(), 126) 1998-11-23T11:25:43:250
DD Mon YYYY HH:MI:SS:MMMAM 1 Kuwaiti SELECT CONVERT(VARCHAR(26), GETDATE(), 130) 28 Apr 2006 12:39:32:429AM 1
DD/MM/YYYY HH:MI:SS:MMMAM Kuwaiti SELECT CONVERT(VARCHAR(25), GETDATE(), 131) 28/04/2006 12:39:32:429AM

Here are some more date formats that does not come standard in SQL Server as part
of the CONVERT function.

Extended Date Formats
Date Format SQL Statement Sample Output
YY-MM-DD
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), ‘/’, ‘-’) AS [YY-MM-DD]
99-01-24
YYYY-MM-DD
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 111), ‘/’, ‘-’) AS [YYYY-MM-DD]
1999-01-24
MM/YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 3), 5) AS [MM/YY]
SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 3), 4, 5) AS [MM/YY]
08/99
MM/YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 103), 7) AS [MM/YYYY] 12/2005
YY/MM SELECT CONVERT(VARCHAR(5), GETDATE(), 11) AS [YY/MM] 99/08
YYYY/MM SELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM] 2005/12
Month DD, YYYY 1 SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9)
AS [Month DD, YYYY]
July 04, 2006 1
Mon YYYY 1 SELECT SUBSTRING(CONVERT(VARCHAR(11), GETDATE(), 113), 4, 8) AS [Mon YYYY] Apr 2006 1
Month YYYY 1 SELECT DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month
YYYY]
February 2006 1
DD Month 1 SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) AS [DD
Month]
11 September 1
Month DD 1 SELECT DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(DAY(GETDATE()) AS VARCHAR(2)) AS [Month
DD]
September 11 1
DD Month YY 1 SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) + ‘ ‘
+ RIGHT(CAST(YEAR(GETDATE()) AS VARCHAR(4)), 2) AS [DD Month YY]
19 February 72 1
DD Month YYYY 1 SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) + ‘ ‘
+ CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [DD Month YYYY]
11 September 2002 1
MM-YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 5), 5) AS [MM-YY]
SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 5), 4, 5) AS [MM-YY]
12/92
MM-YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 105), 7) AS [MM-YYYY] 05-2006
YY-MM SELECT RIGHT(CONVERT(VARCHAR(7), GETDATE(), 120), 5) AS [YY-MM]
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 5) AS [YY-MM]
92/12
YYYY-MM SELECT CONVERT(VARCHAR(7), GETDATE(), 120) AS [YYYY-MM] 2006-05
MMDDYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 1), ‘/’, ”) AS [MMDDYY] 122506
MMDDYYYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 101), ‘/’, ”) AS [MMDDYYYY] 12252006
DDMMYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 3), ‘/’, ”) AS [DDMMYY] 240702
DDMMYYYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 103), ‘/’, ”) AS [DDMMYYYY] 24072002
Mon-YY 1 SELECT REPLACE(RIGHT(CONVERT(VARCHAR(9), GETDATE(), 6), 6), ‘ ‘, ‘-’) AS [Mon-YY] Sep-02 1
Mon-YYYY 1 SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), GETDATE(), 106), 8), ‘ ‘, ‘-’) AS [Mon-YYYY] Sep-2002 1
DD-Mon-YY 1 SELECT REPLACE(CONVERT(VARCHAR(9), GETDATE(), 6), ‘ ‘, ‘-’) AS [DD-Mon-YY] 25-Dec-05 1
DD-Mon-YYYY 1 SELECT REPLACE(CONVERT(VARCHAR(11), GETDATE(), 106), ‘ ‘, ‘-’) AS [DD-Mon-YYYY] 25-Dec-2005 1

1 To make the month name in upper case, simply use
the UPPER string function.

 

 
Categories: SQL
Follow

Get every new post delivered to your Inbox.

Join 36 other followers