Emil Stoichev's Blog

Just a few coding tips
Tip: RowFilter with IN operator over a column of type Guid

Case

Apply a RowFilter on a DataView which filters a column of type System.Guid and can contain a variable number of values.

Example:

DataView dv = new DataView();
dv.RowFilter = "TypeId in ('<guid>', '<guid>', ...)";

where TypeId column is of a System.Guid type. As the number of values is variable it makes perfect sense to use the in operator.

The problem

When you are looking at this expression you may think this should be working as expected, i.e. the result should only contain the data where TypeId is in the specified values. In fact, if you run it you will get the following exception:

Cannot perform '=' operation on System.Guid and System.String.

The Solution

To convert the String to Guid you should use the Convert(expression, type) method like this:

dv.RowFilter = "TypeId in (Convert('<guid>', 'System.Guid'), Convert('<guid>', 'System.Guid'), ...)";
Tip: Get application based file path with ASP.NET

Linking to a resource from a reusable control in different levels in your web app folder tree can be a tedious and not so obvious task.

We have a number of tools in our bag that we can use:

  • absolute paths - http://www.yoururl.com/a/b/c/page.ext - not acceptable for reusable components
  • relative paths
    • current level based - a/b/c/page.ext - doesn't work for reusable components
    • root based - /a/b/c/page.ext - that works good in some cases but not in every
    • app based - ~/a/b/c/page.ext - perfect when you can use it

What's wrong with root based paths?

When you work on a project you often use built-in WebServer of the Visual Studio and your app runs on http://localhost:XXXX/. Everything seems to be working fine with the root based paths. Now it's time to deploy your app on a test machine. You deploy it on http://test/myBestApp/. Now all your root based paths are pointing to http://test/Page.ext instead of http://test/myBestApp/Page.ext. That's a good reason not to use root based paths.

~ (tilde)

That's a good solution that comes out of the box and takes care finding the root of your app. Ok, but what if need to build the URL on the fly like in this example:

~/Item.ext?id=<% Request.QueryString[ "id" ] %>

This won't work if you put it in a Hyperlink like this:

<asp:HyperLink ID = "hlnkItemDetails" runat = "server" NavigateUrl = '~/Item.ext?id=<% Request.QueryString[ "id" ] %>' />

Don't think about changing the quotation marks. It won't work however you try.

The universal solution - Page.ResolveUrl

Now that's what can help you in every situation (or at least all cases I can think of). Think about this case: you have a custom control in ~/items/controls/ItemViewControl.ascx. This control is used in ~/Default.aspx and ~/items/Default.aspx. You need to link to ~/items/Item.aspx?id=<query string param> from ItemViewControl.ascx. You can't use ~ (tilde), root based, current folder relative or absolute path for some of the reasons written above. This is where Page.ResoulveUrl comes into help. You can build your link in this way:

<a href='<% String.Format( "{0}?id={1}", Page.ResolveUrl( "~/items/Item.aspx" ), Request.QueryString[ "id" ] ) %>' />

Yes, it is a bit complicated, but at least you won't be worried about broken links and they will work as expected wherever you put them.

2008 Launch

8f04d0a7-f17e-4146-9b93-59e0697c1936 I've just registered for the 2008 Launch in Athens. I guess most of you are exciting about MIX08 now but I won't be able to join this event and I'll have to satisfy myself with the 2008 Launch and I hope with the REMIX. I'm sure it will be fun so if you are somewhere near Athens be sure to attend. The event is free of charge. Check out the sessions here.

Tip: How to get the client culture from an ASP.NET app

I fall in a couple of situations where I needed to get the client’s culture from the server side in an ASP.NET application. I googled this and found only client side solutions, but I knew there was some way to get this information because the ASP.NET framework supports client based culture (through the (UI)Culture = "Auto" in the page attributes and the globalization section in the web.config). The only way I thought of getting the client culture was from the Request object.

After examining the HTTP Headers collection I found the Accept-Language header. It contains information about the user's preferred languages. This is a sample Accept-Language header:

Accept-Language
bg-BG,en-US;q=0.7,ar-BH;q=0.3

The languages are explicitly defined in the browser and their order is determined. You are probably wondering what this q-thing means. According to the RFC 3282 (Content Language Headers) it specifies the language quality or in other words the language priority set in the client's browser. In the example above bg-BG (Bulgarian (Bulgaria) has highest priority then en-US (English (United States)) and the last preferred language is ar-BH (Arabic (Bahrain)).

The Accept-Language header lists all languages set in the browser in a comma separated list which makes it easy to extract each language.

From ASP.NET you can access this header using the Headers collection in the Request object - Request.Headers["Accept-Language"]. Then you can process it the way you like.

UPDATE:
Raj Kaimal gave a useful tip that instead of using Request.Headers["Accept-Language"] you can simply use the HttpRequest.UserLanguages to get a sorted string array of client language preferences. Thanks Raj!

I hope you find this tip useful.

Posted: Jan 21 2008, 03:44 PM by Emil Stoichev | with 4 comment(s)
Filed under:
Have you heard about Microsoft Live Labs Volta?

logo-volta Volta is a toolkit that enables developers to build multi-tier web applications by applying familiar techniques and patterns - namely .NET languages, libraries and development tools. Volta is what many .NET web developers have been waiting so far, especially those who don't like JavaScript.

At first I thought Volta is the Microsoft's answer to Google Web Toolkit (GWT). Yes, on one hand it is, but on the other it provides a way more. Personally I've been wondering when the .NET world will have a similar toolset and now when it is a fact I'm sure a lot of developers will like it.

Volta is not only for web. Volta is to enable multi-tier and asynchronous programming via declarative attribution and MSIL to MSIL rewriting. By Volta you can import JavaScript libraries in .NET and that's one of the things that makes Volta important. There are great JavaScript libraries out there that now can be used in any ordinary .NET application - for example you can use the Virtual Earth or Search libraries in your WinForms applications.

The main goal is to simplify the designing, building, deploying, testing, and debugging of distributed, multi-tier applications, while minimizing the amount of "new stuff" developers must learn. Volta leverages familiar, existing .NET compilers, tools, and libraries and extends them into the distributed realm.

I like that passage. I like the way Microsoft are trying to push the envelope.

If you are interested go and check out the official Volta web site in the Microsoft Live labs. There is an available technical preview that you can download and play with. Also you can find samples included in the package. Remember to visit the Volta Team Blog and to subscribe for their feed to stay up to date with the latest bits.

Technorati Tags: ,,
Consume data from Astoria service using the Astoria Silverlight API

In my previous post I referred you to a tutorial how to make a simple line chart with Silverlight 1.1. With this chart we were able to load data from an exported Excel XML Spreadsheet or from a XML serialized list of Point objects. I thought it would be great if the chart can consume data from a web service and thus stay updated without any user intervention. I decided to use Astoria service - it is new, unexplored, easy to understand and to use, the payload is low, etc. I believe that Astoria will be used by a lot AJAX-enabled and rich internet applications. If you are not familiar with Astoria go to its official labs site and learn! The technology is still in an early development phase and there is yet only a CTP version but you can find enough info to get started. Also there is a couple of useful blogs: Project Astoria Team Blog, Mike Flasko's Blog, Pablo Castro's blog.

Yesterday I continued my series of articles regarding how to build a simple line chart with Silverlight 1.1 (read here). I explained how to make an ADO.NET Entity Model, create Astoria service and then consume it from Silverlight. The sample chart loads data from a Northwind database and then represents it in a line chart. It is a pretty straight-forward way to keep the chart alive. The source code is also included (ASP.NET 3.5 app + silverlight control library + silverlight project) so you can try and use it for your needs. Prerequisites: Visual Studio 2008 Beta2, the Silverlight 1.1 Alpha Tools, the Astoria toolkit (VS2008 Beta2 Refresh) and the ADO.NET Entity Framework Beta 2.

How to build simple line chart with Silverlight 1.1

Today I've published an article on how to build a line chart control with Silverlight 1.1 in SilverlightShow.net. The chart allows you to load data from an exported Excel XML Spreadsheet and a custom XML serialized array of points. The goal of the article is to give a Silverlight solution of how to visualize data in a line chart and let non-technical staff maintain it.

The article shows how to use basic framework elements and transformations, how to load XML in Silverlight, how to create and include in ASP.NET project a Silverlight class library and Silverlight project. 

The full source code is included in the article so you can download and examine it yourself.

Check out the live demo.

Simple Silverlight Line Chart

 

SilverlightShow.net Beta2 Launched!

About 2 months ago I and a few of my colleagues started a Silverlight community site with the hope to be a trustworthy source for Silverlight content and to give our visitors the best we can offer. SilverlightShow has been developed as an internal project, we cannot offer that much functionality in this short time and limited budget. With this release I think we did a good job, though. The thing I'm mostly happy about is the interviews we took from some really cool guys like Chad Hower a.k.a Kudzu (MVP, Regional Director Adviser for Microsoft MEA), Lino Tadros (MVP, CEO Falafel Software), Todd Anglin (MVP, Telerik Technical Evangelist) and Xavier Lemoine ( Netika Technical Evangelist). It is so easy to talk with these guys – they are so experienced and no matter what you ask them, they can talk for hours. I really hope you like the interviews and learn something.

This release also includes Showcase, Get Started and Event sections. With all this content – news, articles, shows (interviews), showcase and events – SilverlightShow.net now offers all you need gathered together in well organized way for you to stay tuned for Silverlight. If you are interested in this technology, I'd highly recommend you to join the community and subscribe for the feeds.

Of course there is still a lot to be done for the community and we will keep contributing and adding new features. It's just a matter of time. So stay in touch and I promise we won't disappoint you ;) We are also looking for a partnership with other communities and users ready to contribute, so send us an email at support [at] silverlightshow [dot] net if you have something on your mind.

I received a couple of emails asking what CMS we use for SilverlightShow.net. We don't use third-party CMS. As this is an ASP.NET blog I'll say a couple of things for the design of SilverlightShow.net and what problems we faced during development.

For an experienced ASP.NET developer this project is not such an interesting thing as it is almost just a CRUD (create, retrieve, update, delete) application without any complex logic. It is entirely based on something we call "a Resource item" which is the object behind news, article, show, etc. The resource item has common fields as Title, Description, Author, etc. Then if a content item has something specific, like a podcast which has a video file, a new business object that inherits ResourceItem is created with its specific properties. The object model completely reflects the database design. That approach makes it super easy to organize the data and display it.

We use a couple of third-party controls and frameworks like ASP.NET Pager – for paging result items, ELMAH for error logging, the ASP.NET AJAX Control Toolkit, ASP.NET Futures (the media control), the Argotic Syndication Framework, Subkismet – the cure for comment spam, URLRewriter.NET, etc. For the time being I'm preparing a blog about the custom controls, frameworks and tools I use in my everyday development and there I'll tell you more about them.

If you want to learn more what is behind SilverlightShow let me know.

Thoughts on the ASP.NET ViewState

Last week I've attended the DevReach conference in Sofia, Bulgaria. It is one of the few international events presented in South Eastern Europe, but a lot of famous international speakers took part in it and I would say it was a good conference. I met a number of well-known faces from the .NET community worldwide and I also had the chance to interview Lino Tadros, Chad Hower a.k.a Kudzu and Todd Anglin (big thanks guys!) for SilverlightShow.net.

One of the sessions I attended was about Tips & Tricks for Managing ViewState (by Todd Anglin). It made me acquire a deeper knowledge on this 'magic' StateBag. A lot of developers, not only junior, are confused about how the ViewState actually works. If you google about ViewState, you will find a couple of articles that explain the 'magic' – some of them good, some of them not so. I strongly recommend reading the blog of Dave Reed (Infinities Loop) TRULY Understanding ViewState if you want to truly understand it ;)

The thing in Todd Anglin's session which provoked me to blog about is the way he programmatically set control properties – in the PreInit stage. Just to give you an overview of the ViewState lifecycle, I'll say that it is loaded in the Init stage and this is exactly where TrackViewState() is called. After that, if a ViewState value is changed, it is considered dirty and StateBag.SaveViewState() will save and return the new value when its state is requested. Having this in mind you can think of changing control properties at the PreInit event. Yes, that is great place. They won't be marked as dirty because TrackViewState() is not still called.

So if you have a code like the following your ViewState won't suffer.

protected override void OnPreInit( EventArgs e )

{

litMessage.Text = "Hey, my ViewState is less than before! Ha!";

base.OnPreInit( e );

}

Just as simple as that. Then, why do we continue to see lot of ASP.NET tutorials, articles, blogs, etc. that initialize control properties at the Load event? Frequently I see code like this:

protected void Page_Load( object sender, EventArgs e )

{

if ( !IsPostBack )

{

gridData.DataSource = myDataCollection;

gridData.DataBind();

}

}

What is the size of myDataCollection? 10kb? 20kb? 120kb? Depends on the data. But why, even if it is 10bytes don't you put it in the PreInit event? Hey, when we are talking about public web applications, that matters! Notice that the next time you set default values, bind data, etc.

In case you use a MasterPage you can't use this tip. MasterPage is treated like a control in the ContentPage and all the controls on the page aren't still initialized at this stage. The simplest thing you can do is to wire up the Init event of the control and there to set the properties you want. Of course, you can use this trick even you have no MasterPage but you don't want to wire up the Init event of all 100 controls you have on the page, do you? ;)

As this is my first contribution to the ASP.NET community, I hope I've helped you guys and I'll be glad to have your feedback.

Introducing Emil Stoichev

Hey it is my pleasure to have the opportunity to blog alongside the asp.net team and to be able to share my knowledge directly from the community blogs (thanks, Joe!).

For the time being I'm a senior web developer at CompletIT. I and my team-mates successfully invented a few private enterprise products in the domain of paramedical software. It is my passion to work on web 2.0 projects and to use cutting edge technologies. Trying to be on the top I spend hours every day reading blogs and contributing to .NET and RIA communities. Besides, I like speaking at seminars and I am looking forward to the next. 

Lately I've been in charge of forming a Silverlight community (of course, my colleagues helped a lot ;). That results in the recent beta launch of SilverlightShow.net - an independent free open community.

This blog will be entirely focused on my day-to-day experience with ASP.NET, AJAX, Silverlight, IIS and .NET in common. Also, I experiment with LINQ, Astoria and Acropolis, so stay tuned and I'll do my best to share my knowledge with you.

More Posts