- Before Checking In or Out:
- Consider getting latest.
- Check if someone else has already checked the file out. If so, inform that person. This to avoid duplicating activities.
- Checking out:
- You can check out a file either explicitly by right clicking and select Check-out or implicitly by typing into the file.
- Before Checking-Out, check that the file is already checked out by another person; if so, inform that user, this to avoid duplicating activities.
- Checking In:
- Before checking in make sure:
- The modified code compiles.
- The entire solution builds successfully.
- StyleCop rules implemented.
- Code reviewer is present.
- Add clear and concise description to what has been changed and why.
- Assign to Work Item(s) ID
- Code reviewer name entered.
- Never Auto-Merge; always merge manually.
- Check that all new files, or relevant assembly in the global Library folder, have been successfully added to TFS. Missing such files might trigger Build Server failure.
- Before checking in make sure:
- After checking in keep an eye on the Build Server notification for successful build.
- At the end of the working day; if the coding is not successfully completed, you must “Shelf” the files within TFS.
- Make sure to regularly update relevant work items with progress and relevant comment.
Singleton Pattern the right way
The singleton pattern is used in almost all modern day programming languages, so why do I keep finding it written incorrectly in so many applications, so lets start with the right way
public sealed class SimpleNoLockLazy
{
static readonly SimpleNoLockLazy instance = new SimpleNoLockLazy();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SimpleNoLockLazy()
{
}
SimpleNoLockLazy()
{
}
public static SimpleNoLockLazy Instance
{
get
{
return instance;
}
}
}
So why this implementation? The reason for using a Singleton is for performance in a multi-threaded environment and this pattern is not only simple, but it is the fastest. I have attached a benchmark application, which is based on Jon Skeet’s benchmark, but testing using a Parallel processes.
I found Jon Skeet’s article very useful
Validation from WCF layer through to MVC
First off, why would you want to perform validation in the WCF layer?
After a vigorous PEN test, it was noted that the validation was mainly happening at the client browser and the application required validation to occur at the business logic layer, in our case the WCF layer.
In general, when working with an MVC/ASP.NET web application, you would typically want to do validation on the client-side as well as on the server side. Whilst the custom validation is simple enough, you’d have to duplicate it on the client and server, which is annoying – now you have two places to maintain a single validation routine.
Lets look at different validation options that will assist us in solving the issues over validation.
There are five validation approaches which you can prefer during validations. Each one has advantages and disadvantages over each other. Also, it is possible to apply multiple approaches at the same time. For example, you can implement self validation and data annotation attributes approaches at the same time, which gives you much flexibility.
- Rule sets in configuration
- Validation block attributes
- Data annotation attributes
- Self-validation
- Validators created programmatically
Rule sets in Configuration
In this approach, we put our validation rules into the configuration file (web.config in ASP.NET and app.config in Windows applications). Here is an example showing how to define validation rules:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="validation" type="Microsoft.Practices.EnterpriseLibrary.
Validation.Configuration.ValidationSettings,
Microsoft.Practices.EnterpriseLibrary.Validation, Version=5.0.414.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<validation>
<type name="ELValidation.Entities.BasicCustomer"
defaultRuleset="BasicCustomerValidationRules"
assemblyName="ELValidation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<ruleset name="BasicCustomerValidationRules">
<properties>
<property name="CustomerNo">
<validator type="Microsoft.Practices.EnterpriseLibrary.
Validation.Validators.NotNullValidator,
Microsoft.Practices.EnterpriseLibrary.Validation"
negated="false" messageTemplate="Customer must have valid no"
tag="CustomerNo" name="Not Null Validator" />
<validator type="Microsoft.Practices.EnterpriseLibrary.
Validation.Validators.StringLengthValidator,
Microsoft.Practices.EnterpriseLibrary.Validation"
upperBound="5" lowerBound="5" lowerBoundType="Inclusive"
upperBoundType="Inclusive"
negated="false" messageTemplate="Customer no must have {3} characters."
tag="CustomerNo" name="String Length Validator" />
<validator type="Microsoft.Practices.EnterpriseLibrary.
Validation.Validators.RegexValidator,
Microsoft.Practices.EnterpriseLibrary.Validation"
pattern="[A-Z]{2}[0-9]{3}" options="None" patternResourceName=""
patternResourceType=""
messageTemplate="Customer no must be 2 capital letters and 3 numbers."
messageTemplateResourceName="" messageTemplateResourceType=""
tag="CustomerNo" name="Regex Validator" />
</property>
</properties>
</ruleset>
</type>
</validation>
</configuration>
Validation Block Attributes
In this approach, we define our validations through the attributes defined in Enterprise Library validation block.
[NotNullValidator(MessageTemplate = "Customer must have valid no")]
[StringLengthValidator(5, RangeBoundaryType.Inclusive,
5, RangeBoundaryType.Inclusive,
MessageTemplate = "Customer no must have {3} characters.")]
[RegexValidator("[A-Z]{2}[0-9]{3}",
MessageTemplate = "Customer no must be 2 capital letters and 3 numbers.")]
public string CustomerNo { get; set; }
Message template is a good way to provide meaningful messages on failure with the flexibility to be replaced by Enterprise Library validation block for brackets.
Data Annotation Attributes
In this approach, we define our validations through the attributes defined within System.ComponentModel.DataAnnotations assembly.
[Required(ErrorMessage = "Customer no can not be empty")]
[StringLength(5, ErrorMessage = "Customer no must be 5 characters.")]
[RegularExpression("[A-Z]{2}[0-9]{3}",
ErrorMessage = "Customer no must be 2 capital letters and 3 numbers.")]
public string CustomerNo { get; set; }
This approach is widely used in conjunction with Entity Framework, MVC and ASP.NET validations.
Self-validation
This approach gives much flexibility to us in order to create and execute complex validation rules.
In order to implement this approach, we first decorate HasSelfValidation attribute with the object type as shown in the following example:
[HasSelfValidation]
public class AttributeCustomer
{
…
}
Then, we write our validation logic by putting SelfValidation attribute on the top of the method which executes the validations.
[SelfValidation]
public void Validate(ValidationResults validationResults)
{
var age = DateTime.Now.Year - DateTime.Parse(BirthDate).Year;
// Due to laws, only customers older than 18 can be registered
// to system and allowed to order products
if (age < 18)
{
validationResults.AddResult(
new ValidationResult("Customer must be older than 18",
this,
"BirthDate",
null,
null));
}
}
Validators Created Programmatically
This approach is different from the others because validation rules are created programmatically and executed independent of the type.
First, we define our validation rules:
Validator[] validators = new Validator[]
{
new NotNullValidator(false, "Value can not be NULL."),
new StringLengthValidator(5, RangeBoundaryType.Inclusive,
5, RangeBoundaryType.Inclusive, "Value must be between {3} and {5} chars.")
};
Then, we add them into one of the composite validators depending on your preference.
var validator = new AndCompositeValidator(validators);
In this example, we check Value to be tested… if it is not null and it has five exact characters.
Finally, I want to mention about the validations against collections. Actually, it is similar to the validations for objects.
// Initialize our object and set the values
var customer = new AttributeCustomer();
FillCustomerInfo(customer);
// Create a list of objects and add the objects to be tested to the list
List<AttributeCustomer> customers = new List<AttributeCustomer>();
customers.Add(customer);
// Initialize our validator by providing the type of objects in the list and validate them
Validator cusValidator = new ObjectCollectionValidator(typeof(AttributeCustomer));
ValidationResults valResults = cusValidator.Validate(customers);
// Show our validation results
ShowResults(valResults);
First thought was to use the MVC answer to validation – DataAnnotations, so why can’t we do this?
WCF is technology for exposing services and it does it in interoperable way. Data contract exposed by the service is just create for data. It doesn’t matter how many fancy attributes you use on the contract or how many custom logic you put inside get and set methods of the property. On the client side you always see just the properties.
The reason for this is that once you expose the service it exposes all its contracts in interoperable way – service and operation contracts are described by WSDL and data contracts are described by XSD. XSD can describe only structure of data but no logic. The validation itself can be in some limited way be described in XSD but .NET XSD generator doesn’t do this. Once you add service reference to your WCF service the proxy generator will take WSDL and XSD as a source and create your classes again without all that attributes.
If you want to have client side validation you should in the first place implement that validation on the client side – it can be done by using buddy classes for partial classes used by WCF proxy. If you want to have a maintenance nightmare and you don’t want to use this way you must share assembly with your entities between your WCF client and WCF service and reuse those types when adding service reference. This will create tight coupling between your service and ASP.NET MVC application.
What about Microsoft.Practices.EnterpriseLibrary.Validation.Validators?
This is a possible solution to the WCF layer, but what this does not provide is a process to pass the validation back to the UI for JavaScript validation, which you get from DataAnnotations.
It may be worth using both the DataAnnotations and the Enterprise Library validation block together.
One question still to remain, is if the validation fails in the Services layer (WCF) how does the validation message get passed to the calling WCF client?
In general, when working with an MVC/ASP.NET web application, you would typically want to do validation on the client-side as well as on the server side. Whilst the custom validation is simple enough, you’d have to duplicate it on the client and server, which is annoying – now you have two places to maintain a single validation routine.
So what else can we use?
First of all, do not throw Exceptions as a way of validating data – that’s a way too expensive operation, instead of graceful handling of invalid data.
If you would like to see some sample code take a look at Microsoft Enterprise Library 5.0 – Introduction to Validation Block by Ercan Anlama
ELValidation_src.zip (772.17 kb)
We’ve looked at all possible validation options, now the searching question is how do pass the validation over WCF to the WCF client for validation? to be continued……
MVC running on IIS8
After a number of 500 errors coming up from IIS8 under Windows Server 2012, I final found the solution.
The solution was to go back to the Microsoft Server 2012 Dashboard and select the “Add Roles” feature. Scroll down to the root “Web Server (IIS)”, expand “Web Server”, expand “Application Development” and select “ASP.NET 3.5” and “ASP.NET 4.5” and “Install”.
What confused me originally was I hadn’t expanded “Application Development”, but selected IIS and continued. On the next step, “Features”, “.NET Framework 4.5 Features” was selected by default so I selected “.NET Framework 3.5 Features” and thought all would be fine.
Use Case templates
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.
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
Internal error messages warning
Write up the following post
http://www.troyhunt.com/2012/01/aspnet-session-hijacking-with-google.html