Filtered by Tag (tips)
Do you use Visual Studio 11 Developer Preview and miss your extensions? Well, I do! Especially, ADO.NET C# DbContext Generator. We'll see how to make them compatible with Visual Studio 11 Dev. Preview
@ 12-07-2011
by Tugberk Ugurlu


works-on-my-machine-seal-of-approvalDo you use Visual Studio 11 Developer Preview and miss your extensions? Well, I do! Especially, ADO.NET C# DbContext Generator.

As you know, for now Visual Studio extensions are not compatible with Visual Studio 11 Developer Preview.

image

This is normal because it is Developer Preview. Even, I opened up a thread for that on Stackoverflow: Visual Studio Extensions and Visual Studio 11 Dev. Preview and @betty replied to my post after a long time with an amazing answer. I never developed a Visual Studio extension before and I am not familiar with the drill so I thought it is not possible to tweak the extensions so that they can be compatible with Visual Studio 11 Developer Preview but it turns out that it is as easy as pie. How so? Here are the steps:

Oww, by the way, this thing works on my machine and I am not guarantee that it will work on yours as well. Even worse, it can completely screw your machine up. So, take the risk here and don’t swear to me.

I also assume that the ADO.NET C# DbContext Generator does not integrate with Visual Studio that much so there was no big compatibility problems but I won’t try this for the extensions like VSCommands 2010, Web Essentials, etc. If you try, please let me know how it went. Anyway, here is the drill:

First of all, download the extension from Visual Studio Gallery.

image

I am not sure if you are aware of it but vsix files are actually zip files just like NuGet package files (nupkg) and MS Word files (docx). So, change the extension of the file we have downloaded from vsix to zip:

image image

Unzip the zip file and you will see a file called extension.vsixmanifest under root folder. No, it is not a zip file, too Open-mouthed smile It is an xml file though. Open it up with a text editor and find the node called SupportedProducts:

image

Just change the value of version attribute of VisualStudio node to 11.0 and save it.

image

This is actually enough for the extension compatibility standpoint but ADO.NET C# DbContext Generator extension has some dependencies which are specific to Visual Studio 2010 (not sure on that though). So,we have one more step to go as well.

Navigate to /T/code/ folder and you will see a zip file there:

image

Unzip it:

image

Open up the file called ADONETArtifactGenerator_DbContextCSharp.vstemplate with a text editor this time and you will notice a node like below:

  <WizardExtension>
    <Assembly>Microsoft.Data.Entity.Design, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
    <FullClassName>Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.AddArtifactGeneratorWizard</FullClassName>
  </WizardExtension>

Change this one with the below code:

  <WizardExtension>
    <Assembly>Microsoft.Data.Entity.Design, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
    <FullClassName>Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.AddArtifactGeneratorWizard</FullClassName>
  </WizardExtension>

Don’t ask me why because I have no clue. I assumed that it was a versioning issue and it works this way. Remember, this is developer preview. Not even alpha or beta so don’t look for logic that much.

Save the file and zip it up again.

image,

Don’t forget to delete other files. You just need that zip file inside the code folder.

Lastly, go under the root and zip all the files:

image

image

Now we have a zip file again. Change the extension from zip to vsix and double click on that

imageimage

Now we get it working smoothly:

imageimage

Now when you want to continue you way with database first approach, you can follow the steps which are explained here:

http://blogs.msdn.com/b/adonet/archive/2011/11/01/ef-4-2-released.aspx

Here is the quote from that blog post:

Model First & Database First Templates

The templates for using the DbContext API with Model First and Database First are now available under the “Online Templates” tab when “Right-Click –> Add Code Generation Item…” is selected on the EF Designer.

Instead of navigating to "Online Templates" tab, you will find the code gen. file under the "Code" tab:

image

Admit it, we totally nailed that thing Winking smile

We will see How to detect errors of our ASP.NET MVC views on compile time inside Visual Studio.
@ 09-29-2011
by Tugberk Ugurlu


head-in-a-cake

Yesterday, I saw a question on stackoverflow.com asking why Visual Studio doesn’t know that the app is going to fail when there is an error on your code inside your views. This is a good question and it brings up an philosophical question :

Do we trust compile time check?

In my opinion, no. If this was the case, there would be no point for TDD, even Unit Testing.

Compile time check is no more useful than your Microsoft Word’s spell checker. It helps a lot but it is basically a spell checker.

 

In this blog post, I am trying a new way of blogging which I just learnt from Phil Haack Smile Put unrelated photo to your blog post. This approach is among Top 10 Blogging Clichés of 2010. It was a not-to-do but here I am doing it.

The basic problem here is that Visual Studio is not even useful as a spell checker. How so? Let me show you an example.

works-on-my-machine-seal-of-approval

NOTE

Couple of days ago, I saw something cool from one of Scott Hanselman‘s blog posts : The "Works on My Machine" Certification Program. This blog post fits very well in this program so here Works on My Machine Seal of Approval.

Silently Blow up

I have simple ASP.NET MVC 4 internet application which we get out of the box (Things that I will show can be applied with ASP.NET MVC 3 as well). Then I will put a bug inside the index view of my home controller :

@{
    var poo = "bar"
    }

<h3>We suggest the following:</h3>

As you can see it is not a valid code. So it should fail on both compile time and runtime, right? Let’s build the project first :

image

Successful! Let’s run it :

image

Boom! Now you have a new, polished ScottGu’s YSOD (Yellow Screen of Death). So, the question here is why it wasn’t caught by VS.

By default, on ASP.NET MVC projects, your views aren’t compiled on build process of your application. VS treats your views just like it treats CSS files. This doesn’t mean that VS isn’t doing its job, it certainly does. Here is a proof of it :

I went into my index.cshtml file and and press CTRL+W, E to bring up the Error List window. Here is the result :

image

Everything is there. But how many of us really check this window on regular basis unless you work on a team project and your team has a habit of putting #warning blocks inside your C# codes. Probably a few of us.

What we can do here is a fairly simple action to get this blow up on compile time.

Blow Up In My Face so I can See you

Right click on your project inside solution explorer and click Unload Project section as follows :

image

After that your project will be unloaded.

Then, right click it again and it will bring up much shorter. From that list, click on Edit {yourProjectName}.csproj section (If your project is a VB project, then .csproj should be .vbproj) as follows :

image

As you will see, there is so much going on there. We won’t dive into detail there. What we will simply do is to toggle MvcBuildViews node from false to true :

image

Save the file and close it. Then, right click on your project inside solution explorer again. This time click Reload Project section :

image

Finally, press CTRL+W, O to bring up the Output window, build your project and watch it fail :

image

Now, when we correct the bug, we will see that we will have a successful build. Note that this won’t compile your views into a .dll file, this action will only check them for any compile time errors.

Hope that this helps.

One of the aspect of SEO (Search Engine Optimization) is canonicalization. In this blog post, we will see how easy to work with IIS Rewrite Module in order to remove evil trailing slash from our URLs
@ 09-11-2011
by Tugberk Ugurlu


redirect-me-baby

One of the aspect of SEO (Search Engine Optimization) is canonicalization. Canonicalization is the process of picking the best URL when there are several choices according to Matt Cutts, the head of Google’s Webspam team.

Here is how Matt Cutts explains what canonical URL is :

“Sorry that it’s a strange word; that’s what we call it around Google. Canonicalization is the process of picking the best URL when there are several choices, and it usually refers to home pages. For example, most people would consider these the same URLs:

  • www.example.com
  • example.com/
  • www.example.com/index.html
  • example.com/home.asp

But technically all of these URLs are different. A web server could return completely different content for all the URLs above.”

If you have multiple ways of reaching your web page (as above), then you need to sit down because it is time to make some decisions my friends.

Trailing Slash is Evil

Let’s assume that we have created a web application, an ASP.NET MVC app because we are so cool. We have our pretty URLs as well.

Let’s go to a page on our web site :

http://localhost:55050/Home/About

image

And another page :

http://localhost:55050/Home/About/

image

We have got the same page content. As we have mentioned before, these two will be treated as two different web page and it will confuse the search engine a bit (even if they are so smart today).

The solution is pretty simple : when a page is requested with trailing slash, then make a 301 (permanent) redirect to the non-trailing-slash version.

IIS URL Rewrite Module

There are several ways of doing that with ASP.NET architecture :

  • You could write your own HttpModule to handle this.
  • You could do a poor man’s redirection on your controller (on your page load if the application is a web forms application).
  • You could use IIS URL Rewrite Module to easily handle this.
  • And so on…

In this quick blog post, I will show how we can implement this feature for our whole web site with IIS Rewrite Module.

URL Rewrite Module is an awesome extension to IIS. Installing it to your web server is also pretty easy if you haven’t got it yet. Just run the Web Platform Installer on your server, and make a search for “url rewrite”. Then the filtered result will appear and you will see if it is installed or not :

image

After you have it, you will see the management section inside your IIS Manager under IIS section :

image

Cut the crap and show me the code

Now, we are all set up and ready to implement this feature. As it is usual nearly for all Microsoft products, there are thousands (ok, not thousand but still) of way to approach this feature but the easiest way of implementing it is to write the logic inside your web.config file.

As you already know, there is a node called system.webServer under the root configuration node. IIS Rewrite Module reserves a node under system.webServer section and allow us to configure the settings there pretty easily. What we will do is to only write the following code under system.webServer node :

<rewrite>
  <rules>
  
    <!--To always remove trailing slash from the URL-->
    <rule name="Remove trailing slash" stopProcessing="true">
      <match url="(.*)/$" />
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="{R:1}" />
    </rule>
    
  </rules>
</rewrite>

What this code does is to tell the module to remove the trailing slash from the url if there is one and make 301 permanent redirect to the new URL.

Don’t allow the code to freak you out. It might look complicated but there are good recourses out there to make you feel better. Here is one of them :

Using the URL Rewrite Module by Ruslan Yakushev

When you run your site after this implementation and navigate to /Home/About/, watch what is going to happen :

image

image

Isn’t that awesome? A little effort and perfectly clean way of implementing the 1 of a thousand parts of canonicalization.

Some Gotchas

  • In your development environment, if you run your web site under Visual Studio Development Sever, you won’t be able to see this feature working. You need to configure your application to run under at least IIS Express to see this feature working.
  • When you deploy your web site and see this feature not working on your server, it is highly possible that you misconfigured something on your server. One of the misconfiguration you might have done could be setting the overrideModeDefault attribute to Deny for rules under <sectionGroup name="rewrite"> inside your applicationHost.config file.
  • If you are on a shared hosting environment and you see this feature not working, then ask your provider if they have given you the permission of configuring this part.
Couple of days ago I took the Exam 70-515, TS: Web Applications Development with Microsoft .NET Framework 4 and I am gonna walk you through it in this post
@ 05-14-2011
by Tugberk Ugurlu


mcts-logo

Couple of days ago (actually a week ago on the 7th of May), I took the Exam 70-515, TS: Web Applications Development with Microsoft .NET Framework 4 to be qualified as MCTS guy but it didn’t go smoothly as I assumed and I failed Confused smile It was ok though. The experience it has given me was enough to encourage me to go and discover all the other goodness of ASP.NET and it’s children (AJAX and all that stuff). 700 points should be taken to pass the exam but mine was 546.

Actually, my exam number was 72-515. If you have taken the 072 exams before, you’d know that they are Microsoft Academic exams for students and a small discount is applicable with those exams. In terms of questions and qualification which will you get, there is no difference between 070 and 072 exams.

For those who don’t know what MCTS is, here is a quick overview;

MCTS Overview

The Microsoft Certified Technology Specialist (MCTS) certifications provide the foundation for Microsoft Certification. These certifications are designed to validate your skills on the features and functionality of key technologies. You can show your depth of knowledge in one specific technology, earn multiple MCTS certifications to show breadth across different products, or build on the MCTS to earn a Microsoft Certified IT Professional (MCITP) certification.

MCTS candidate profile

MCTS candidates are capable of implementing, building, troubleshooting, and debugging a particular Microsoft technology.

More information about MCTS can be found here : http://www.microsoft.com/learning/en/us/certification/mcts.aspx

When I found about these exams, I haven’t had a single hard time to figure out which direction should I go or what is the best suitable exam for me. Microsoft exams are well documented on their website and also there is a ‘Training and Learning’ section up on social Microsoft.

When you pass an MCTS exam, you will be qualified to get a certificate on the topic that you have taken the exam of. But also, MCTS exams for .Net developers are also the steps which will lead us to MCPD.

Quick Overview of MCPD

The Microsoft Certified Professional Developer (MCPD) certification validates a comprehensive set of skills that are necessary to deploy, build, optimize, and operate applications successfully by using Microsoft Visual Studio and the Microsoft .NET Framework. The MCPD certification is designed to provide hiring managers with a strong indicator of your potential job success. It requires two to three years of relevant experience and a commitment to remaining current in best practices and technologies.

More information can be found on http://www.microsoft.com/learning/en/us/certification/mcpd.aspx

In order to be qualified as an MCPD on Microsoft Visual Studio 2010, three MCTS exams for Windows Developer 4 and Web Developer 4; two MCTS exams for windows azure developer are needed to be passed. In addition to those, there is going to be a MCPD requirement exam in order to complete to road which will lead you to MCPD.

image

Registration for those exams are not made on Microsoft websites, it can be done on Prometric Testing Services.

If you are a student and have an e-mail address through your high school or university, I encourage you to go and take a look at DreamSpark program. There is a campaign running now for Certification Exams which will give you a promotion code for one free exam.

I hope that this blog post helped you to have a better idea on Microsoft exams. Please share your thoughts or experiences by writing a comment to this post so that others can take advantage of them Smile

Useful Links

In this blog post, we will see how ClientIDMode property of Web Controls makes our lives easier. Also, we will demonstrate couple of scenarios on how it works...
@ 03-24-2011
by Tugberk Ugurlu


If you want, you could directly download the source code which is used in this blog post as example and skip the reading Smile. Source code is on ;

http://cid-0ee89cb310fe3603.office.live.com/self.aspx/Programming/WeLoveNet4^_1.rar

One of the things that every JavaScript programmers hate about ASP.NET is Web Control IDs. When we use Master Page or any of Data Controls for displaying data (there are other things which fit in this category but for the sake of less talking, I skipped them), the id of the web controls’ values are generated by concatenating the ID values of each parent naming container with the ID value of the control. This thing screws up the id of the control. As you can see on below source view;

image_thumb[5]

This also makes it hard to write JavaScript (nowadays, JavaScript is also known as JQuery which is kind of bizarre because JQuery is a JavaScript library Smile) codes when we want to bind the code to a control. Of course, it is not impossible to accomplish that on ASP.NET. There are a few ways of doing that on ASP.NET;

  1. One of the ways is to create a JS function and bind the control to that function inside the DOM. For instance, let’s say we have System.Web.UI.Controls.Button control on our web form and we would like to fire a JS function on click of this button. User creates the JS function and bind the control to the function by putting the function name on OnClientClick property of the Button control. I do not recommend this way. Binding the JS code to DOM elements directly is sloppy. 
  2. Other way is to bind the JS code to a Web Control by getting the name of the control with code blocks (often called Code Nuggets by members of the Visual Web Developer team). We’ll get that option on our following example latter.

With .NET Framework v4, we have been introduced with a new property of Web Controls called ClientIDMode. This little thing is now making our lives easier. ClientIDMode gets or sets the algorithm that is used to generate the value of the ClientID property.

ClientIDMode’s value type is enum and it has 4 values. The default value of ClientIDMode for a page is Predictable. The default value of ClientIDMode for a control is Inherit.

You can get more information on Control.ClientIDMode property from offical MSDN document :

http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

I think better way of understanding this is by demonstrating a scenario. On the following example, our goal is to fire a JS function with on click event of a button control. Let’s see how this little feature fits in our lives.

OldFashionWay.aspx

We are assuming that we are working on .NET 3.5 here. So, we do not have the ability to use ClientIDMode feature. What do we do then? Following OldFashionWay.aspx web form code shows us how we can accomplish that;

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

    <title>We Love .NET 4</title>

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {
            $("#<%= button1.ClientID  %>").click(function () {
                alert('textbox1.Text : ' + $("#<%= textbox1.ClientID  %>").val());
            });
        });

    </script>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <div>
        
            <asp:TextBox runat="server" ID="textbox1" />  <asp:Button Text="Submit" ID="button1" runat="server" />

        </div>

</asp:Content>

As you can see inside the script tag, we use Code Nuggets to determine the id of the web controls. Here is the result;

image_thumb[7]

image_thumb[12]image_thumb[10]

This way works just fine but only inside the .aspx files. When we want to get the JavaScript code out of here, put it on a separate .js file and reference it inside the .aspx page, you will certainly fail! This is because of the fact that ASP.NET framework do not apply any special rendering on.js files as it does on .aspx, .ashx or any other ASP.NET specific file types.

ClientIDMode.aspx

As we mentioned earlier, we have been introduced with ClientIDMode property for Web Controls on .NET Framework v4. Let’s see how we accomplish the above scenario on .NET Framework v4. Here is ClientIDMode.aspx file code;

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

    <title>We Love .NET 4</title>

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $("#button1").click(function () {
                alert('textbox1.Text : ' + $("#textbox1").val());
            });

        });

    </script>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <div>
        
        <asp:TextBox runat="server" ID="textbox1" ClientIDMode="Static" />  
        <asp:Button Text="Submit" ID="button1" runat="server" ClientIDMode="Static" />

    </div>

</asp:Content>

As you can notice here, we have set ClientIDMode property of TextBox and Button control to Static. What does that mean? When we set the ClientIDMode to Static, the ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains. Let’s view the rendered html source code;

image_thumb[14]

The id of the controls are the same as we determined. Perfect!

ClientIDMode_SeperateJSFile.aspx

Let’s make our html file unobtrusive. ClientIDMode_SeperateJSFile.aspx file’s source code;

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

    <title>We Love .NET 4</title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/ClientIDMode.js" type="text/javascript"></script>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <div>
        
        <asp:TextBox runat="server" ID="textbox1" ClientIDMode="Static" />  
        <asp:Button Text="Submit" ID="button1" runat="server" ClientIDMode="Static" />

    </div>

</asp:Content>

What we do here is to get the JS code out of the .aspx file and put it inside a separate .js file. This way we could use the same file for other pages and we will accomplish to make ourselves DRY (Don’t Repeat Yourself). We are unable to do that on .NET 3.5 as we mentioned above. ClientIDMode.js is no different than the JS code we used before. Here is the content of ClientIDMode.js;

$(document).ready(function () {

    $("#button1").click(function () {
        alert('textbox1.Text : ' + $("#textbox1").val());
    });

});

Pretty awesome Smile

ClientIDMode_ForEntirePage.aspx

Assuming that we have a large page content and it will make it hard to set ClientIDMode for every Web Control. ASP.NET team also have thought that. We can set the ClientIDMode value for a page in the @ Page directive. Only we need to do is to set ClientIDMode property on <%@ Page … %> section;

<%@ Page 
        Title="" 
        Language="C#" 
        ClientIDMode="Static" 
        MasterPageFile="~/Site1.Master" 
        AutoEventWireup="true" 
        CodeBehind="ClientIDMode_ForEntirePage.aspx.cs" 
        Inherits="WeLoveNet4_1.WebForm22" %>

After this configuration, you do not need to set ClientIDMode value for every control.

Also, we can set the ClientIDMode value for all pages in a Web site by setting the pages element in the site's Web.config file. Example code for Web.config;

<configuration>
  
    <system.web>
        <pages clientIDMode="Static"></pages>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>

</configuration>

ClientIDMode_InsideData-Bound_Controls.aspx

On data-bound scenarios, there is another property that we can make use of for ListView control : ClientIDRowSuffix. ClientIDRowSuffix gets or sets the name of the data field whose value is used to uniquely identify each data row of a ListView control when the ClientIDMode property is set to Predictable.

Let’s see our example. here is the ClientIDMode_InsideData-Bound_Controls.aspx file’s code;

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server"></head>

<body>

    <asp:ListView ID="ListView1" ClientIDMode="Predictable" ClientIDRowSuffix="LanguageID"  runat="server" >

        <ItemTemplate>
            <li>
                <asp:Label Text='<%# Eval("Name") %>' ID="namelabel" runat="server" /> : 
                <asp:Label Text='<%# Eval("Rating") %>' ID="ratinglabel" runat="server" />
            </li>
        </ItemTemplate>

        <LayoutTemplate>
            
            <div ID="itemPlaceholderContainer" runat="server">
                <ul ID="itemPlaceholder" runat="server" />
            </div>
            
        </LayoutTemplate>

    </asp:ListView>

</body></html>

As it is above, we have set ClientIDMode of ListView control to Predictable and ClientIDRowSuffix of ListView control to LanguageID which is the ID field of our datasource. Some of you might wonder where the datasource is. I made a List of ProgrammingLanguages and bound it to ListView1 as you can see on the below code;

    public partial class ClientIDMode_InsideData_Bound_Controls : System.Web.UI.Page {

        public class ProgrammingLanguages {

            public int LanguageID { get; set; }
            public string Name { get; set; }
            public int Rating { get; set; }

        }

        protected void Page_Load(object sender, EventArgs e) {

            List<ProgrammingLanguages> _list = new List<ProgrammingLanguages>();

            _list.Add(new ProgrammingLanguages {LanguageID = 10, Name="C#", Rating=10 });
            _list.Add(new ProgrammingLanguages {LanguageID = 20, Name = "Visual Basic", Rating = 6 });
            _list.Add(new ProgrammingLanguages {LanguageID = 30, Name = "F#", Rating = 7 });
            _list.Add(new ProgrammingLanguages {LanguageID = 45, Name = "Java", Rating = 8 });

            ListView1.DataSource = _list;
            ListView1.DataBind();

        }
    }

When we view the source code of the rendered page, we will see that id of the controls are predictable.

image_thumb[16]

I hope that this article gives you an idea on how you can make your application better with this new feature of ASP.NET.

Happy coding Smile



Hi 🙋🏻‍♂️ I'm Tugberk Ugurlu.
Coder 👨🏻‍💻, Speaker 🗣, Author 📚, Microsoft MVP 🕸, Blogger 💻, Software Engineering at Deliveroo 🍕🍜🌯, F1 fan 🏎🚀, Loves travelling 🛫🛬
Lives in Cambridge, UK 🏡