.NET 4.5 – Visual Studio Web Designer API bug

Recently, we developed one REST service using ASP.NET Web API. We have used a lot of  async/await in that projects. Before we deploy this project on our staging web server that has a few ASP.NET 4.0 websites, we installed .NET 4.5 on one of our local server and requested QA team to test all of our existing ASP.NET 4.0 websites. I know that it’s the extra effort for our QA team but we got no choice since .NET 4.5 can’t be installed side by side with .NET 4.0. Luckily, QA reported only one issue that I am going to share in this post.

The error message that we got is as below.

Error Message: The ‘VirtualItemCount’ property cannot be set declaratively.

.NET 4.5 error

There is a custom control that we are using in our exisitng ASP.NET 4.0 project. There is the code that set VirtualItemCount in aspx but it stopped working after installing .NET 4.5 on the server.

Unfortunately, it turns out that it’s a known issue that has been reported in MS Connect. You can read about this bug report here. Microsoft didn’t mention about fixing this bug so far but there is a workaround that you can use before Microsoft release the fixes.

Workaround

In the meantime, you can apply an easy workaround which is to set the custom control’s property value in code behind and remove the affected property from the mark up.

Anthem.NET and .NET 4.0

Solution for making Anthem.NET works in .NET 4.0 project.

Problem

Anthem.NET Ajax library written by Jason Diamonds supports only ASP.NET 1.1 and ASP.NET 2.0. This library is totally depending on the classic client id generation. When we upgraded our project to .NET 4.0, we found that the pages that use Anthem.NET doesn’t work anymore.

Please refer to the following links below to see ASP.NET 4.0 breaking changes.

ASP.NET 4.0 breaking changes

ClientIDMode.

Solution

The solution for this issue is very simple. You can set the compatibility mode to 3.5 in web.config and then Anthem.NET will work without changing anything.

Here is the code that you copy.


<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">

<controls>

<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</controls>

</pages>

Download

I converted the existing project to .NET 4.0 as well. You can download it from the link below.

Building ASP.NET MVC, Web API, and Web Pages source code

Update #1: Brad Wilson replied me as below ~

Paul Betts has diagnosed this as having some auto-generated files which are currently UTF16, which Git does not support. I’m working to figure out exactly how widespread the problem is.

Seems like codeplex is having the encoding problem with UTF16 file on git repository.

Update #2: Brad Wilson said that he has fixed that file. I re-pulled the repo again and tested it.. It works!

Introduction

Scott Guthrie announced that Microsoft is releasing the source code of ASP.NET Web API and ASP.NET Web Pages (aka Razor) under an open source license (Apache 2.0). They will be accepting the contributions from community as well. What a great news for us! I’m really happy to see more open source projects coming out from Microsoft.

Even though I’m currently occupied with my school, work and etc, I tried downloading the source code from codeplex and building it with a lot and lot of love. (If you don’t know how to install git on your machine, please follow this post “Set Up Git” from github. )

  • Git: git clone https://git01.codeplex.com/aspnetwebstack.git

I got the following folders once I cloned the git repository.

The first thing that I need to do is to restore the nuget packages. Microsoft put the nuget configuration file only instead of  all those third-party assemblies that are required to build the source code. This can be achieved by running “build RestorePackages” from the root of the repository that I just cloned.

You can enable the nuget restore permanently by adding this system variable in your environment.

Otherwise, you will get this error.

Error 1 NuGet package restore is not currently enabled. For more information, please see: http://aspnetwebstack.codeplex.com/wikipage?title=NuGet+Packages System.Web.Razor

According to the official document, we need to download “SkipStorngNames” and run “skipstrongnames -e” with admin right in command prompt but I didn’t do it on one of my machines and I can still build the whole code (including test) from VS10. I’m still pretty new to the code base so I will download and run it when I need.

Errors and Warning

When I tried building the solution, I got this error below.

WebGrid\_WebGridRenderer.generated.cs(1,1): error CS0116: A namespace cannot directly contain members such as fields or methods [C:\aspnetwebstack\src\System.Web.Helpers\System.Web.Helpers.csproj]

I thought that the auto-generated code got screwed up so I deleted everything from that file and tried saving the _WebGridRenderer.cshtml again. Nothing was generated and found two warnings below.

Warning 8 C:\Michael Sync\++ Project\aspnetwebstack\aspnetwebstack\src\System.Web.Helpers\WebGrid\_WebGridRenderer.cshtml: ASP.NET runtime error: There is no build provider registered for the extension ‘.cshtml’. You can register one in the <compilation><buildProviders> section in machine.config or web.config. Make sure is has a BuildProviderAppliesToAttribute attribute which includes the value ‘Web’ or ‘All’. C:\Michael Sync\++ Project\aspnetwebstack\aspnetwebstack\src\System.Web.Helpers\WebGrid\_WebGridRenderer.cshtml 1 1 System.Web.Helpers

Warning 1 Cannot find custom tool ‘RazorHelperGenerator’ on this system. C:\Michael Sync\++ Project\aspnetwebstack\aspnetwebstack\src\System.Web.Helpers\WebGrid\_WebGridRenderer.cshtml System.Web.Helpers

(Temp?) Solution

Ok! There are a lot of doubts and questions but I will share the way that I fixed in order to build the solution without any error.

The main problem that we can’t build is that _WebGridRenderer.generated.cs file has weird non-English characters but when you look at that file in browser, you can see the English version.

The picture below shows the differences between the file that I have and the file on server.

So, I manually copied it from browser (downloading the code as zip file doesn’t work either) and override everything in _WebGridRenderer.generated.cs. After that, it works.

If you are desperately willing to build the code right now, you can follow what I did. I will keep you updated once I found something useful.

Conclusion

You are no longer need to use the temp solution that I mentioned above.. The coordinator from project has fixed the issue and you should be able to re-pull the repository and can build the project already.

Thanks!

Date Issue in Excel Export

This is just a tip on solving date issue in exporting the excel file from ASP.NET.

Introduction

One of my guys was using this following code to export the excel file from ASP.NET application. The code is very simple. He created the datatable with the data that he wants to export from database. He bind that datatable with datagrid, write the HTML code to HtmlTextWriter and write those HTML code to the response with “application/vnd.ms-excel” content type.

Download

protected void Button1_Click(object sender, EventArgs e) {
            var datatable = CreateDataTableWithData();

            System.IO.StringWriter stringWriter = GetHtmlTagsfromDatagrid(datatable);

            WriteResponse(stringWriter);
        }

        private void WriteResponse(System.IO.StringWriter stringWriter) {
            Response.Clear();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = System.Text.Encoding.Unicode;
            Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            Response.AppendHeader("Content-Disposition", "attachment;filename=myexcel.xls");
            Response.Write(stringWriter.ToString());
            Response.End();
        }

        private static System.IO.StringWriter GetHtmlTagsfromDatagrid(DataTable datatable) {
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
            DataGrid dg = new DataGrid();
            dg.DataSource = datatable;
            dg.DataBind();
            dg.RenderControl(htmlWrite);
            return stringWriter;
        }

        private static DataTable CreateDataTableWithData() {
            var datatable = CreateDataTable();

            datatable.Rows.Add(CreateDataRow(datatable, 1, "Michael Sync",
                "8/31/1982 3:19:40 PM"));
            datatable.Rows.Add(CreateDataRow(datatable, 1, "Shwesin Sync",
                "9/29/1982 3:00:32 PM"));
            datatable.Rows.Add(CreateDataRow(datatable, 1, "Elena Sync",
                "1/15/2011 00:00:01 PM"));
            datatable.Rows.Add(CreateDataRow(datatable, 1, "Tiffany Sync",
                "7/6/2012 00:00:01 PM"));

            datatable.AcceptChanges();
            return datatable;
        }

        private static DataTable CreateDataTable() {
            var datatable = new DataTable();
            datatable.Columns.Add("Id");
            datatable.Columns.Add("Name");
            datatable.Columns.Add("Date of Birth");
            return datatable;
        }

        private static DataRow CreateDataRow(DataTable datatable, int id, string name, string dob) {
            DataRow dr = datatable.NewRow();
            dr[0] = id;
            dr[1] = name;
            //dr[2] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", dob); //Right code
            dr[2] = dob; // Wrong code

            return dr;
        }

Problem

We are able to view the exported file in excel but the problem is that the date formats are not consistent for all rows. Take a look at Elena’s b’day and Tifa’s b’day in this screenshot below. The date formats are different, right?

Why?

This problem occurred because Excel is using the formats from regional setting. The format of short date in my system is M/d/yyyy and the long date format is dddd/MMMM dd,yyyy. All data that follows those date format will be treated as a date in excel. Otherwise, it will be treated as a string. If you look at my b’day “8/31/1982 3:19:40 PM”, it doesn’t follow dddd/MMMM dd,yyyy format so excel treat it as a string.

Solution

There are more than one solution for this problem. You can specify “vnd.ms-excel.numberformat:dd/mm/yy” style to that cell. but the easiest fix that we came up is to set the date format as below while populating the data.

dr[2] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", dob); //Right code

Conclusion

It’s just a simple issue and simple solution but we did face this issue so I’m sharing it here. Hopefully, developers who are facing the same problem might find this post useful. :)

Happy Silverlighting! Oh no! Happy sharing!!

Related ~

Codeproject Highlight

Do you want to be informed the best stuffs of Codeproject every months? I have one good news for you. I’m gonna launch one new program called “Codeproject Highlight” started from this month in my blog. In this program, there will be there parts such as news, the best articles and the best posts in CP forum (mostly are from ASP.NET, Web development and C#. ).

The main reason why I start this program is that it saves your time for reading all of latest articles from CP’s feed and tracking all questions and answers from Codeproject forum.

News

Site Upgrading

The whole Codeproject site has been upgraded from Classic ASP to ASP.NET version with a lot of improvements . This is really big changes which is done during 8 years of running. As this site has really huge amount of traffic, it’s very hard for them to upgrade this site with new version. However, the CP development team has done the great job to upgrade the whole site successfully. Congratulation! CP team

Chris shared a few interesting things here ~

For those interested here are some whacky and amusing things we found:

  • SQL Server, IIS and the ASP.NET framework are possessed.
  • Using development settings instead of production settings is a Bad Thing.
  • Storing session state in a SQL database can be a performance killer. Especially when the database is an old P4 test harness machine 40 km away from the webserver. That was an interesting experience in scream therapy.
  • Always check your indexes. Especially the ones that absolutely positively are not and cannot be fragmented. They will be the ones most in need of attention.
  • 20,000 users hitting your application is wonderful load testing. We did load test but our testing machines did not generate the load you guys can generate
  • no matter how many ways you check code there’s always an angle that you haven’t looked at. We’re finding errors in 10 mins of being on that we couldn’t find from 3 months of beta testing. This is just nature.

The Best Articles

  • Silverlight 1.1 Fun and Games by Sacha Barber

    Silverlight Game and Fun

    Sourcecode : Download Source

    Note: This is an award-winning article of Visual Studio 2008 Competition.

  • Silverlight Alien Sokoban by Daniel Vaughan

    A fun Silverlight implementation of the game Sokoban. Contrasting Silverlight 1.1 and WPF, while showcasing some new features of C# 3.0, Expression Design, Expression Blend, and Visual Studio 2008.

    Silverlight Alien Sokoban

    Sourcecode : Download Source

  • Build Google IG-like Ajax Start Page by Omar Al Zabir

    Build a start page similar to Google IG in 7 nights using ASP.Net Ajax, .NET 3.0, Linq, DLinq and XLinq.

    Google IG

    Sourcecode : Download Source

    Demo : Ajax Web Portal

  • WCF / WPF Chat Application by Sacha Barber

    How to create a peer-to-peer chat application using Windows Communication Foundation

    Free Chatting Client in .NET

    Sourcecode : Download Source

  • ASP.NET Popup Control by Tomas Petricek

    Highly customizable JavaScript popup control for web page wrapped in ASP.NET custom control.

    ASP.NET Popup Control

    Sourcecode : Download Source

Links

The best posts in Codeproject forum

  • How to store the password in Database? Encrypting Vs Hashing, Salt

    This is a discussion about storing the password in database. As the user authentication used to be a part of almost every software system, the developers should have good understanding about how to store the password in database. We have discussed about encrypting vs hashing, adding salt or adding the user name after the password and etc.

    Summary

    • Don’t use encryption/decryption for password.
    • Don’t need to append the user name to the password.
    • Hashing the password with random salt (SHA2 might be the best for hashing.)

    You can read about it in the link below.

    Read More ~ guidelines on password encryption

  • Does the System.Deployment namespace cover a great deal of scenarios?

    I have been asked this question regarding ClickOnce deployment in CP forum. As I’m using ClickOnce APIs on SCSF (Smart Client Software Factory) project, I found a few missing things in System.Deployment namespace. The following are the things that ClickOnce can’t handle.

    Summary

    • No way to get the list of latest modules
    • The version of the whole application need to be updated if we wanna update just one module
    • ClickOnce doesn’t care about the version of assemblies.
    • DownloadFileGroup (“”) works only if “optional” is checked. There is no way to download the group of file by force

    Read More ~ An application that will get the updates from server automatically

  • ADODB.DataTypeEnum.adBigInt problem “Bad variable type!” in Windows 2000

    One people who are using ADODB in .NET asked the question below in our CP forum.

    The identity field of one of my SQL DB tables is a bigint, using ADODB to query the DB based on this bigint works fine in my XP machine, but gives me a “Bad variable type” error when I use my app in a W2000 machine.

    The W2000 machine has every service pack issued by MS, what could be the problem?

    Something works fine on XP doesn’t work on Windows 200 is very strange issue. As I never use ADODB (something that we used for VB6 projects in old days ) in .NET, I don’t have that experiences. The possibilities that I think of at that time did solve his problem.

    The trick is that casting the original datatype (long datatype in his case) to double datatype. :) Honestly, I’m not so sure why we need to do this but it did solve the problem.

    Cmd.Parameters.Append(Cmd.CreateParameter("TransId", ADODB.DataTypeEnum.adBigInt, 1, , CType(iTransId, Double)))
    

    Read More ~ In XP works fine, W2000: Bad variable type!

Okay. That’s all for now. This is just a taste of new thing in my blog. What do you think? Is it interesting? As this program is just started, your feedback is highly appreciated. I think that there are a few area that I can’t add in this post. Based on the feedback from all of you, I will make this program better and interesting.. If you like it, don’t forget to subscribe my feed ( http://michaelsync.net/feed ).

Thanks.

Script# – Is Script# right for you?

I was playing a lit bit with Script# and I have some thoughts that I wanna share you. ( If you have no idea about what Script# is then you can read this post “Script#: C# to Javascript converter[^] “. ) I know that Script# is a great framework but it might not be right for all ASP.NET developers. The reason is that there are a few things which are not so convenience for me while I’m using Script#. But I don’t want to say that this framework is not for you. maybe, you might like it. In fact, I will give some facts that I’ve learnt about Script#. You decide whether Script# is right for you or not.

Contents

  1. Script#’s features
  2. Writing the object-oriented code with Script#
  3. Tools for generating the documentation and compressing the sourcecode
  4. What we meant by Script# as a C# to Javascript Converter is ~
  5. Script# as a new language
  6. Debugging problem in Script#
  7. Script# is not from Microsoft
  8. Script# is not Opensource
  9. Using the thirt-party Javascript library in Script#
  10. Script# for ASP.NET Ajax developers and Vista Gadget developers

1. Script#’s features

Script# supports the compile-time checking, intelliSense, class-viewer, reflection and etc. It helps you not to have any typo-errors (e.g. calling foo’() instead of foo(); foo(arg1, arg2) instead of foo(arg1); ) that the most of Javascript developers used to make. So, the benefit of using Script# is that it will improve your productivity.

intellisense.jpg
Fig: intelliSense

tooltip.jpg
Fig: Tooltip

Script# - Compile-time Validation
Fig: Compile-time validation

2. Writing the object-oriented code with Script#

Writing the object-oriented Javascript become so easy with Script#. As you know, writing the object-oriented code in Javascript and C# are quite different. If you are not so familiar with Javascript, you probably need to find the reference when you need to write the code with object-oriented concept. Now, it’s over. You can just write the object-oriented code in C# and Script# will convert this code to the object-oriented Javascript code.

3. Tools for generating the documentation and compressing the sourcecode

If you are using Script#, you won’t need any third-party tool (e.g. JSDoc, Javascript Compressor) for generating the documentation or compressing your javascript library. Script# already has the build-in feature for that purpose.

4. What we meant by Script# as a C# to Javascript Converter is ~

This is very important thing you need to understand before you start learning about Script#. As I said in my previous article, Script# is able to convert the C# code to Javascript. But it doesn’t mean that it can convert all C# code that you wrote in winform or webform. In order to convert the C# to Javascript via Script#, you have to write the Script#-specific code in C# then those codes will be converted to Javascript…

5. Script# as a new language

The syntax of Script# is not so similiar to the Javascript’s syntax. So, I feel like learning a new language to write the Javascript. Another problem is that it is so hard to find the equivalent syntax in Script#.

For example: How to access ‘document’ of created DOMElement??[^]

In Javascript,

var iframe = document.createElement("iframe");
var doc = iframe.contentWindow.document;

In Script#,

using System;
using System.DHTML;
using ScriptFX;
using ScriptFX.UI;

public class MyScriptlet {

public static void Main(ScriptletArguments arguments) {
DOMElement _iframe = Document.CreateElement("iframe");
DOMElementExt contentWindowElement = (DOMElementExt)_iframe.GetAttribute("contentWindow");
DOMElement doc = contentWindowElement.document;

}
}

[IgnoreNamespace]
[Imported]
public class DOMElementExt : DOMElement {

[IntrinsicProperty]
public DOMElement document {
get { return null; }
}

[IntrinsicProperty]
public DOMElement body {
get { return null; }
}

[IntrinsicProperty]
public DOMElement src {
get { return null; }
}

[IntrinsicProperty]
public DOMElement firstChild {
get { return null; }
}
}

If you look at both examples, you will understand how hard to find the equivalent syntax in Script#. It’s okay if we can find the equivalent one. But what if Script# doesn’t support something that can be done with Javascript?

6. Debugging problem in Script#

Script# does support the compile-time validation but the problem is that you won’t be able to debug the C# code that you wrote. Instead, you will have to debug the Javascript code that generate by Script#. I think that it is the big issue for web developer. I don’t feel comfortable to debug those generated code.

7. Script# is not from Microsoft

Script# is not developed by Microsoft while the GWT is developed by Google. It has too much differences. Even thought Nikhil is an architect from Microsoft, Script# is just one of his pet projects.. So, I don’t think that he is gonna support his pet project all the time.. And I’m not so sure that Nikhil will add more features to this project or not..

8. Script# is not Opensource

Script# is not an opensource project. Actually, it’s absolutely okay for me to use the non-opensource projects (I’ve been using the Visual Studio since long long ago.) but there should be a group of people who are supporting this project, right? What if we need the bug-fixed?

9. Using the thirt-party Javascript library in Script#

The most of Javascript libraries /framework (e.g. prototype, script.aculo.us, Yahoo.UI, ExtJS) are not written in Script#. So, you can’t use those libraries right away from your Script# code. I think you will have to create a wrapper class for those libraries in order to use them in your Script#-enabled projects.

10. Script# for ASP.NET Ajax developers and Vista Gadget developers

I think that Script# might be good for ASP.NET Ajax developers and Vista Gadget developers. As I’m not very familiar with those things, I’m not able to cover about this. I need your contributes for this fact.

Okay That’s all from my side. Feel free to let me know if you have any thought or comment. Thanks.