TypeScript and Building with your Visual Studio Project

TypeScript is great, and it is in Preview from Microsoft.  One of the first issues I had was how to get TypeScript to build your JavaScript files every time you build your Visual Studio project.

Steps to achieve this:

  1. Open your project file using editor (so you can see the xml definition)
  2. Search for import of Microsoft.Common.targets tag
         <Import Project="$(MSBuildBinPath)\Microsoft.Common.targets" />
  3. If you have not found this reference in your project include it, it can be added after <Project *>
    This will enable for you to have BeforeBuild and AfterBuild events.
<Target Name="AfterBuild">
        <Message Text="After Build" Importance="high" />
</Target>
<Target Name="BeforeBuild">  
        <Message Text="Before Build" Importance="high" />  
</Target>
Put following xml under first PropertyGroup. This will introduce variables that we are using later on.Note: make sure you have correct version of typescript installed
<PropertyGroup>  
 <TypeScriptVersion>0.8.1.1</TypeScriptVersion>
 <CompileTypeScript>true</CompileTypeScript>
</PropertyGroup>
Now we are ready to introduce our implementation.The following can be inserted in Project tag, its best to add it in the end of the file.
<Project ToolsVersion="4.0" DefaultTargets="Build"    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- omitted code -->
<!-- Insert your implementation -->
</Project>
Following tag will get all files from project directory that ends with .ts
<ItemGroup> 
 <TypeScriptCompile Include="$(ProjectDir)\**\*.ts" />
</ItemGroup>
Update before build event to call our custom target
<Target Name="BeforeBuild">  
  <Message Text="Before Build" Importance="high" />  
  <CallTarget Targets="TypeScriptBuild"/>
</Target>
And our implementation of build for every TypeScript build for every single file.
<Target Name="TypeScriptBuild"  Inputs="@(TypeScriptCompile)" Outputs="%
    (Identity).Dummy" Condition="'$(CompileTypeScript)'=='true'" >
 <Message Text="Building typescript file - @(TypeScriptCompile)"  Importance="high" />  
<Exec Command=""$(MSBuildProgramFiles32)\Microsoft SDKs\TypeScript\$(TypeScriptVersion)\tsc" -target ES5 "@(TypeScriptCompile)"" />
</Target> 
Thanks for Pavel Svarc for find this out

Missile Launcher

Time to get tough and have a bit of fun.....

This small project came about when team members kept breaking the builds on our build server, and as a result causing compile errors for other developers when they wanted to work on the latest code.

So with a plan in mind I set to task in resolving this issue, first I needed to raise peoples attention that something has gone wrong, so what can I use to do this?

I could use a flashing light, a siren, both would draw attention, but it these would just signal that something has gone wrong.  I need something that will not only signal that something has gone wrong but will also seek out, wait I know the solution a Missile Launcher, both physical and I could get it to fire at the developer who has failed....!  Perfect

I need to find a Missile Launcher that I could programme, and I found one:

Dream Cheeky has the perfect launcher.

So after paying $34.99 and it being shipped from Hong Kong, it arrived about a week later

Next to download the drivers and software from Dream Cheeky, it was not long I had my missiles firing across my room.

Okay now let's get hacking.

I found in the "C:\Program Files (x86)\Dream Cheeky\STORM O.I.C. Missile Launcher" directory a file called USBLib.DLL, so I tried to reference Visual Studio to this file, hay presto it connects, first step completed.

Let try and connect to the DLL from within Visual Studio

So load up the MissileLauncher.cs below and you have an API

Storm_setup.exe (7.18 mb)

MissileLauncher.cs (4.67 kb)

Next step is to interface to Team Foundation Server and detect failed builds, watch this space for the next steps

Encrypting Web.config for the website

Security is always high for installation to customer so is it not about time you encripted the connection string in your web.config file?

This is how it looks like before encrypting:

<connectionStrings>
  <add name="Pubs" connectionString="Server=localhost;Integrated Security=True;Database=Pubs"
    providerName="System.Data.SqlClient" />
  <add name="Northwind" connectionString="Server=localhost;Integrated Security=True;Database=Northwind"
    providerName="System.Data.SqlClient" />
</connectionStrings>

We can encrypt any section of your Web.config file on-the-fly and programatically. If you have full access to your Web server, you can encrypt your connection strings with this single command-line located in the in the %windows%\Microsoft.NET\Framework\versionNumber folder:

aspnet_regiis -pe "connectionStrings" -app "/SampleApplication"

Now, the section in your Web.config file will look like this:

<connectionStrings>
  <EncryptedData>
    <CipherData>
      <CipherValue>AQAAANCMndjHoAw...</CipherValue>
    </CipherData>
  </EncryptedData>
</connectionStrings>

If you can't execute commands in your web server, for example, when using shared hosting, you still can encrypt it programatically:

Configuration config = Configuration.GetWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.Sections["connectionStrings"]; 
section.ProtectSection ("DataProtectionConfigurationProvider"); 
config.Update();

References: Encrypting Web.Config Values in ASP.NET 2.0

Don't and Do's in C#

For a while now I have been reviewing developers code and performing code reviews and I have noticed some common mistakes are being repeated time and time again. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of the developed software. So what are these common mistakes and why are they wrong?

String concatenation instead of StringBuilder

String concatenation works in such a way that every time when you add something to a string, a new address in the memory is being allocated. The previous string is copied to a new location with the newly added part. This is inefficient. On the other hand we have StringBuilder which keeps the same position in the memory without performing the copy operation. Thanks to the strings’ appending by means of StringBuilder the process is much more efficient, especially in case of hundreds of append operations.

//Just wrong
List values = new List(){"This ","is ","Sparta ","!"};
string outputValue = string.Empty;
foreach (var value in values)
{
   outputValue += value;
}
//Correct
StringBuilder outputValueBuilder = new StringBuilder();
foreach (var value in values)
{
   outputValueBuilder.Append(value);
}

LINQ – ‘Where’ with ‘First’ instead of FirstOrDefault

A lot of programmers find a certain set of elements by means of ‘Where’ and then return the first occurrence. This is inappropriate, because the ‘First’ method can be also applied with the ‘Where’ condition. What’s more, it shouldn’t be taken for granted that the value will always be found. If “First” is used when no value is found, an exception will be thrown. Thus, it’s better to use FirstOrDefault instead. When using FirstOrDefault, if no value has been found, the default value for this type will be returned and no exception will be thrown.

//Wrong
List numbers = new List(){1,4,5,9,11,15,20,21,25,34,55};
return numbers.Where(x => Fibonacci.IsInFibonacciSequence(x)).First();
/Almost correct
return numbers.First(x => Fibonacci.IsInFibonacciSequence(x));
//Correct
return numbers.FirstOrDefault(x => Fibonacci.IsInFibonacciSequence(x));

Casting by means of ‘(T)’ instead of ‘as (T)’ when possibly not castable

It’s common that software developers use simple ‘(T)’ casting, instead of ‘as (T)’. And usually it doesn’t have any negative influence because casted objects are always castable. Yet, if there is even a very slight probability that an object can be under some circumstances not castable, „as (T)” casting should be used. See Difference Between C# Cast Syntax and the AS Operators for more details.

//Wrong
var woman = (Woman)person;
//Correct
var woman = person as Woman;

Not using mapping for rewriting properties

There are a lot of ready and very powerful C# mappers (e.g. AutoMapper). If a few lines of code are simply connected with rewriting properties, it’s definitely a place for a mapper. Even if some properties aren’t directly copied but some additional logic is performed, using a mapper is still a good choice (mappers enable defining the rules of rewriting properties to a big extend).

Incorrect exceptions re-throwing

C# programmers usually forget that when they throw an exception using „throw ex” they loose the stack trace, how many times have I seen this? It is then considerably harder to debug an application and to achieve appropriate log messages. When simply using „throw” no data is lost and the whole exception together with the stack trace can be easily retrieved.

//So So wrong
try
{
   //some code that can throw exception [...]
}
catch (Exception ex)
{
   //some exception logic [...]
   throw ex;
}
//Correct
try
{
   //some code that can throw exception [...]
}
catch (Exception ex)
{
   //some exception logic [...]
   throw;
}

Not using ‘using’ for objects disposal

Many C# software developers don’t even know that ‘using’ keyword is not only used as a directive for adding namespaces, but also for disposing objects. If you know that a certain object should be disposed after performing some operations, always use the ‘using’ statement to make sure that the object will actually be disposed.

//the below code:
using(SomeDisposableClass someDisposableObject = new SomeDisposableClass())
{
   someDisposableObject.DoTheJob();
}
//does the same as:
SomeDisposableClass someDisposableObject = new SomeDisposableClass();
try
{
   someDisposableObject.DoTheJob();
}
finally
{
   someDisposableObject.Dispose();
}

Using ‘foreach’ instead of ‘for’ for anything else than collections

Remember that if you want to iterate through anything that is not a collection (so through e.g. an array), using the ‘for’ loop is much more efficient than using the ‘foreach’ loop. See Foreach vs For Performance for more details.

Retrieving or saving data to DB in more than 1 call

This is a very common mistake, especially among junior developers and especially when using ORMs like Entity Framework or NHibernate. Every DB call consumes some amount of time and therefore it’s crucial to decrease the amount of DB calls as much as possible. There are many ways to do so:

  • Using fetching (Eager Loading)
  • Enclosing DB operations in transactions
  • In case of a really complex logic, just moving it to the DB by building a stored procedure
With any SQL connections you can always use the SQL Profiler to see what is happening, and it is quite often easy to spot the excessive use of database connections and more so repeated tries of the same routine.
Just a few I know, but the more common mistakes that developer make when programming day to day.

Code Review Guidelines

What is a code Review?

Code review is systematic examination (often known as peer review) of computer source code. It is intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills. 

Why Reviews are important?

Quoting from Code Complete:

.. software testing alone has limited effectiveness — the average defect detection rate is only 25 percent for unit testing, 35 percent for function testing, and 45 percent for integration testing. In contrast, the average effectiveness of design and code inspections are 55 and 60 percent. Case studies of review results have been impressive:

In a software-maintenance organization, 55 percent of one-line maintenance changes were in error before code reviews were introduced. After reviews were introduced, only 2 percent of the changes were in error. When all changes were considered, 95 percent were correct the first time after reviews were introduced. Before reviews were introduced, under 20 percent were correct the first time.

In a group of 11 programs developed by the same group of people, the first 5 were developed without reviews. The remaining 6 were developed with reviews. After all the programs were released to production, the first 5 had an average of 4.5 errors per 100 lines of code. The 6 that had been inspected had an average of only 0.82 errors per 100. Reviews cut the errors by over 80 percent.

The Aetna Insurance Company found 82 percent of the errors in a program by using inspections and was able to decrease its development resources by 20 percent.

IBM’s 500,000 line Orbit project used 11 levels of inspections. It was delivered early and had only about 1 percent of the errors that would normally be expected.

A study of an organization at AT&T with more than 200 people reported a 14 percent increase in productivity and a 90 percent decrease in defects after the organization introduced reviews.

Jet Propulsion Laboratories estimates that it saves about $25,000 per inspection by finding and fixing defects at an early stage.

The main goals of code review are:

  1. To spot and fix defects early in the process.
  2. Better-shared understanding of the code base as team members learn from each other
  3. Helps to maintain a level of consistency in design and implementation.
  4. Helps to identify common defects across the team thus reducing rework.
  5. Builds confidence of stakeholders about technical quality of the execution.
  6. Uniformity in understanding will help interchangeability of team members in case of non-availability of any one of them.
  7. A different perspective. “Another set of eyes” adds objectivity. Similar to the reason for separating your coding and testing teams, peer reviews provide the distance needed to recognize problems.
  8. Pride/reward. Recognition of coding prowess is a significant reward for many programmers.
  9. Team cohesiveness. Working together helps draw team members closer. It also provides a brief respite from the isolation that coding often brings.

The main areas a reviewer is focusing on are as follows:

  • General Unit Testing
  • Comment and Coding Conventions
  • Error Handling
  • Resource Leaks
  • Thread Safety
  • Control Structures
  • Performance
  • Functionality
  • Security

Roles and Responsibilities

  • The Developer is the person who has written the code to be reviewed and has initiated the review request.
  • The Reviewer/s: are the people who are going to review the code and report the findings to the developer.
Like any skill, good peer reviews come with practice. Some tips that should help you get started on the right track are as follows:
Tips for the Developer:
  1. The primary reviewer is the author i.e. YOU.
  2. Create a checklist for yourself of the things that the code reviews tend to focus on. Some of this checklist should be easy to put together. It should follow the outline of the coding standards document. Because it’s your checklist, you can focus on the thing that you struggle with and skip the things that you rarely, if ever, have a problem with. Run through your code with the checklist and fix whatever you find. Not only will you reduce the number of things that the team finds, you’ll reduce the time to complete the code review meeting—and everyone will be happy to spend less time in the review.
  3. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered.
  4. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry, so we can, and should, learn, laugh, and move on.
  5. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed.
  6. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.
  7. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, not as some serious inconvenience to be fought.
  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you do turn out to be right, don’t take revenge or say, “I told you so” more than a few times at most, and don’t make your dearly departed idea a martyr or rallying cry.
  9. Don’t be “the guy in the room.” Don’t be the guy coding in the dark office emerging only to buy cola. The guy in the room is out of touch, out of sight, and out of control and has no place in an open, collaborative environment.
  10. Please note that Review meetings are NOT problem solving meetings.
  11. Help to maintain the coding standards. Offer to add to the coding standards for things discussed that aren’t in the coding standards. One of the challenges that a developer has in an organization with combative code review practices is that they frequently don’t know where the next problem will come from. If you document each issue into the coding standards, you can check for it with your checklist the next time you come up for code reviews. It also will help cement the concept into your mind so that you’re less likely to miss opportunities to use the feedback.

 Tips for the Reviewer

  1. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.
  2. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.
  3. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.
  4. Please note that Review meetings are NOT problem solving meetings.
  5. Ask questions rather than make statements. A statement is accusatory. “You didn’t follow the standard here” is an attack—whether intentional or not. The question, “What was the reasoning behind the approached you used?” is seeking more information. Obviously, that question can’t be said with a sarcastic or condescending tone; but, done correctly, it can often open the developer up to stating their thinking and then asking if there was a better way.
  6. Avoid the “Why” questions. Although extremely difficult at times, avoiding the”Why” questions can substantially improve the mood. Just as a statement is accusatory—so is a why question. Most “Why” questions can be reworded to a question that doesn’t include the word “Why” and the results can be dramatic. For example, “Why didn’t you follow the standards here…” versus “What was the reasoning behind the deviation from the standards here…”
  7. Remember to praise. The purposes of code reviews are not focused at telling developers how they can improve, and not necessarily that they did a good job. Human nature is such that we want and need to be acknowledged for our successes, not just shown our faults. Because development is necessarily a creative work that developers pour their soul into, it often can be close to their hearts. This makes the need for praise even more critical.
  8. Make sure you have good coding standards to reference. Code reviews find their foundation in the coding standards of the organization. Coding standards are supposed to be the shared agreement that the developers have with one another to produce quality, maintainable code. If you’re discussing an item that isn’t in your coding standards, you have some work to do to get the item in the coding standards. You should regularly ask yourself whether the item being discussed is in your coding standards.
  9. Remember that there is often more than one way to approach a solution. Although the developer might have coded something differently from how you would have, it isn’t necessarily wrong. The goal is quality, maintainable code. If it meets those goals and follows the coding standards, that’s all you can ask for.
  10. You shouldn’t rush through a code review - but also, you need to do it promptly. Your coworkers are waiting for you.
  11. Review fewer than 200-400 lines of code at a time.

Security Code Review

If the applications requires a very close attention to security then www.owasp.org is the right place for resources. This is a very good Security Code Review document to consider: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf

Assign Severity to Review Finding

The severity to find issues with code should go as below. Reviewer must focus on issues with High severity first and then to Medium severity and then Low severity issues.
  1. Naming Conventions and Coding style = Low
  2. Control Structures and Logical issues = Medium or High
  3. Redundant Code = High
  4. Performance Issues =High
  5. Security Issues = High
  6. Scalability Issues= High
  7. Functional Issues =High
  8. Error Handling = High
  9. Reusability = Medium
  10. Checklist for developers and reviewers
Checklists are a highly recommended way to find the things you forget to do, and are useful for both authors and reviewers. Omissions are the hardest defects to find – after all, it’s hard to review something that’s not there. A checklist is the single best way to combat the problem, as it reminds the reviewer or author to take the time to look for something that might be missing. A checklist will remind authors and reviewers to confirm that all errors are handled, that function arguments are tested for invalid values, and that unit tests have been created.
Another useful concept is the personal checklist. Each person typically makes the same 15-20 mistakes. If you notice what your typical errors are, you can develop your own personal checklist. Reviewers will do the work of determining your common mistakes. All you have to do is keep a short checklist of the common flaws in your work, particularly the things you forget to do. As soon as you start recording your defects in a checklist, you will start making fewer of them. The rules will be fresh in your mind and your error rate will drop. We’ve seen this happen over and over.

Checklist for Developers

  • My code compiles
  • My code has been developer-tested and includes unit tests
  • My code is tidy (indentation, line length, no commented-out code, no spelling mistakes, etc)
  • I have considered proper use of exceptions
  • I have made appropriate use of logging
  • I have eliminated unused usings'
  • I have eliminated warnings
  • The code follows the Coding Standards
  • Are there any leftover stubs or test routines in the code?
  • Have I use Separation of Concerns and interface where possible?
  • Are there any hardcoded, development only things still in the code?
  • Was performance considered?
  • Was security considered?
  • Does the code release resources? (HTTP connections, DB connection, files, etc)
  • Corner cases well documented or any workaround for a known limitation of the frameworks
  • Can any code be replaced by calls to external reusable components or library functions?
  • Thread safety and possible deadlocks

Checklist for Reviewers

  • Comments are comprehensible and add something to the maintainability of the code
  • Comments are neither too numerous nor verbose
  • Types have been generalized where possible
  • Parameterized types have been used appropriately
  • Exceptions have been used appropriately
  • Repetitive code has been factored out
  • Frameworks have been used appropriately – methods have all been defined appropriately
  • Command classes have been designed to undertake one task only
  • The presentation layer do not contain business logic
  • Unit tests are present and correct
  • Common errors have been checked for
  • Potential threading issues have been eliminated where possible
  • Any security concerns have been addressed
  • Performance was considered
  • The functionality fits the current design/architecture
  • The code is unit testable
  • The code does not use unjustifiable static methods/blocks
  • The code complies to coding standards
  • Logging used appropriately (proper logging level and details)

Import a Web Deploy Package through IIS Manager

Import a Package

  1. Always make a backup prior to changing your system. Run the following command to backup an IIS 7.0 or above server:
        %windir%\system32\inetsrv\appcmd add backup "PreMsDeploy"
  2. Open the IIS Manager by clicking Start > Run and typing inetmgr.
  3. In IIS Manager, expand the Server node and the Sites node, then select the Default Web Site.
  4. In the right-hand Actions pane, click the Import Application... link to launch the packaging wizard.
  5. Select the package that you created in the previous quick guide, MyApplication.zip, or any other package.
  6. In the Install an Application Package dialog, you will see the application and the database.
  7. On the Parameters page, enter a new application name if desired and enter a SQL connection string.
  8. Click Next to install the package.
  9. The Summary page will provide a high-level overview of some items that were installed from the package. The Details tab will give a lot of detail of exactly what was added.

For more information go to : http://www.iis.net/learn/publish/using-web-deploy/import-a-package-through-iis-manager

 

Publish Database Project causing "the script file could not be found"

If you come across publishing a SQL databse from a Visual Studio Database Project that the "the script file could not be found", after a lot of digging around I found that all you need to do is delete the .dbmdl file, and it will publish again.

SQL71566 when upgrading to VS12

In VS 2012 I receive the following error message (one for each table) when trying to build a database project.

SQL71566: Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlFilegroup cannot not be set on both the Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlTable and the clustered Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlPrimaryKeyConstraint.

For reference here is script associated with this error.

CREATE TABLE [dbo].[OperationsMaster](
[OperationID] [numeric](18, 0) NOT NULL,
[OperationName] [nvarchar](150) NOT NULL,
[OperationTypeID] [numeric](18, 0) NOT NULL,
CONSTRAINT [PK_OperationsMaster] PRIMARY KEY CLUSTERED
(
[OperationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

In above script in last line on word [PRIMARY] red line appears. When I run the same script in SSMS it executed successfully.

You can get your project to build by enabling the project setting "Enable extended Transact-SQL verification for common objects.".

Setting up StyleCop

How to get StyleCop working and running in Visual Studio 2012

First download the latest StyleCop from Codeplex, and install.

If you now load up Visual Studio and create a new project, how you'll find lots of underlined code that need attention

As you can see form above, we now need to start correcting these, most are due to lack of documentation

So once you made the changes things should look better

Now that we have got it running it is time to start to configure StyleCop, if you right click on your project you'll find StyleCop Settings

One rule which I turn off is SA1126: PrefixCallsCorrectly, just find SA1126 on the Rules tab and uncheck the rule, like this:

You'll need to rerun StyleCop again and you'll find that this rule is now ignored.

Setting Up StyleCop MSBuild Integration

Next is to get StyleCop running with all builds for your project, to do this check out Setting Up StyleCop for MSBuild Integration

MSBuild integration will cause the tool to run automatically whenever the code is built, and StyleCop violations will show up alongside compiler errors in the build output.

It is possible to set up the build integration so that StyleCop violations will appear as build warnings, or as build errors if so desired.

Installing MSBuild Files

To enable build integration, first be sure to select the MSBuild option when installing the tool, as shown in the image below:

This will cause the StyleCop binaries and supporting MSBuild targets files to be installed under the {Program Files}\MSBuild\Microsoft\StyleCop folder.

Adding the Import Tag

Once the StyleCop MSBuild files are installed, the next step is to import the StyleCop targets file into your C# projects. This is done by adding an Import tag to each C# project file.

For example, to integrate StyleCop to the project SampleProject, open the project file SampleProject.csproj within your favorite text editor. Scroll down to the bottom of the file and add a new tag to import the Microsoft.StyleCop.targets file. This import tag should be added just below the import of Microsoft.CSharp.targets:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

   ...Contents Removed...

  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

  <Import Project="$(ProgramFiles)\MSBuild\StyleCop\v4.7\StyleCop.targets" /> 

   ...Contents Removed...
 

</Project>

Save the modified .csproj file. The next time you build this project either within Visual Studio or on the command line, StyleCop will run automatically against all of the C# source files within the project.

Build Warnings Vs Errors

By default, StyleCop violations will show up as build warnings. To turn StyleCop violations into build errors, the flag StyleCopTreatErrorsAsWarnings must be set to false. This flag can be set as an environment variable on the machine, or within the build environment command window. Setting the flag this way will cause StyleCop violations to appear as build errors automatically for all projects where StyleCop build integration is enabled.

Alternately, this flag can be set within the project file for a particular project. Open the .csproj file for your project again, and find the first PropertyGroup section within the file. Add a new tag to set the StyleCopTreatErrorsAsWarnings flag to false. For example:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{4B4DB6AA-A021-4F95-92B7-B88B5B360228}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>SampleProject</RootNamespace>
    <AssemblyName>SampleProject</AssemblyName>
    <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
  </PropertyGroup>

Team Development

The configuration described above will suffice to enable StyleCop build integration on an individual development machine. However, development teams working within a well-defined development environment can set up the build integration in a more global way, so that each developer does not have to manually install StyleCop on his machine.

To do this, copy all of the files from {Program Files}\MSBuild\Microsoft\StyleCop into a custom folder within your build environment, and check all of these files into your source control system. Next, define an environment variable within your development environment which points to the location of the StyleCop targets file. For example:

set StyleCopTargets=%enlistmentroot%\ExternalTools\StyleCop\v4.3\Microsoft.StyleCop.targets

With this configuration in place, it is simply a matter of adding the following import tag to each .csproj file within your development environment:

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(StyleCopTargets)" />

StyleCop will automatically run each time this project is built, no matter who is building the project. There is no need for each developer to install StyleCop manually, since the StyleCop binaries are checked directly into your source control system and are centrally integrated into your build environment.

Command Line

If this is not enough for you try it from the command link

msbuild myproj.csproj /p:StyleCopTreatErrorsAsWarnings=false

Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4

 

ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 3 application to ASP.NET MVC 4.

The simplest way to upgrade is to create a new ASP.NET MVC 4 project and copy all the views, controllers, code, and content files from the existing MVC 3 project to the new project and then to update the assembly references in the new project to match any non-MVC template included assembiles you are using. If you have made changes to the Web.config file in the MVC 3 project, you must also merge those changes into the Web.config file in the MVC 4 project.

To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:

In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):

System.Web.Mvc, Version=3.0.0.0
System.Web.WebPages, Version=1.0.0.0
System.Web.Helpers, Version=1.0.0.0
System.Web.WebPages.Razor, Version=1.0.0.0

with the following corresponding text:

System.Web.Mvc, Version=4.0.0.0
System.Web.WebPages, Version=2.0.0.0
System.Web.Helpers, Version=2.0.0.0
System.Web.WebPages.Razor, Version=2.0.0.0

In the root Web.config file, update the webPages:Version element to "2.0.0.0" and add a new PreserveLoginUrl key that has the value "true":

<appSettings>
  <add key="webpages:Version" value="2.0.0.0" />
  <add key="PreserveLoginUrl" value="true" />
</appSettings>

n Solution Explorer, right-click on the References and select Manage NuGet Packages. In the left pane, select Online\NuGet official package source, then update the following:

  • ASP.NET MVC 4
  • (Optional) jQuery, jQuery Validation and jQuery UI
  • (Optional) Entity Framework
  • (Optonal) Modernizr

In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.

Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.

Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.

If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:

<configuration>
  <!--... elements deleted for clarity ...-->
 
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" 
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" 
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" 
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Original article can be found at: MVC 4 release notes

 

About the author

You have probably figured out by now that my name is Bryan Avery (if not, please refer to your browser's address field).  Technology is more than a career to me - it is both a hobby and a passion.  I'm an ASP.NET/C# Developer at heart...

Month List