Archive for the ‘C#’ Category

Upload to ASP.NET from HTML, Flash, or Flex clients

File uploading has been a hot topic during my time as an internet programmer.  In the classic ASP days this was a bit of a task to build and get correct.  Nowadays both Adobe’s Coldfusion and Microsoft’s ASP.NET both have built in file uploader tags ( server controls ) that handle this with ease.

This is great, but what happens when you have a mixed bag of clients that all need to upload to the same location?  Sometimes I work with completely ASP.NET or CF web apps, but more often than not I’m dealing with Flash clients as well as HTML clients.

Recently I ran into this upload scenario and built this simple ASP.NET uploader script.  This feels a bit old school since it uses .NET’s built in Request.Files collection, instead of a fancy new ‘all in one’ server control, but I actually prefer this method.

Here’s all you need :

    // Check for posted files
    for (int xx = 0; xx < Request.Files.Count; xx++)
    {
        // UPLOAD FILE
        HttpPostedFile _file = Request.Files[xx];

        // create full save path for uploaded file
        var full_file_path = Server.MapPath( UP_FOLDER ) + "\\" + _file.FileName;

        try
        {
            // save file to server
            _file.SaveAs(full_file_path);
        }
        catch (Exception exc)
        {
            var emsg = "Unable to upload file : " + exc.Message;

            Response.Write( emsg );
            Response.Flush();
            Response.End();
        }

        // show result
        Response.Write( _file.FileName + " uploaded! <br>" );
    }

That’s all there is to it codewise. Before using this code you will need to give the NETWORK SERVICES user write permissions to your upload folder. Other than that, that’s all she wrote!

Here is a zip of all the code for you to download.

Inside this zip you will find :

  • flashclient.fla – Flash upload client ( *be sure to update the upload path before building )
  • flexclient.mxml – Flex upload client ( *also update upload path before building )
  • uploader.aspx - ASP.NET file upload handler
  • uploadform.html - sample HTML upload form ( again, update path )

Hope somebody finds this useful.

How to show line numbers in Visual Studio 2010

I’ve been using Visual Studio since forever, yet it always takes me a while to remember how to show line numbers.  It’s especially hard to remember after a fresh install of Visual Studio.  Assuming you have it installed and open, here’s how to display line numbers in your code.

  1. Click Tools in the menu bar
  2. Options
  3. Expand Text Editor ( in the popup window )
  4. Click ‘All Languages’
  5. Check the ‘Line numbers’ box under the Display heading ( on the right )
  6. Click OK
  7. Happy Happy Joy Joy!

How to Display Line numbers in Visual Studio 2010

DataBind a List of custom classes to an ASP:ListBox control

Recently I was scratching my head at this error from the .NET Framework

DataBinding: ‘MyApp.vo.customVO’ does not contain a property with the name ‘Name’

I was stumped because my custom VO class did in fact have a public property called Name.  After many trials and tribulations I figured out that .NET didn’t like how I structured my custom class.

Here is what my original custom class looked like.

namespace MyApp.vo
{
    public class customVO
    {
        public Int32 id  = 0;
        public DateTime time  = new DateTime();
        public string Name  = string.Empty;
        public string DeviceType  = string.Empty;
        public string ObjectIDs  = string.Empty;
    }
}

Luckily I have JetBrains ReSharper installed, and it suggested using C#’s Auto-Implemented properties. This is the one thing I hadn’t thought about trying, and it ended up being the fix! My new custom VO class now looks like this.

namespace MyApp.vo
{
    public class customVO
    {
        public Int32 id { get; set; }
        public DateTime time { get; set; }
        public string DeviceType { get; set; }
        public string ObjectIDs { get; set; }
        public string Name { get; set; }
    }
}

So if you find yourself running into this error while trying to DataBind a collection of custom classes to a ListBox or similar control, have a look at your custom class and see if you can convert it over to using auto-implement properties as well.

Now I’m not suggesting this is the only way to DataBind a List of custom classes to a ListBox, but it solved my problem and let me do direct databinding from my service call without having to do any pre-processing on my list.

Hope this helps someone else.

How to TWEET from a SQL CLR Stored Procedure

Here’s another SQL Server 2005 geek out moment, a CLR SPROC that tweets to Twitter. Big shoutout to Danny Battison for sharing the C# code to post to Twitter. This is what got me started on the C# side of things.  Also, you can skip all my ramblings here and just download code here and fire it up.  The zip file contains all the source code, the compiled assembly file, and install.sql that shows you how to hook this up.

Being the SQL junky that I am, I was interested in trying out SQL Server’s new CLR Stored Procedures. A CLR sproc is a stored procedure that is able to use .net code that you’ve compiled into an assembly file. For you classic ASP heads out there, think of the ASP page being the sproc, and the .net assembly being your COM object ( cringe, let’s talk about classic ASP ). While there are plenty of great articles on writing CLR stored procedures, I’m going to breeze through the code that makes up this project.

First make a .net class library that will be compiled into an assembly file.

using System;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// This assembly will be used by a SQL2005 SPROC to communicate
/// with twitter.com
/// </summary>
public sealed class tweetsproc
{
    /*
     * TWITTER CODE BORROWED FROM :
     *  http://www.dreamincode.net/code/snippet2556.htm
     *
     * A function to post an update to Twitter programmatically
     * Author: Danny Battison
     * Contact: gabehabe@hotmail.com
     */

    /// <summary>
    /// Post an update to a Twitter acount
    /// </summary>
    /// <param name="username">The username of the account</param>
    /// <param name="password">The password of the account</param>
    /// <param name="tweet">The status to post</param>
    [Microsoft.SqlServer.Server.SqlProcedure(Name = "PostTweet")]
    //public static void PostTweet( string username, string password, string tweet)
    public static void PostTweet(   SqlString username,
                                    SqlString password,
                                    SqlString tweet)
    {
        try
        {
            // encode the username/password
            string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username.ToString() + ":" + password.ToString()));
            // determine what we want to upload as a status
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet.ToString());

            // Create a WebPermission.
            WebPermission myWebPermission1 = new WebPermission();

            // Allow Connect access to the specified URLs.
            myWebPermission1.AddPermission(NetworkAccess.Connect,new Regex("http://www\\.twitter\\.com/.*",
              RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline));

            myWebPermission1.Demand();

            // connect with the update page
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");

            // set the method to POST
            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
            // set the authorisation levels
            request.Headers.Add("Authorization", "Basic " + user);
            request.ContentType = "application/x-www-form-urlencoded";
            // set the length of the content
            request.ContentLength = bytes.Length;

            // set up the stream
            Stream reqStream = request.GetRequestStream();
            // write to the stream
            reqStream.Write(bytes, 0, bytes.Length);
            // close the stream
            reqStream.Close();

            // Let's get the Response from Twitter
            var webresp = request.GetResponse();
            // Let's read the Response
            var sread = new StreamReader( webresp.GetResponseStream() );

            // Use SqlContext to return data to the QueryAnalyzer results window
            SqlContext.Pipe.Send( sread.ReadToEnd() );

        }
        catch (Exception exc)
        {
            // send error back
            SqlContext.Pipe.Send(exc.Message);
        }
    }
}

Here’s the app.config for this assembly.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <trust level="Full" processRequestInApplicationTrust="true" originUrl="" />
  </system.web>
</configuration>

Once you build this project, you should have your assembly ( tweetsproc.dll ) which will be used by your CLR Sproc. Now it’s time to do some SQL server work.

Enable CLR access for SQL server

EXEC sp_configure @configname = 'clr enabled', @configvalue = 1
RECONFIGURE WITH OVERRIDE
GO

Create the SQL Assembly

CREATE ASSEMBLY tweetsproc_clr_assembly from 'C:\Users\eric\Desktop\blog\tweetsproc.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO

Create your SPROC

CREATE PROC tweetsproc_tweet(	@username as nvarchar(50),
								@password as nvarchar(50),
								@tweet as nvarchar(140)
							)
AS
	-- [Assembly Name].[Class Name].[CLR function Name]
	EXTERNAL NAME tweetsproc_clr_assembly.tweetsproc.PostTweet
GO

Tweet from a sproc

EXEC tweetsproc_tweet 'TwitterUsername', 'TwitterPassword', 'Hey @ericfickes, I''m tweeting from my database too!'

Running this sproc returns the XML response from Twitter.

Twitter response from tweet sproc

Tweetsproc returns the full Twitter response

That’s one sample CLR SPROC in the bank!  Feel free to download this code and try it out yourself.  I’d love to get some feedback on anybody looking to use this for real.  While tweeting from a stored procedure probably isn’t a hot topic for anybody, this is a nice teaser for what you can do with CLR sprocs now.

Download code here.

Inside this zip you’ll find this.

  • install.sql is everything you need to install this on your database
  • tweetsproc.dll is the twitter assembly used by the sproc
  • tweetsproc folder is the .net class library project
Contents of tweetsproc.zip

Everything you need to get TWEETING from a sproc