I’m always somewhat amazed when I read something from documentation that is not straight forward and it actually works.  So amazed and excited that I often feel the need to blog about it.

So, here is the problem.  I created a CodeFirst implementation of EntityFramework in Visual Studio and created a simple hierarchy in my data model.  That is, without showing all the code, here is what I have:

public class Person
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public virtual List<EmailAddressInfo> EmailAddressInfoList { get; set; }
..
}

public class EmailAddressInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public string EmailAddress { get; set; }

}

public class EmailAccount
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
...
}

Now, if you execute a LINQ command like the following:

var recs = (from data in db.Persons
select data);
foreach (var rec in recs)
{
foreach (var email in rec.EmailAddressInfoList)
{
Console.WriteLine(email);
}
}

You get the error:

Exception Details: System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

 

image

 

To solve this, you need to tell EntityFramework/CodeFirst to include the EmailAddressInfoList in the query.  All you need to do is change the db.Persons to db.Persons.Include("EmailAddressInfoList") as follows:

 

var recs = (from data in db.Persons.Include("EmailAddressInfoList")
select data);

 

Then, it all works!

Hope this helps.

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.

 

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.

 

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…)

The What and Where

Something that may not be obvious is if are creating an asp.net WebForms project and you put a datasource such as SqlDataSource or ObjectDataSource for example on the page, how can you prevent the SqlSelect associated with that datasource from being triggered.

The answer is to set the control’s visible property to false.  That’s it!

(more…)

I normally don’t blog about such simple things, but somehow, I’ve always done this in about 5 lines of code and I ran into at eggheadcafe in one line this morning.  Simply using the File static method ReadAllBytes of the File class.

Here it is.  Can’t be much simpler I don’t think.

 

byte[] downloadByteArray = File.ReadAllBytes(imageLocation);

That’s it! hope this helps someone else.

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.

Introduction

If you’ve started using SqlAzure for your SqlServer with your Azure application, you’ve probably discovered that you get a reasonable number of connection failures.  The advice from the Azure team is add retry logic to all your connections to SqlAzure. There is a long discussion posted by the Azure team here.

The key paragraph states the problem as follows:

The Problem
One of the things that SQL Azure does to deliver high availability is it sometimes closes connections. SQL Azure does some pretty cool stuff under the covers to minimize the impact, but this is a key difference in SQL Azure development vs. SQL Server development.

Basically, what this means is that you must be able to deal with connections failing when you call SqlAzure.  Something that all of probably should have been doing forever, but because most of the time SqlServer is running on your local LAN and the likelihood if a connection failing was next to zero unless something else was going terribly wrong.  Certainly not something we had to do on regular basis.  To emphasize that even more, most of the controls built into asp.net that open connections to sqlserver don’t even do this and that’s from Microsoft itself.

The solution proposed in the thread mentioned above basically has you add tons of code to everyplace you access a connection object.  Personally, I don’t like that because I have hundreds if not thousands of places I open connections and inserting tens of thousands of lines of extra new untested code is a little scary.

So, what to do?

Fortunately, another team at Microsoft, known as the Windows Server AppFabric Customer Advisory Team published a general purpose solution using Extension Methods and some darn clever coding wrote a great article and published code including azure examples that solves this problem very elegantly without requiring a lot of changes to your existing code base.

In this article I plan on giving an example and publishing a sample project that uses this code with SqlAzure to solve the connection retry problem.  My goal here is not to simply restate what they published but to simply have a very simple concrete example of using their library.

(more…)

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!

So, It’s always annoyed me that when I want to check an AppSettings variable from app.config or web.config I’ve had to go through code like the following:

<appSettings>
<add key="AccountStorageURL" value="http://testit.blob.core.windows.net/" />
 

public string GetStorageURLOld(string username, string password)
{
var accountStorageURL = string.Empty;
if (ConfigurationManager.AppSettings["AccountStorageURL"] != null)
{
accountStorageURL = ConfigurationManager.AppSettings.Get("AccountStorageURL");
}
return accountStorageURL;
}

I should have realized a long time ago that this code is equivalent to:

public string GetStorageURL(string username, string password)
{
return ConfigurationManager.AppSettings["AccountStorageURL"] ?? string.Empty;
}

Just thought I’d share in case someone else had forgot this also.
 
HTH’s.

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.

I’ve recently started using CodeRush with Visual Studio 2010 and am so far very impressed with the convenience it adds to coding.  One thing that is very clear is that the creators of CodeRush are real programmers and look very hard for patterns that us developers are constantly doing.  As I run into these things that get my attention, I plan on blogging them.  Some are just earth shattering, and others, just nice to have.  This particular one is a nice to have.

So, say you have code like this:

 

var sessionAttendeeOds = 
new SessionAttendeeODS();
listSessionAttendees =
sessionAttendeeOds.GetByUsername(Context.User.Identity.Name);
 
(more…)

In this post, I’ll show a simple example of how when you add a parameter to C# method, ReSharper gives you a simple prompting to ask if you want to add a parameter to your method, or create an overloaded method that gives you the flexibility to maintain the old method signature and have the new method.

(more…)

I’ve recently started using Microsoft’s WCF Data Services which supports OData Services.  What this means is that we can access resources by simply specifying a URI.  This concept greatly simplified building an ORM layer on a web site, as well as creating the linkage between the server side data and the client side application, which in my case is usually a browser.

So, the issue this blog addresses is that if you form a URI with the parameter $top={anything}, your data will automatically be sorted.  The documentation for OData on top basically says that, but it could be clearer.  It says the following:

“If the data service URI contains a $top query option, but does not contain a $orderby option, then the Entries in the set needs to first be fully ordered by the data service.”

What actually happens is when you use the orderby clause, the data will be sorted 100% of the time for you, whether you do it or not.

(more…)

Here is a shorthand way for converting a list of strings defined as follows:

 List<string> strings = new List<string>
 
	{
		"a","b","c"

	};

To something that looks like:

(more…)

  Title Of Each Article Video Included With Each Post
Part 1 Introduction To RIA Services In Silverlight (This Article) 7 Minutes
Part 2 Basic RIA Services And DataGrid With  VS 2010 Tooling 14 Minutes
Part 3 Adding A DataGrid With Connect The Dots DataBinding in VS 2010 13 Minutes
Part 4 Adding a Navigation Page to a Silverlight Business Application Template 11 Minutes
Part 5 Adding Speakers Page Template With Converters In Visual Studio 2010 Beta2 11 Minutes
Part 6 Adding A Sessions Page That Includes a Query Parameter In Silverlight VS2010 Beta2 10 Minutes
Part 7 Basic Authentication and Authorization In RIA Services 5 Minutes

Get the Flash Player to see the wordTube Media Player.

This article is very short.  In the actual presentation, there was not much time to talk about this so a brief overview was done.  Basically, it’s all standard WCF stuff.  The idea is that the Silverlight Business Template adds logging in and supports Authentication just like an asp.net application does.  It uses the DomainDataSource to do the bridging between the silverlight clientside app, and the web application.  Authorization is built into the login module also so that you can assign attributes to your domainservice classes to restrict access.

(more…)

© 2012 PeterKellner.net. All Rights Reserved