Part 1 Basics
Part 2 Enhanced (coming)

 

Introduction

In this series of articles, we will take the reference application build by the Sencha product team for using Sencha’s MVC pattern running with an ASP.NET 4.0 project (IIS in production).  The first article takes the reference Sencha MVC app and with almost no changes, makes it work with the ASP.NET Visual Studio 2010 project.  By default, the application works with JSON static files.  We change that to work with an ASP.NET MVC3 project.  The second article in the series embellishes the application to include a more real user experience by adding additional functionality and data.  The improved functionality includes both date and number columns as well as paging.  It also adds functionality for inserts and deletes which are left out of the base app from Sencha.


Visual Studio Project SenchaMVCASPNetSolution

 

The Final Project when running:

 

image

 

(more…)

Normally, when we stick a JSON file up on an IIS web server, all we have to do to get to is is to set the Mime type.  One easy way to do it is to add to your web.config the following:

 

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
...

 

This works great as long as the GET verb is used (or just enter the on the url like http://mysite.com/myfile.json).

So, what if you "need” to use the POST keyword.  Say for example, you can not change the JavaScript file to use GET instead of POST to get the file.  I was hoping to find some simple web.config parameter to set but I had no luck.  I even posted to StackOverflow and so far, the answers have been less than helpful.  Who knows, maybe by the time you read this, there will be a better answer then my solution which is to write a simple asp.net handler and register it to type json.

 

So, here is the simpler handler that does the trick:

 

public class JSONHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
string output = System.IO.File.ReadAllText(context.Request.PhysicalPath);
context.Response.Write(output);

}

public bool IsReusable
{
get
{
return false;
}
}
}

 

and the associated web.config entries

 

<httpHandlers>
<add verb="*" path="*.json" validate="false" type="JSONHandler" />
</httpHandlers>
</system.web>

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
<handlers>
<add verb="*" path="*.json" name="JSONHandler" type="JSONHandler"/>
</handlers>
</system.webServer>

I’m assuming there is a simple way, but for now, this works for me.  Please post a better solution and reference it or just tell me in the comments.

 

In May of 2009 I discovered some significant performance problems that I blogged about.  In summary, I had tracked it down to the issue of LINQ2SQ having to create a full expression tree on every instantiation of a LINQ2SQL query.  I’m not a compiler write kind of guy but do respect the complexity of that and doing things like building expression trees, but still this really sucked.  Using the compile syntax in LINQ2SQL is very awkward, and IMHO takes all the fun out of using LINQ2SQL.  If you don’t remember my post, here is the graph showing the evil happening.

 

image

So, what is a Microsoft MVP to do?  I complained to everyone at Microsoft I knew.  I made this my mission for about a year.  I was told time after time that the problem was hugely complicated and no one was working on making it any faster.  I just could not believe it because I felt this was such a barrier to success to LINQ2SQL type technology (now Entity Framework really) that Microsoft just could not ignore my findings.  I was actually surprised that I was the only one screaming about this.

Well, quietly, Microsoft has announced that in .Net Framework 4.5, Entity Framework will include “Auto-Compiled LINQ Queries”.  This is awesome!   When it comes out, I’ll be testing and it giving feedback.

For now, I’m a very happy camper.

 

image

 

Scott Hanselman posted a while back about a browsers definition problem with some ASP.NET sites that causes problems.  Microsoft has articles on this also.  Having just received my BUILD tablet that includes IE10, I tested the Silicon Valley Code Camp web site and discovered that when you login, then switch to another page, the login did not stick.  After uploading the two files Scott mentions (firefox.browser and ie.browser), the problem goes away.

Thanks Scott for the heads up.

 

image

 

I know this is old hat, but after recently having a conversation with one of the ASP.NET Team guys about how easy Web Forms is to use, I thought I’d just post a simple example of that.  Here is the scenario.  You have a simple GridView with just three columns (Select,Id,TagName).  You want to be able to capture what happens when the user pressed the Select command and capture the Id.  It looks like this:

 

image

 

And has an aspx page like this:

 

<asp:GridView ID="GridViewNotSelected" runat="server" AllowSorting="True" 
AutoGenerateColumns="False"
DataSourceID="SqlDataSourceTagsNotSelected"
onrowcommand="GridViewNotSelected_RowCommand">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
CausesValidation="False" CommandArgument='<%# Eval("Id") %>'
CommandName="Select" Text="Select"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField
HeaderText="&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;">
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" Text='<%# Eval("TagName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


Notice that in the TemplateField there is LinkButton with a CommandArgument that simply extracts the TagName with the current Id of the SqlDataSource.  Now, all you need is the RowCommand event and you are done.  Here it is in C#.

 

protected void GridViewNotSelected_RowCommand(object sender, GridViewCommandEventArgs e)
{
int tagsId = Convert.ToInt32(e.CommandArgument);
}

And finally, the proof!

 

image

 

Very very simple.  HTH’s.

I have heard all the hype about how great Sql Server CE 4.0 and that it is now standard with Visual Studio 2010 SP1.

 

image

 

I’ve got a small project (1 table) that I’d like to include in an asp.net website project so I decided to give it a try.  For the most part, things have gone smoothly, however I did have a couple hiccups I’d like to mention.  One cost me $9 because I was doing this implementation on an airplane and immediately, I had a failed connection with a confusing error that I needed Bing to lookup  (more details below).

 

(more…)

 

Introduction and Problem

Converting Data Formats back and forth between browser and back end servers can be a little confusing.  In my case, I have a simple Sencha ExtJS 4.0 form that the user types a date into.  That date gets passed through an ajax request to the Microsoft asp.net controller, then that dates updates the SqlServer Database.  When the Date is displayed on a Grid Panel, again, an ajax request is made that grabs the date from the controller, then formats it using the MS dateFormat from ExtJS and hopefully, the same date the user typed in gets re-displayed.

So, let’s look at the details.

Posting the Date To the Server (View From JavaScript)

First, we need to define an ExtJS Model that has the date in it.  That codes looks like this in my case.

(more…)

I often forget that the simplest way (IMHO) to connect to a Microsoft SqlServer 2008 database is to use the web.config connection for making a Trusted connection.  Basically, it keeps you from having to put a username and password in the web.config and also from having to keep track of different username and passwords on different systems (like where you deploy to for example).  The simplest connection string I can think of looks like this:

 
 
<add name="MyConnName" connectionString="Server=.;Database=mydbcatalogname;Trusted_Connection=True;" 
providerName="System.Data.SqlClient" />

Notice that I’m using the “.” as the server name.  This allows me to reference the local system where my sqlserver lives. Not necessarily a best practice, but often is the case.

Upside

One big benefit is if you fall victim to a disk scraping attack, or someone gets a hold of your source (maybe from version control?), you don’t give up your passwords.

Downside

If you SqlSever is not on the system system as your web project or application, then this become more tricky because of the cross system authentication issues.  If you have active directory installed on both systems, then this works also.

To build fully-featured web applications that support complex interaction in a reasonable amount of time requires a high-end JavaScript library. Someday, maybe JQueryUI will be good for this, but for now, the choices are few and include ExtJS, Dojo, YUI and a handful of others. This session will use ExtJS as the example. We will use Microsoft’s ASP.NET MVC as the data / CRUD layer and from that, we will build a typical LOB (line of business) application using complex UI elements. Those elements include layout managers, data grids, extensive validation, spinner controls and other advanced UI features. To get an idea of what I’m talking about, spend five minutes looking at the examples on the ExtJS web site demonstrating these advanced web UI features http://www.sencha.com/products/js/. You will be convinced that spending hundreds of hours trying to build something not nearly as well done as this is a waste of time when there are such excellent libraries already built for you.

The source attached below for my demos.

image

(more…)

Getting filenames to use as scratch files is usually very straight forward.  Well, today, I found out “not so much”.  I decided today was a good day to tackle the problem of why is my file synchronization product we are about to release still littering my tmp directory with files when it finishes.  Turns out, it’s the subtle difference between the above two Path member functions GetTempFileName and GetTempPath.

The big difference is that GetTempFileName actually creates a file where as GetTempPath simply tells you where the file is going to be.

Here are some words out of MSDN for Path.GetTempFileName

This method creates a temporary file with a .TMP file extension.

And For Path.GetTempPath

The path to the temporary folder, ending with a backslash.

Subtle, but clear when you read the doc.  If you read the community content, there is a humorous discussion with someone saying “you might as well use the other one, it does the same thing”.  All I can say to that is read the docs!  I got stung today, but never again.

I’m now creating my filename with a string as follows which kind of does the same thing, but not really. 

 

public static string GetTempFileWithGuid(string filePrefix)
{
string retFileName = string.Format("{0}{1}{2}.crsync",
Path.GetTempPath(), filePrefix, Guid.NewGuid());
return retFileName;
}

HTH’s.

I’ve been slowly building up my Azure experience over the past few months and actually plan to release a product using Azure during the next month or two.  Programming Windows Azure has been a huge value to me in learning both the basics of the Azure platform as well as the details.  It has a great balance of theory verses practice.  I strongly recommend this book if you are new to Azure or even if you have experience with Azure.  I often find myself going back and re-reading sections to better understand things.

 

Two of the sections I feel are particularly well written or the ones that talk about Storage and Tables (chapters 7 and 8).  The application I’ve been working on heavily uses blob storage and I spend lots of times re-reading those sections.  Azure tables is a hard topic to get a sql server programmer like me to get my head wrapped around.  Sriram does a great job of talking directly to someone like me to help me understand how and when to use tables.

Again, I whole heartedly recommend this book.

Background

This post shows a very simple technique for processing a gzip compression on a background thread using c# with Visual Studio 2010.  What is unique here is we are using no statics to do it.  I’m not totally against using statics, but in general, it is best to avoid them.  I’ve heard the notorious Ward Bell say statics are evil and have had many cases where they have bitten me.  Since I heard Ward say this, I’ve been trying to avoid them where I can.

 

The Simple Problem

The problem is to simply compress a file to bytes and return to us the compressed, uncompressed and byte array of the result.  We can pass parameters into a thread, however we can not return them (when I say thread, I mean the anonymous method that processes our data).

(more…)

 

Background And Conclusion

In my very last post I talked about how using SHA256 seemed to not be affected by whether you use Buffered or Not Buffered streams.  An astute reader (Samuel Jack) referenced an article by one of my favorite ex MIcrosoft employees (Brad Abrams) saying that almost all the .Net streams have buffering built in.

Well, I think SHA256Managed does not.  One of the challenges I’ve been facing lately with my current project is to provide feedback while doing all kinds of byte piping (stream stuff).  While figuring out how to do this, I inadvertently figured out that buffering makes a huge difference.  Briefly, let me show my results first, then talk about the code that went into it.

Notice that when I use a 64MB Buffer, the memory used for the process is 77MB and when I use an 8MB buffer, the memory used is 17MB.  Clearly the buffer allocated matters.  Just for information, I’ve also included the code that does not break the SHA256 hash into blocks, and it has the same results based on the size of the Memory Buffer declared.  That is, small buffer, small use, big buffer, big use.

(more…)

* I just added another post on similar topic and added more details on performance and a case where buffered memory usage really did matter:  http://peterkellner.net/2010/12/03/using-sha256managed-to-generate-sha256-hash/

I’m building a file synchronization with the cloud application and I want to store a checksum with the file so that I can verify later that the file is what I think it is. I’m not a crypto guy so I searched around the internet for a solution.   I found lots of examples and settled on this one that uses SHA256 for the job.  I also found some comments saying that it would be more efficient to wrap it in a BufferedStream rather than processing the entire file at once.

Example Links: http://efreedom.com/Question/1-1345851/MD5-File-Processing ; http://stackoverflow.com/questions/1177607/what-is-the-fastest-way-to-create-a-checksum-for-large-files-in-c/1177744#1177744

My intention for this post was to show how much more efficient it would be to use BufferedStream, however my results don’t show that.  I’m guessing that somehow, the efficiency is happening under the covers in a place I don’t see.

If anyone knows this space well, please feel free to comment and suggest a better method.  I’m publishing my source below for the test and my surprisingly similar results whether I used buffering or not.

Looking forward to the responses.

(more…)

Understanding how Azure Blob Storage can be used to simulate directory structures is a little tricky to say the least.  I’ve got a long forum thread on the Windows Azure Community site  now discussing the details.  As always, Steve Marx has been a big help here with a bunch of code. Steve’s got a great blog where he provides lots of examples and insights.  Neil Mackenzie has also contributed here to getting to the answer.

Just so we now have an example, I’ve put together a simple windows form app that let’s you set a few variables in your app.config to point at your azure storage and container, let you view your app as a tree as well as see the code how it can be done.  I have not commented the code much, just thought it would be good to get it out there.  The running application shows you the data as follows.

image

(more…)

So, just a short post in case someone runs into the same problem I had today that cost me about 2 hours using Visual Studio 2010.  Basically, if you are using the BackgroundWorker in a windows app (with visual studio) and find that the method is not finishing and seemingly not throwing exceptions, maybe it actually is and you are missing it.

That is, if you have code like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(0,"starting...");
for (int i = 0; i < 10;i++ )
{
if (i > 5)
{
throw new ApplicationException("any error here");
}
backgroundWorker1.ReportProgress(i, "working...");
}
}

and you run it in the debugger, it will not stop by default when the exception is thrown (like it would in single threaded code).

So, I recommend doing the following and setting a break point to see the error.

image

 

Another thing you can do is bump up where debug’s stops uisng the dialog:

image

goes to:

image

 

Then, you will get an error you expect.

 

image

HTH’s!

 

The End Result

 image

 

Motivation

As you can imagine, The Silicon Valley Code Camp web site has lots of “back end” functions that need to be done. That is, things like doing mailings, assigning roles to users, making schedules, allocating rooms and times and literally  hundreds of other tasks like that.  Over the 5 years of code camp, I’ve always built simple protected asp.net web pages to do this.  I’ve always used the simplest asp.net control I could find, such as GridView, DetailsView, DropDownList, and SqlDataSource.  The interfaces usually basically work but are very clumsy and lacking in both functionality and aesthetics.

 

Why Now

I’ve seen lots of short demos on LightSwitch for Visual Studio and recently read on someone else’s blog that they are now building all their simple applications using LIghtSwitch.  Also, my friend Beth Massi has been running around the world espousing the greatness of this product and I knew if I ran into any dumb issues that she’d bail me out (I’m the king of running into dumb issues.  I’ve found that given two choices that seem right, I always pick the wrong one which is what actually happened here along the way, and Beth did bail me out).

(more…)

There are 10,000 ways to do this.  Back way back when (ASP.NET 1.1) days, we would have created either a custom control to do this, then added a Repeater control on the page to display it.  Well, the Silicon Valley Code Camp Website was started back in those days and since what I want is so simple, I decided to do just that (minus the custom control).  I really only wanted to spend about 10 minutes doing this, and as it turned out, it took about 30.  Oh well, 3x plan verses execution.  Could do better next time.

So, here is basically what I want on the left side bar of the home page of Silicon Valley Code Camp:

(more…)

So, you have a simple class that has a bunch public properties and you want to be able to use ToString() on it to show some data?  It’s easy.  All you have to do is override the ToString() class inside your C# code.

So, here is an example class that does that.

public class DbProgressReport
{
public string ScopeNameProgress { get; set; }
public string SourceOrDestination { get; set; }
public string TableName { get; set; }
public int TotalRecords { get; set; }
public int ChangesApplied { get; set; }
public int ChangesFailed { get; set; }
public int ChangesPending { get; set; }
public int Deletes { get; set; }
public int Inserts { get; set; }
public int TotalChanges { get; set; }
public int Updates { get; set; }
public DateTime LastChangeDate { get; set; }

public override string ToString()
{
string readableDbProgressReport =
string.Format(
"{0} ScopeName {1},Table {2},TotalRecords {3}"
SourceOrDestination, ScopeNameProgress, TableName);

return readableDbProgressReport;
}
...

Now, all you have to do when accessing this class is use the ToString property.

That is:

DbProgressReport dbProgressReport = 
new DbProgressReport("source","scopename","tablename");
string str = dbProgressReport.ToString();

and the output will be:

source ScopeName scopename,  Table tablename

Simple as that!

Hope this helps.

In my previous post (http://peterkellner.net/2010/07/10/installing-umbraco-to-win7-step-by-step/), I detailed the steps to use WebPI to install a fresh version of Umbraco on a Windows 7 Ultimate 64 bit system.  Now that I’ve done that, and played with it for a few hours, I’d like to start again with a fresh (no RunWay) set of data to play with.

I posted on the Umbraco forums and got some tips, but I thought I’d document the process here because I’m sure I’m going to be doing this again and thought it best to have some notes I can go back to (and that might help others newbie’s to Umbraco while I’m at it).

(more…)

© 2012 PeterKellner.net. All Rights Reserved