Feed

While trying to use the Session state dictionary in a web application, you may eventually receive the following exception:

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

To my surprise, session state has to be enabled before it can be used. I followed some steps that I found while digging for the solution online that might be helpful:

1. Enable the ASP.NET Session State Manager Service (under Control Panel > Administrative Tools > Services)

2. Enable it in the web.config file: <pages enableSessionState="true"> 

3. Add the proper http module to the web.config: <add name="Session" type="System.Web.SessionState.SessionStateModule" />

4. At last but not least: Make sure you're accessing the Session object after it has been initialized. This is very important, since if you try to manipulate it in the page constructor, for example (which was my case), you'll still get the above exception, even after executing steps 1, 2 and 3. You should be able to access it after the page OnLoad event has been fired.

Tags:

How to use the results of a database query using Linq to fill a DataGrid? It should be no big deal since there is a useful CopyToDataTable extension method:

   1:  public static DataTable CopyToDataTable<T>(
   2:      this IEnumerable<T> source
   3:  )
   4:  where T : DataRow

 However, there is a problem: T has to be a DataRow. When returning query results from the database, especially with EF, your query results are not DataRows (and I wonder if the same is true for Linq to Sql too). So, in this case, you'll have to fill the DataTable by hand. Thanks to this good blog post, I was able to fill it:

   1:  DataTable dataTable = new DataTable();
   2:  dataTable.TableName = "ResultsTable";
   3:  dataTable.Columns.Add("User", typeof(string));
   4:  dataTable.Columns.Add("TotalJobs", typeof(int));
   5:   
   6:  var query = /* your linq query comes here. no restrictions! */

we have the DataTable and the query set up. Now, the tricky part!

   1:  var results = query.Select(anonym => new Func<DataRow, int, int, DataRow>(
   2:      (DataRow row, int index, int count) =>
   3:      {
   4:          row["User"] = index;
   5:          row["TotalJobs"] = count;
   6:          return row;
   7:      })
   8:      .Invoke(dataTable.NewRow(), anonym.Index, anonym.TotalJobs));
   9:   
  10:  results.ToList().ForEach(row => dataTable.Rows.Add(row));

Absolutely a good piece of unreadable code :)

query variable are your Linq query results, which may be an IEnumerable of some of your data entities or even a anonymous type. It doesn't matter! For each element of this enumeration, we're creating a DataRow and assigning some values to its columns. Then, we call Invoke to indeed invoke our anonymous delegate Func, passing in our anonymous type properties, that are used later to fill the DataTable.

You'll probably gonna need to read it a couple times to digest it a bit and still it will look "WTF did I really wrote this code?!?" after a couple days :)

Tags: ,

Some time ago, I wrote about predicate building with the Entity Framework and how the use of AsExpandable solves the issue. Frequently, people see and ask me about the following error, which is also associated with the same root cause that I blogged about in my previous post. However, it may be a bit confusing as to what is the cause of the following exception:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

Again, as I stated before, calling LinqKit's AsExpandable solves this problem. As per Tomas Petricek (the creator of a good part of this great work):

"(...) ToExpandable creates a thin wrapper around the DLINQ Table object. Thanks to this wrapper you can use second method called Invoke that extends the Expression class to invoke the lambda expression while making it still possible to translate query to T-SQL. This works because when converting to the expression tree, the wrapper replaces all occurrences of Invoke method by expression trees of the invoked lambda expression and passes these expressions to DLINQ that is able to translate the expanded query to T-SQL."

 In the last days, while looking for a way to do image cropping in ASP.NET, I found out several high quality tools that do the job very well. The main one is a great jQuery plugin called jCrop. It has many useful features out of the box coupled with a well forged look and feel, which made me choose to use it with no doubt.

What I needed, exactly, was a way to enable users to upload pictures and crop them on the fly before storing them on the website database. I often use ASP.NET dynamic data to build complete and fully functional data driven websites in minutes. ASP.NET Dynamic Data is based on page templates and field templates that are brought together in runtime using user controls, in order to generate custom forms for manipulating the database tables.

One of these field templates, is DbImage, which is available in the Dynamic Data preview 4 on Codeplex. Basically, it maps a binary table column to a user control that consists of a FileUpload control, which you can use to upload the image. Then, the image bytes are stored in the database. It is obviously not the best way to store images on a database, but it is extremely convenient. In an ideal scenario, the table would only point to the actual path of the image on the disk.

So, my work was to couple together jCrop and ASP.NET Dynamic Data DbImage control, so that the user may choose to crop the image just before it is saved to the database.

I found a very complete and interesting post on this topic at mikesdotnetting.com, which handles the actual image cropping part of the work with C#.

My work was then based on Mike's post and jCrop, putting it all together inside a DbImage to enable the whole workflow. The general flow is strongly based on Mike's code using panels and hidden fields to store the selected X, Y, Width and Height, but I moved to a more wizard-like flow, which should be more straightforward to the regular user.

I first added a "Crop.." button to the control that should launch jCrop with the selected image file. 

 
Next step was to open a AJAX ModalPopupExtender and show the selected image ready to be cropped with jCrop:
 
Last step, check the cropped image and finish the Wizard:
 
 
The cropped image is then scaled down and added to the form:
 
In order to scale down the cropped image, I used a code from Rick Strahl and added to a page called GetThumb.aspx. This page receives the desired filename in the query string, fetches it from the crop temporary files directory and writes it to the response stream.
 
I am providing the whole set of files needed to accomplish this in a zip file. Follow these instructions for setup:
1. Put the DbImage_Edit.ascx* files in the <dynamic data website>\DynamicData\FieldTemplates\ folder;
2. Put the GetThumb.aspx* files in the website root ("~" folder);
3. Put the Limaf.Tools.Web.dll file in  <dynamic data website>\bin folder (the Crop and Thumb functions are there).
4. Create an 'images' folder in your project root
 
If you prefer, you can copy/paste get Mike's Crop and Rick's Thumbnails functions yourself and build them as part of the website. In this case, step 3 above is not needed.
 
I may have forgotten a file or a step or two, so please let me know if anything goes wrong.
 
Till next time! 

Today I just earned my third MCTS certification: Microsoft .NET Framework 3.5, ASP.NET Application Development.

The exam was good and under my expectations. Not very hard you've been working with ASP.NET on a daily basis for quite some time. For the ones that are planning on taking this exam in the future, be aware that you'll face some mobile development specific question, of which I am not very familiar with. ASP.NET AJAX and ADO.NET topics appear extensively through the exam. It is composed of a total of 50 questions, spanned in seven topics:

- Configuring and deploying web applications

- Consuming and creating server controls

- Working with data and services

- Troubleshooting and debugging web applications

- Working with ASP.NET AJAX and client-side scripting

- Targeting mobile devices

- Programming web applications

The passing score is 700/100 (as always). My score was 810! Smile


Today my Firefox started behaving very strangely and extremely slow especially when using Gmail and Google Reader. I tried cleaning the cache, restarting but nothing solved. Then, I realized I had installed Skype these days and it installed a Firefox add-on without even asking me for permission. I removed the add-on and Firefox went back to normal operation, fast and reliable, as always.
I have to say that Skype dissappointed me this time installing a defective add-on on my browser, since I don't even remember to have allowed it to do so.
Seems like I wasn't the only one who had this problem. :(

Tags: , ,

About the Author

myself
My name is Felipe Lima and I am a Software Engineer and co-founder at Quavio, a digital agency at Porto Alegre, Brazil. I am interested in technology, programming with the .Net Framework and sports. Check out my full profile.

Powered by BlogEngine.NET 1.4.5.0