Validating an e-mail address the DataAnnotation way

There are many ways to validate if an e-mail address is right, and many wrong ways.  The biggest wrong way is using a Regular expression, why?  They are complex and there is not one that resolves this issue, you will always get an invalid e-mail address that passes through okay.

So what can we do?  Why not use something that already works, something that someone else maintains, something we already have?

Let’s take a look at the System.Net.Mail name space, it has MailAddress, and if you add a string that is an invalid e-mail address it fails eg:

new MailAddress("invalidemailaddress");

This causes an exception to be thrown.

This mean you can use a single line of code to see if an e-mail is valid or not.

Let’s make it more practical and generate a ValidationAttribute that validates an email address for any given field in a model, what we are after doing is something like this:

    public class UserModel
    {
        [Required]
        public string name { get; set; }
        
        [Email]
        public string email { get; set; }
    }

To does this we just need to create an email attribute:

public class EmailAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid
        (object value, ValidationContext validationContext)
        {
            if (string.IsNullOrWhiteSpace(value?.ToString())) return ValidationResult.Success;

            try
            {
                new MailAddress(value.ToString());
            }
            catch (Exception)
            {
                return new ValidationResult("Please provide a valid email address.");
            }
            return ValidationResult.Success; 
         } 
     }

So simple when you know how to do it.

Determine which file type has been uploaded

It is quite an easy process to upload files from a web browser, but how do you know it is the correct type of document you are asking for?

You can check the file extenstion, but a hacker would just change the file type to another extension, so this is not a fail safe way of checking the file type being uploaded.

Another way which can check for the content of the file being uploaded and look for a signature.

First we will need to hold the signature in a file type, so lets create an enum for them

public enum FileType
    {
        Gif = 7173,
        Jpg = 255216,
        Png = 13780,
        Bmp = 6677,
        TxtAspxAspSql = 239187,
        XlsDocPpt = 208207,
        Xml = 6063,
        Html = 6033,
        Js = 4742,
        XlsxZipPptxMmapZip = 8075,
        Rar = 8297,
        AccdbMdb = 01,
        ExeDll = 7790,
        Bat = 64101,
        Unknown
    }

You’ll notice that some file types have the same signature so you need to be a little careful with these files.

Now for the method that will return our file type:

protected FileType IsImageFile(HttpPostedFileBase file)
        {

            var fs = new FileStream(file.FileName, FileMode.Open, System.IO.FileAccess.Read);
            var br = new BinaryReader(fs);
            string fileclass;
            byte buffer;

            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
                return FileType.Unknown;
            }
            finally
            {
                br.Close();
                fs.Close();
            }

            foreach (var type in Enum.GetValues(typeof(FileType)))
            {
                var l = (int)type;
                String[] fileType = {l.ToString()};

                if (fileType.Any(t => fileclass == t))
                {
                    return (FileType)Enum.Parse(typeof(FileType), type.ToString());
                }
            }

            return FileType.Unknown;

        }

That is it, all done

Stay Alive in MVC

Have you ever opened a page for one of your websites and it lags for a while before it finally shows a page but then all of your following requests are quick? If you were to Google the problem you’d find that often it ends up having to do with IIS meeting an idle time limit and shuts down your site.

Keep me Alive

private static void _SetupRefreshJob() {

    //remove a previous job
    Action remove = HttpContext.Current.Cache["Refresh"] as Action;
    if (remove is Action) {
        HttpContext.Current.Cache.Remove("Refresh");
        remove.EndInvoke(null);
    }

    //get the worker
    Action work = () => {
        while (true) {
            Thread.Sleep(60000);
            //TODO: Refresh Code (Explained in a moment)
        }
    };
    work.BeginInvoke(null, null);

    //add this job to the cache
    HttpContext.Current.Cache.Add(
        "Refresh",
        work,
        null,
        Cache.NoAbsoluteExpiration,
        Cache.NoSlidingExpiration,
        CacheItemPriority.Normal,
        (s, o, r) => { _SetupRefreshJob(); }
        );
}

If we place this code in the Global.asax and call it when Application_Start() is raised, we can basically start a job that keeps our website alive. You could just as easily use a Thread to host the refresh method but for this example we simply used an Action delegate.

Once our application starts the refresh job is also started and is saved to the cache. In this example we’re using 60 seconds, but you can change this to be as often as you like.

So How Can We Keep It Fresh?

So how about an example of some code we can use? Here is a simple example that could keep our website alive. Replace the //TODO: in the example above with something like the following.

WebClient refresh = new WebClient();
try {
    refresh.UploadString("http://www.website.com/", string.Empty);
}
catch (Exception ex) {
    //snip...
}
finally {
    refresh.Dispose();
}

This snippet uses a WebClient to actually make an HTTP call to our website, thus keeping the site alive! We could do any number of things from this code like updating local data or get information from external resource. This can be used to keep our site alive and our content refreshed, even if we’re using a Hosted Environment!

It is worth nothing that might not actually need to do an HTTP call back to your website. It is possible that using any method will keep your website from being killed off (but I haven’t tested it yet so let me know what happens if you try it). This example, however, has been tested and works quite well with my provider.

You need to be careful that you don’t call a page with any Analytics attached, otherwise you’ll get false reading in your logs.

Original article

Overloading Methods in WCF

Is this possible?

It is possible to overload a method in WCF.  However, when you want to expose overloaded methods as operations in a WCF contract, there is more to it than simply writing two or more methods with the same name.

Consider the following example:

[ServiceContract]
public interface ICalendarService
{
   [OperationContract]
   ScheduledEvent[] GetScheduledEvents(DateTime date);

   [OperationContract]
   ScheduledEvent[] GetScheduledEvents(DateTime start, DateTime end);
}

Now, try to actually implement this interface and host it as a WCF service.  An InvalidOperationException will be raised when you invoke ServiceHost.Open. 

As far as the C# compiler is concerned, this is a completely legal piece of code.  The interface contains two methods.  The methods have the same name, but their signatures are unique since their parameters differ.  The interface and methods are decorated with attributes.  However, WCF doesn’t have any special hooks into the compiler. Consequently, the compiler doesn’t have any special knowledge about the attributes.  It is simply going to emit their information in the assembly metadata.

When WCF attempts to start the service, it essentially interrogates the metadata to generate a WSDL contract.  WSDL is all about technology neutral, message based communication.  It doesn’t support object-oriented concepts such as inheritance and overloading.  (Actually, I think the earliest versions of WSDL allowed overloading to a certain extent, but it has since been removed in the newer versions.)  So, WCF basically detects there are two methods with the same name and raises an exception to indicate this isn’t allowed even though the code compiled without any errors.

Regardless, WCF still provides the ability to overload methods.  This can be achieved by using the name property of the OperationContract attribute.  By default, the name of the method will be used for the value of the name property.  However, you can explicitly set the value of the name property to provide a unique value.  Under the covers, WCF will use the value you supply as the name of the corresponding operation in the generated WSDL.

Here is our previous example revised to use alias method names:

[ServiceContract]
public interface ICalendarService
{
   [OperationContract(Name = "GetScheduledEventsByDate")]
   ScheduledEvent[] GetScheduledEvents(DateTime date);

   [OperationContract(Name = "GetScheduledEventsByDateRange")]
   ScheduledEvent[] GetScheduledEvents(DateTime start, DateTime end);
}

You may be wondering how the method will appear to the consumer of the service.  Will it appear as two different names (based on the the alias) or as overloaded methods with the same name?  This will depend upon the proxy class used by your client.  If you use the proxy class that is automatically generated by svcutility.exe, the alias method names will be used.  However, you can manually edit the generated proxy class to achieve the appearance of overloaded methods on the client as well.  This can be accomplished by applying the same attributes to the methods defined in the interface that is used by the proxy class.

Original article from Jeff Barnes