December 2007 - Posts

Execute a Stored Procedure: Quick and Dirty

Ok, I usually try to only talk about best practices but sometimes we all need a quick an dirty few lines to execute a stored procedure, no Enterprise Data Access, no LINQ, just System.Data and the managed provider for our given DB. Well here goes.

    1             //get the config info from the app.config file

    2             ConnectionStringSettings myConnectionSettings = ConfigurationManager.ConnectionStrings["ConnectionKey"];

    3             DbProviderFactory myProvider = DbProviderFactories.GetFactory(myConnectionSettings.ProviderName);

    4 

    5             using (DbConnection myConnection = myProvider.CreateConnection())

    6             using (DbCommand myCommand = myProvider.CreateCommand())

    7             {

    8                 // Get the connection string from the connectionsettings

    9                 // This gets us the specific provider by which we will connect

   10                 myConnection.ConnectionString = myConnectionSettings.ConnectionString;

   11                 myCommand.Connection = myConnection;

   12                 myCommand.CommandType = System.Data.CommandType.StoredProcedure;

   13 

   14                 DbParameter parm = myProvider.CreateParameter();

   15                 parm.ParameterName = "Your parameter Name";

   16                 parm.Value = id;

   17                 myCommand.Parameters.Add(parm);

   18 

   19                 // Open the connection

   20                 myConnection.Open();

   21 

   22                 myCommand.CommandText = "Name of the stored proc";

   23                 myCommand.ExecuteNonQuery();

   24             }

Posted by sweisfeld | 1 comment(s)
Filed under: ,

2007 Day of Silverlight

Our original plan for Day of Silverlight was to have Jesse Liberty from the Silverlight product team come down and fill us in on all things Silverlight. After lunch sponsored by KFoce (http://www.kforce.com). We planed to close the day out with a presentation by John Papa on WPF. Well the gods must not have been smiling on us because on the Tuesday before the event I got a frantic email from Bill Reiss (https://mvp.support.microsoft.com/profile/Bill.Reiss) telling me to read Jesse's blog (http://silverlight.net/blogs/jesseliberty/archive/2007/12/10/did-you-know-1-if-you-fall-on-black-ice-you-can-dislocate-your-shoulder.aspx). After a few emails with Jesse I learned that he would have to cancel due to the fact that he needed to undergo emergency surgery to repair the damage that was done. Now I start to make phone calls to see who can fill in for Jesse. My local Developer Evangelist from Microsoft, Joe Healy (http://www.devfish.net) stepped up offering a Silverlight 1.0 presentation. Bill then said that he would bring home the Silverlight content with an overview of Silverlight 1.1 (2.0 or whatever the heck marketing is calling it this week). After a deep breath I sent out an email Friday afternoon telling all the registered attendees what had happened. Later that evening before I went to bed I decided to check my email one last time and I got an email from John Papa (https://mvp.support.microsoft.com/profile=7D3BBCB7-E956-4730-B3E0-24BD7EAD0D5D) telling me that he got sick on a business trip and would not being able to present. As disappointed as I was after a quick email to Jon Goodyear (https://mvp.support.microsoft.com/profile=48387CAA-D3A6-4263-9446-43493F31E240), President of ASPSOFT (http://www.aspsoft.com/) he stepped up to fill in for his co-worker with an offer to do a presentation on MVC (http://weblogs.asp.net/scottgu/archive/tags/MVC/default.aspx).

With the scheduling nightmare behind us, we got to the venue early and began the process of setting up. I have to give a big thanks to the volunteers that made the logistics of the day happen, Ken Tucker (https://mvp.support.microsoft.com/profile=9F6B5CDE-AB25-4864-998C-A6652B33D234), Rosemary Gray, Jessica Sterner, Fabio Honigmann, and Brian Banville. Also have to give a big thank you to Lenny Portlli and Melinda White from Seminole Community College for all there help with the venue.  While we started a little late Joe's presentation went off well. But we soon realized that we were going to need a microphone if we were ever going to hear in the back of the room. A thoughtful attendee offered to drive home and get his microphone to let us borrow. I wish I got his name so I could properly thank him. After Joe spoke Bill did his thing, the great part about Bill's presentation is the perspective that Bill has on things being, one of us that actually had to use the technology. After Bill concluded his presentation everyone enjoyed there lunches and got a chance to talk to the people from KForce. Concluding the day Jon gave us a great overview of the new MVC features that Microsoft is going to release.

All in all, even with all our scheduling problems I think the day went very well. I had many attendees come up and tell me what a good time they had and how much they learned. You can see the Day of Silverlight Video here (http://www.onetug.org/dayofsilverlight/video.htm) published with Silverlight of course, and you can see the sideshow here (http://cid-afc22ba66ea68f7d.spaces.live.com/photos/cns!AFC22BA66EA68F7D!115/).

 

Thanks again to everyone that help with this event, it would not have been possible without your help!

Posted by sweisfeld | 1 comment(s)

Generate, Compile and Execute Code Dynamically

Like any good developer, when someone comes to my desk and says you cannot do something I have to prove them wrong. This was one of those challenges. He said you cannot “generate, compile and execute code on the fly in .NET”. I said yes you can, he said no you cannot and after five minutes of back and forth I decided to throw together this example.

Step 1: Build the code
Here you have 2 options: code as strings, code from CodeDom. What one you pick depends on what you are doing. In “Programming Microsoft ASP.NET 2.0 Applications Advanced Topics by Dino Esposito” he does a good job of explaining each. “Using a text-writer binds you to a particular language, but it allows you to write code more quickly. The CodeDom API is more abstract and certainly more complex and quirky to write. CodeDom requires a larger memory footprint then a text-writer based solution. In terms of readability, no approach is perfect. CodeDom is hard to read because of its level of abstraction; a text-writer solution has code interspersed with strings and placeholders, and it can be dangerously error-prone to modify and maintain.”

I decided to use the CodeDom technique. So for my example I am going to create a simple static add method that takes in two integers and adds them together and returns the results.

    1         //Step 1: Build the Code

    2         //Create the code unit that we are going to work with

    3         CodeCompileUnit code = new CodeCompileUnit();

    4 

    5         //Give it a namespace

    6         CodeNamespace ns = new CodeNamespace("GeneratedNamespace");

    7         code.Namespaces.Add(ns);

    8 

    9         //Create the class

   10         CodeTypeDeclaration cls = new CodeTypeDeclaration("GeneratedClass");

   11         cls.IsClass = true;

   12         cls.Attributes = MemberAttributes.Public;

   13         ns.Types.Add(cls);

   14 

   15         //Create the method

   16         CodeMemberMethod method = new CodeMemberMethod();

   17         CodeParameterDeclarationExpression val1 = new CodeParameterDeclarationExpression(typeof(int), "value1");

   18         CodeParameterDeclarationExpression val2 = new CodeParameterDeclarationExpression(typeof(int), "value2");

   19         method.Attributes = MemberAttributes.Public | MemberAttributes.Static;

   20         method.Name = "Add";

   21         method.Parameters.Add(val1);

   22         method.Parameters.Add(val2);

   23         method.ReturnType = new CodeTypeReference(typeof(int));

   24 

   25         method.Statements.Add(

   26             new CodeMethodReturnStatement(

   27             new CodeBinaryOperatorExpression(

   28             new CodeArgumentReferenceExpression("value1"),

   29             CodeBinaryOperatorType.Add,

   30             new CodeArgumentReferenceExpression("value2"))));

   31         cls.Members.Add(method);

Now that you have the code generated you might want to take a look at it. You can convert it to a string by doing the following:

    1         //Output the generated code to the page so we can see it

    2         StringWriter sw = new StringWriter(new StringBuilder());

    3         CodeDomProvider cdp = new CSharpCodeProvider();

    4         cdp.GenerateCodeFromCompileUnit(code, sw, null);

    5         Response.Write(sw.ToString().Replace("\n", "<br \\>"));

 
The generated code will look something like this. . .

    1 //------------------------------------------------------------------------------

    2 //

    3 // This code was generated by a tool.

    4 // Runtime Version:2.0.50727.1433

    5 //

    6 // Changes to this file may cause incorrect behavior and will be lost if

    7 // the code is regenerated.

    8 //

    9 //------------------------------------------------------------------------------

   10 

   11 namespace GeneratedNamespace

   12 {

   13     public class GeneratedClass

   14     {

   15         public static int Add(int value1, int value2)

   16         {

   17             return (value1 + value2);

   18         }

   19     }

   20 }

Step 2: Compile it
Now that you have your code (in a string or in the CodeDom) you can request that .NET compile it for you. First you need to determine what language you want to compile it using. I am going to use C# but you can easily change it out for VB, etc.

    1         //Step 2: Compile the Code

    2         CompilerParameters cp = new CompilerParameters();

    3         cp.GenerateExecutable = false;

    4         cp.GenerateInMemory = true;

    5         cp.ReferencedAssemblies.Add("System.dll");

    6         CompilerResults results = cdp.CompileAssemblyFromDom(cp, code);

    7         Assembly assembly = results.CompiledAssembly;

Step 3: Run it
Now it is just a matter of using reflection to take the assembly that we generated and invoke its method.

    1         //Step 3: Run it using reflection

    2         Type t = assembly.GetType("GeneratedNamespace.GeneratedClass");

    3         object[] parms = { 5, 5 };

    4         Response.Write(t.GetMethod("Add").Invoke(null, parms));

So while this was an academic exercise to prove that it can be done, it does have real implications for real applications, but I will leave that to your imagination.

Ideas borrowed from:
Dino Esposito - http://weblogs.asp.net/despos/
CodeDom Calculator - http://channel9.msdn.com/ShowPost.aspx?PostID=360076
GotDotNet - http://samples.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/howto/samples/CompMod/CodeDom/ListBuilder/listbuilder.src&file=CS\listbuilder.cs&font=3

Posted by sweisfeld | with no comments
Filed under: ,

Unable to connect to the remote server

When attempting to call a webservice that lives outside my corperate firewall I was getting the following error:

System.Net.WebException was unhandled by user code
  Message="Unable to connect to the remote server"
  Source="System"
  StackTrace:
       at System.Net.HttpWebRequest.GetRequestStream()
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)

After some research I stumbled across this post by Rick Strahl
http://west-wind.com/weblog/posts/3871.aspx

but my problem was a little bit different. In his case he desired to disable to the automatic proxy detection, but I needed to wire in the script that my corperate IT department requires that we use. Easy enough just add the following to the web.config

 <system.net>
  <defaultProxy>
   <proxy scriptLocation ="url to script here" />
  </defaultProxy>
 </system.net>

I think the cause of my problem was the same as Ricks. Everything works fine when using a console application running as me, but when I put the same method call in a web app runing as network service it appears that he doesnt have enough permissions to get the script location from the registry.

Posted by sweisfeld | with no comments
Filed under: , ,