Category: ASP.NET

Error: The reference assembly could not be resolved because it has a dependency on System.Web

I was working on a sample project today when I encountered this error after adding a new Console Application project to my Visual Studio solution that references other Class Library projects contained in the solution:

.NET 4.0 Client Profile Assembly Error

The referenced assembly “C:devcenterdotnetpersonalKeithRull.BibliaKeithRull.Biblia.Service.RepositorybinDebugKeithRull.Biblia.Service.Repository.dll” could not be resolved because it has a dependency on “System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” which is not in the currently targeted framework “.NETFramework,Version=v4.0,Profile=Client”. Please remove references to assemblies not in the targeted framework or consider retargeting your project. KeithRull.Biblia.ConsoleApp.

There are two possible cause of this error. The first possible reason is when you have an assembly that is referencing System.Web and you try to add that assembly to project that does not have any reference to System.Web (if necessary which most of the time is not). The second possible reason is that your project is using the .NET 4.0 Client Profile which is just a subset of the .NET Framework. Below are the steps that illustrate how to fix this issue.

1. Select your project, right-click and then select “Properties”.

Visual Studio Properties Menu

 

2. The properties tab, change the value for “Target Framework” and then set it’s value to “.NET Framework 4″

Visual Studio Change Target Framework

Compile your application and that should fix the problem.

Interested in learning more? Below are some useful links if you want to read more about this issue and the .NET 4 Client Profile.

How To: Encrypt the ViewState in ASP.NET

Sometimes its the basic things that we tend to forget. It’s true. One example is encrypting the ViewState. Someone asked me this question today and I had to admit that I wasn’t able to answer on top of my head. Whats funny is that I’ve been doing it all along but never told myself to remember how.

Anyhow, lets go back to the topic on how to encrypt the ViewState in ASP.NET.

Prior to .NET 2.0 the way you would do this is via the machineKey element validation attribute. In .NET 2.0 onwards Microsoft provided us with an option to specify ViewState encryption in the page level or web.config level via the ViewStateEncryptionMode attribute.

ViewStateEncryptionMode has three enumeration values that you could use defending on what you need. They are Auto, Never and Always. ViewStateEncryptionMode.Auto means that the page will be encrypted if a control request for encryption. By default the value for ViewStateEncryptionMode is set to Auto. ViewStateEncryptionMode.Never means that ASP.NET will not encrypt the ViewState on your page even if a control request for it. This is a good bypassing mechanism if and only if you know that the page does not need to have ViewState encryption on it. ViewStateEncryptionMode.Always on the otherhand will encrypt your page all the time. A good practice for pages with sensitive information is to always set this ViewStateEncryptionMode to Always as you don’t want anybody compromising your ViewState.

To enable ViewState encryption in the page all you need to do is specify the value for ViewStateEncryptionMode at the Page directive

<%@Page ViewStateEncryptionMode=”Always” %>

To enable ViewState encryption via web.config to apply to the whole application

<configuration>
   <system.web>
      <pages ViewStateEncryptionMode=”Always” />
   </system.web>
</configuration>

One thing to remember though is that you can’t set ViewStateEncryptionMode via code

To request for ViewState encryption inside a control all you need to do is call RegisterViewStateEcryption() method from the Page class

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if(Page != null)
    {
        Page.RegisterRequiresViewStateEncryption();
    }
}

Ahhh, such reverie. Now I need to remember this for future use (or questions). Cheers!

ASP.NET MVC 1.0 RTMed

I saw this on the ASP.NET MVC download page and it seems like it was released yesterday.



I haven’t seen any official announcement anywhere yet but I expect to hear something coming out of the MIX09 event regarding ASP.NET MVC 1.0 RTM. I was able to confirm with Ben Scheirman via twitter that it’s RTMed. I don’t know where he got the news but judging by the screenshot above it looks like its true.


In case you are interested in learning about ASP.NET MVC, Microsoft has released an application called NerdDinner.com which is a event management website that enables users to register for “geek dinners”. I believe that application was built using ASP.NET MVC 1.0 RC2 but it should be compatible with the RTM version (I haven’t compiled it with the latest version yet). It’s a really nice sample application that shows you how to build an application using ASP.NET MVC. Whats neat about NerdDinner.com is that it part of the book that Scott, Scott, Phil  & Rob are writing and they have been kind enough to let as peek at their upcoming book by giving a free chapter that details how they built the NerdDinner.com website step-by-step using ASP.NET MVC.


Wow, I’m really stoked! This is going to be a fun day! Thanks MS!

ASP.NET MVC RC 2 Source code and Futures are now available on CodePlex


I just saw this twitter…



Sweeeeet!


Time to start polishing my ASP.NET MVC skills. I’ve played with ASP.NET MVC before but never had the chance to use it other than building small samples. I might be rusty but I know I’ll have a great companion book in learning ASP.NET MVC 1.0 once Rob, Scott, Scott and Phil‘s upcoming book comes out.

How To: Make A Master-Detail View In ASP.NET

In part 3 of this 5 part series I am going to show you how to make a Master-Detail View in ASP.NET. I you weren’t able to see the two previous post you can check them out here:



This post is a continuation of what we started in the two previous post wherein i show you how to consume a webservice ins ASP.NET and present the values returned by the service to the user in a much more meaninful way.


To start off with this post lets look at how the application from our last article look-liked:



As you can see, we have a textbox that accepts a user-input asking for the symbol to lookup in our webservice, a button that triggers that query event and a DetailsView that displays the returned resultset. This works great.


But what if I have a list of symbols that I want the user to see information regarding them? The answer is to show them in a master-detail view so that the user can get a clearer view of the information on each symbol.


To start with this demo lets begin by deleting everything that we have on the page. Yup! we are starting from scratch so that we can get a clearer picture on how we can build a master-detail view screen. Once everything is cleared on the page let’s begin by adding a DataList control on our page with a Label control inside its ItemTemplate:


The first thing that you would notice on the code above is that we have assigned a value to the Text property of our Label control. This value signifies that we are binding the Container.DataItem value to the Text property. This DataItem will come from the value that we are going to set in the codebehind file for this page which in this case is just going to be a List<string>.


Next, lets go the codebehind file and create the Page_Load event for our page:


All i did in the code above is create a list of strings, add some values to it and assign and bind that colletion of strings to our DataList. Running the application now would give us this result:



Nothing really impressive yet. Now let’s add the cool part wherein we call a web service and show the information for each stock symbol.


To do that we need to add another DataList inside the ItemTemplate of our first DataList. The second DataList will serve as the list that shows the imformation about the specified execution symbol. We also need to add an event that is triggered each time a ListItem is binded to a data. Below is our modified HTML page:


I modified the ItemTemplate of our second DataList () and added an html table to hold the values that the web service returns. This way the view that we are presenting is much more readable.


Next stop is looking at the code behind where all these magic is going to be wired. All the work for the detail view will happen on the stockDataList_ItemDataBound event and no further modification to our Page_Load event is needed. Let me show you the code for that event before I start explaining every bits and pieces of that code:


What we are doing on this blog of code is we are checking if the ItemType of the current item being binded-to is either a ListItemType.Item or ListItemType.AlternatingItem. If it passes this criteria we then read the DataItem that was binded to this ListItem which in this case is our executionSymbol. The next step is to find our stockInformationDataList control and assign the stockInformationDataSet to it. The stockInformationDataSet contains the values that is retrieved from our stock web service by passing the exection symbol to our StockQuoteHelper.GetStockQuoteDataSet method.


Running our completed application will result to this screen:



And that’s it! We’ve accomplished a master-detail view in ASP.NET. Pretty easy right? I hope you learned something from this tutorial. Next up we’ll update this project and implement some Asynchronous Web Service calls via ASP.NET AJAX and show you some fun ways to present a master-detail view in a much more interesting way.


As always, source code is available for download here: KeithRull.ConsumingWebServices.Part3.zip (6.9 KB)


As a side note, many thanks to John A. Miller from Trofholz Technologies, Inc. for reminding me about this series. I totally forgot about it already after being assigned to a large project the past few months. Thanks John!

Keith’s Free eBook Recommendations Of The Month

Speaking of free books… Below are the list of free ebooks that I recommend reading/downloading for this month. I personally love Karl Seguin’s book and giving it 5 out 5 stars is actually an understatement if you ask me. :)


Karl Seguin‘s Foundation Of Programming: Building Better Software rocks so much I recommended it to everyone I know. This 79 page book is pack with a hearty bowl of software development knowledge that would teach you about the principles of development that you should have known way before you started coding that nightmarish system.


Red Gate’s Dissecting SQL Server Execution Plan is a must read for anyone who deals with data on a daily basis. It talks about how to optimize your querries and understand whats causing your querries to sleep on you while being executed.


InfoQ’s Domain Driven Design Quickly is a quickly-readable summary and introduction to the fundamentals of DDD that tries to summarizes Eric Evans’ book as well as Jimmy Nilsson’s Applying Domain Driven Design and various other sources. The book gives you hints and tips about DDD as well as ideas on how to start DDD in your own projects.


Minh T. Nguyen‘s Visual Studio.NET Tips & Tricks is a must read for all developers who use Visual Studio. Enuff said!


So what are you waiting for? Download and read ‘em now!

How To: Create dynamic input rows in a GridView with ASP.NET

Sorry for not being able to post anything interesting the past few months. Anyway, I saw this old thread at DevPinoy.org the other day and I realized that nobody has posted a complete sample solution that would solve and show how to accomplish dynamic input rows in a GridView. I was thinking of replying to it a few months back but i guess work caught up at me and I wasn’t able to do so. I found some free time last week and decided to build an app to demonstrate how to solve this question.


Ok, lets start by analyzing the question:



Hi guys,


I have a problem here. How can i create a dynamic row in gridview the row will defend from the user input. For example the user enter a 4 then the gridview will generate 4 rows. Please site me an example.


Thanks,
D_Conqueror


From what I understood the user wants to be able to create dynamically rows of data in the GridView depending on the number he enters on a Textbox. We can accomplish this by creating a datasource with the same number of rows as the user specified and binding it to our GridView.


To demonstrate how to solve this problem i decided to create this sample.


To start off with our tiny project we need to create a page that would ask the user for the number of rows he wan’ts to display on the GridView. The page will contain a TextBox for input and a LinkButton that we will use for submitting the value to a seperate page. Below is the HTML code for our first page (Default.aspx):


dynamiggridview01.jpg


and below is the code listing for Default.aspx


As you can see, all we are doing is passing the value of our TextBox as a query string parameter to our second page. The true juice of our solution is on the next page. But before we go into detail to that we need to setup first what type of values needs to be shown on the page. For this example i’ve decided to display a simple Person class that has for fields. An ID, a Firstname, a Lastname, and a boolean field called IsChristian. Below is the code for our Person class:


I also created a class Persons that is a generic list of type Person. In that class I created a contructor that accepts a integer value that we will use to create the dummy list of person. The code for our Persons class is listed below:


Now on our second page, DynamicGridViewPage.aspx, I decided to place 4 controls. A GridView that would contain our input boxes, a label to display messages, a button to submit the fields and another GridView to show the submit values. I’ve added these few quirks on the page to demonstrate how you can retrieve entered values in a GridView. Below is the HTML listing for the DynamicGridViewPage.aspx.


One of the things that you would quickly realize on our page is that the only thing I’m binding to our GridView is the ID property. The reason is because we don’t really need to bind all the fields to our GridView because we are just creating rows. Next, lets look at the code behind for our page.


What happens on the code-behind is pretty simple. When the page loads it checks to see if it is not a PostBack, if it’s not then it tries to retrieve the rows to create using the RowCount property. Once retrieved, that value is then passed to the contructor of the Persons class to create a dummy list of items that would then be assigned to the DataSource property of our GridView.


dynamiggridview02.jpg


dynamiggridview03.jpg


I’ve added code to the submit button to simulate submissions to show how you can retrieve the values entered on our GridView.


dynamiggridview04.jpg


And that’s it. Thats how you create a dynamic rows in a GridView and access the values. I hope i was to shed light on this issue. Thanks!


Want the source code? Download it here: KeithRull.DynamicGridViewRows.v2.zip (6.37 KB)

Just Released: .NET StockTrader Sample Application

Just in case you are studying WCF.. You might want to check out the .NET StockTrader Sample Application.



The .NET StockTrader Sample Application is an end-to-end sample application illustrating Windows Communication Foundation and .NET Enterprise Technologies. It is a service-oriented application based on Windows Communication Foundation (.NET 3.0) and ASP.NET, and illustrates many of the .NET enterprise development technologies for building highly scalable, rich “enterprise-connected” applications. It is designed as a benchmark kit to illustrate alternative technologies within .NET and their relative performance.


The application offers full interoperability with J2EE and IBM WebSphere’s Trade 6.1 sample application. As such, the application offers an excellent opportunity for developers to learn about .NET and building interoperable, service-oriented applications.


Read more here: http://msdn.microsoft.com/en-us/netframework/bb499684.aspx


I’ve been diving into WCF lately and I have found this sample application as a great blueprint on how to develop applications using WCF & ASP.NET. The sample includes a smart client and an ASP.NET application that you can jump on and play that showcases as huge list of technologies and approaches when developing an SOA app via WCF and .NET


Below is a list of technologies that’s demonstrated in this sample application:



  • Service-oriented, n-tier design with ASP.NET and WCF

    • Clean separation of UI, business services and DB access
    • Design and tuning for performance
    • Horizontally scalable via dynamic clustering
    • Centralized configuration management of clustered service nodes

  • .NET 3.5 with Windows Communication Foundation

    • Interoperability with J2EE/WebSphere Trade 6.1
    • Incorporates alternative designs for performance comparisons
    • Loosely-coupled, message-oriented design with WCF and MSMQ
    • Achieving assured message delivery with transactions
    • Self-hosting WCF Services
    • Custom WCF Behaviors
    • Service host failure detection and automatic restarts

  • .NET Enterprise Application Server Technologies

    • ASP.NET 2.0
    • ADO.NET 2.0
    • .NET Transactions
    • MSMQ 3.5 (Windows XP/Windows Server 2003)
    • MSMQ 4.0 (Windows Vista/”Longhorn Server CTP”)
    • Transaction batching with WCF and MSMQ

Try and see for yourself ;) I bet you will enjoy it too!


 

HowTo: Convert an Xml string to DataSet

In my previous article I showed you how to add a web service reference in your ASP.NET application, call a webmethod and the display the values returned byt the web service to a Label. This time I’m going to show you how to transform that Xml string into a DataSet.


I suggest that you read the previous article before continuing in reading this post so you’ll have a better insight on what we are trying to accomplish on this article.


Let’s begin!


To start off this article let’s look at how the application that we built for the previous article.



and the HTML code for the UI


and the underlying code for the click event of the “Execute” button


    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //HtmlEncode the string to properly render it on the page
        string htmlEncodedResult = System.Web.HttpUtility.HtmlEncode(quoteInfo);
       
        //assign the HtmlEncoded string to our Label control
        xmlResultLabel.Text = htmlEncodedResult;
    }


As you can see the code above does the job of displaying the retuned xml from the webservice. It works. We can understand that XML because we are techie enough but imagine a normal user seeing a xml values on his screen? Yup. Not good. The best way to present data to a user is to show values in tabular form. A lot more pleasing to the eyes and much easier to understand. With that said let’s start by replacing the Label control in the form with a DetailsView control. The new aspx page for our form should look like this:


As you can see in the old code for the Click event we are able to get the XML and display it on a Label. What we need to do now is to read that XML string and assign it to a our DetailsView but there is one problem… The XML string needs to be converted to an object that supports IList or IEnumerable first before it could be loaded to our DetailsView.


To solve this problem I’ve decided to create this method that accepts an XML string and converts it to a DataSet.


Now we can modify our our executeButton_Click event


All we did was pass the xml string to the XmlString2DataSet function to retrieve a DataSet containing the stock quote information and then assigning that DataSet object to our DetailsView for display. Below is how the final form looks-like after our modification



Now that is more presentable! I hope I was able to share with you something useful. Next stop, we’ll be building Master-Detail pages in ASP.NET ;)


Care for the code? Grab it here: KeithRull.ConsumingWebServices.Part2.zip (5.76 KB)