Wednesday, October 05, 2016

C# Updated on Threading with .net 4

With .NET 4 we now have better ways of handling threads. So in this post I'm going to demonstrate several ways of creating and waiting for threads to finish.

First example is creating 10 threads with the new Task.Factory.StartNew() method then we call Task.WaitAll and the framework handles the rest. This call will however block until all the tasks are finished.

 // Wait for all tasks to complete.  
       Task[] tasks = new Task[10];  
       for (int i = 0; i < 10; i++)  
         tasks[i] = Task.Factory.StartNew(() => DoSomeWork(10000000));  

The second way allows us to no block.

 var task1 = DoWorkAsync();  
 var task2 = DoMoreWorkAsync();  
 await Task.WhenAll(task1, task2);  

Monday, October 03, 2016

C# parse invalid XML characters

I've been dealing with XML a bit lately and have found that when you don't control the data you get all sorts of weird stuff. XML 1.0 doesn't allow certain characters or the XML is invalid. I tested a variety of ways using streams and string builders but I found a bit of LINQ and using a .NET function and in two lines you get a string of XML that only has valid characters.

 var validXmlChars = val.Where( ch => XmlConvert.IsXmlChar( ch ) ).ToArray();  
 return new string( validXmlChars );  

Tuesday, August 16, 2016

using jqGrid in an MVC View

Since MVC has gotten so popular and for a good damn reason we've lost the venerable WebForms grids. However a great replacement is the jqGrid an extension of the jQuery UI. However it does take some setup in your View and I personally find their documentation horrendous. Below is a very basic jqGrid and thanks to Bloggers shitty HTML parsing I can't show the HTML very well but you need an empty table with the id that matches what's in the grid and a div that's used for the pager.

You'll notice these items have to match and the div MUST be below the table for the display to work correctly. I'm using an MVC controller to get the data for the grid back. Now this won't let you add, delete, edit, etc because that gets a lot more complicated. For me this is a pretty basic grid. You need to specify a url to get data, I almost always use json as my datatype, and a GET to the server. Whatever data your return needs to be in a JSON format that matches the format in the jsonReader section of the grid. See another post of mine on how to return that from an MVC controller.  You will need to set your columns of course to your needs.

There are a lot more options if you try and read the jqGrid docs.

jqGrid Home Page

table class="container" id="usersGrid"
div id="usersGridPager"

 $(document).ready(function () {  
       url: "@Url.Action( "Get", "Users" )",  
       datatype: "json",  
       mtype: 'GET',  
       colNames: ['Id','Username', 'Name', 'Email Address', 'Created On'],  
       colModel: [  
              { name: 'Id', index: 'Id' },  
              { name: 'Username', index: 'Username' },  
              { name: 'Name', index: 'Name' },  
              { name: 'EmailAddress', index: 'EmailAddress' },  
              { name: 'Created', index: 'Created'}],  
       pager: "#usersGridPager",  
       viewrecords: true,  
       autowidth: true,  
       multiselect: false,  
       height: '100%',  
       width: '100%',  
       rowNum: 20,  
       caption: 'Users',  
       emptyrecords: 'No Users',  
       rowList: [10, 20, 30, 40, 50],  
       altRows: true,  
       loadonce: false,  
       loadtext: "Loading Users...",  
       jsonReader: {  
         root: "rows",  
         page: "page",  
         total: "total",  
         records: "records",  
         repeatitems: false,  
         Id: "0"  

jqGrid get data from MVC Controller

So ever since MVC for started becoming all the rage, and for good reason! Many people have bemoaned the loss of the venerable DataGrid from WebForms. Well there are a few options out there. You have Teleriks Kendo UI suite which is great but costs money. There are a few other options but the best jqGrid a jQuery plugin.

Now this grid can be a bit tricky to use. I personally find the documentation a bit short to put it politely. I've done enough grids now I'm getting the hang of it and want to share some pointers for other MVC developers out there. Now let's assume in your View you have a nice jqGrid pointed to a controller action (I'll make another post about this as well). jqGrids are very powerful and support paging, grouping, filtering, sorting, etc. Now the bad part is you have to handle all that in your controller. This controller action will show you have to sort, page, and generally retrieve data.

Now for the jqGrid to work correctly it needs to have a very unique signature.

We need 4 parameters, these names must BE AS SHOWN, if not you won't get the values to fully sort, etc.

sidx -  Sorting index, the column name being sorted

sord - Sorting direction this will DESC or ASC

page - The page number the grid is on

rows - The number of items per page

 public ActionResult Get( string sidx, string sord, int page, int rows )  
       // check if we have a sort, null means nothing  
       sord= ( sord== null ) ? "" : sord;  

       // get the page index into an int (which page we're on)  
       int pageIndex = Convert.ToInt32( page ) - 1; 
       // get the number of items per page  
       int pageSize = rows;  

       // get some data from an Entity Framework source  
       // you can get it from anywhere  
       var users = _db.Users.Select(  
         user => new UsersGridModel  
           Id = user.Id,  
           Username = user.UserName,  
           EmailAddress = user.EmailAddress,  
           Name = user.FirstName + " " + user.LastName,  
           Created = user.Created  
         } );  

       // get the total count of records to displau  
       int totalRecords = users.Count();  
       // get the total number of pages to display  
       var totalPages = (int)Math.Ceiling( (float)totalRecords / (float)rows );  

       // check which direction if any we're sorting  
       if( sord.ToUpper() == "DESC" )  
         // you need to look at the sidx (sorting index) this will be a column name  
         // use the correct item in your source to sort the column correctly  
         users = users.OrderByDescending( t => t.Id );  
         users = users.Skip( pageIndex * pageSize ).Take( pageSize );  
         // you need to look at the sidx (sorting index) this will be a column name  
         // use the correct item in your source to sort the column correctly  
         users = users.OrderBy( t => t.Id );  
         users = users.Skip( pageIndex * pageSize ).Take( pageSize );  

       // we need to send back JSON in a very specific format  
       var jsonData = new  
         total = totalPages,  
         records = totalRecords,  
         rows = users  

       // send it back, the AllowGet isn't required since MVC 4 or 5 but it's good practice  
       return Json( jsonData, JsonRequestBehavior.AllowGet );  


Now if you have a lot of columns that sorting section can get hairy, I would move it into another function. In fact you could modularize this and try and make it pretty generic but this is a one off example. But this is a basic way to get data to a jqGrid from an MVC Controller.

Wednesday, May 04, 2016

Kendo UI grid update row using Javascript/jQuery

I've been working on a project that utilizes the Telerik Kendo UI grid. I've found that I have a need to change the values in the current row using client side tech (Javascript/jQuery). It's actually pretty easy to do. You get the grid, then the model bound to the grid and change the values on the model. This will refresh the values in the grid on the client side. You can save these new values in the Update controller action you define in the grid.

 // get the grid and model used to bind against the grid  
 var grid = $("#AdminFalloutMappingGrid").data("kendoGrid"),  
    model = grid.dataItem(this.element.closest("tr"));  
 // get a value from the model, using the property name on the model  
 var something = model.get("PropertyName");  
  // update the model using the Property Name  
 model.set("PropertyName", "value");  

Thursday, March 24, 2016 MVC dynamically create and return image from Controller

I've found that I have a need to create an image dynamically (or read from a file) and return it directly from a controller. We can do that pretty easily.

First add this method to a controller:
public class ImageController : Controller
     public void Generate()  
         //when we create a pixel we need to make it a random color  
         Random randomGen = new Random();  
         Bitmap image = new Bitmap( width, height );  
         // create the graphics drawing tool  
         using ( Graphics gfx = Graphics.FromImage( image ) )  
         // create a solid brush to draw the image, I'm using random colors  
         using ( SolidBrush brush = new SolidBrush( Color.FromArgb( randomGen.Next( 255 ), 
                                                    randomGen.Next( 255 ),
                                                    randomGen.Next( 255 ) ) ) )  
           gfx.FillRectangle( brush, 0, 0, width, height );  

         // save the image to a memory stream  
         MemoryStream ms = new MemoryStream();  
         pixel.Image.Save( ms, ImageFormat.Jpeg );  
         ms.Position = 0;  

         // send the image back  
         return new FileStreamResult( ms, "image/jpeg" );  

       catch(Exception ex)  
         Console.WriteLine( ex.ToString() );  

Now you in an image tag set the src property to your controllers action as follows:

  img src="@Url.Content("~/ImageController/Generate")" 

Tuesday, March 15, 2016 MVC Ajax.BeginForm with busy icon

So I've been exploring the world of MVC and found it's pretty easy to do a postback to a controller and do it with AJAX and show a busy icon and keep the user from pressing the submit button. This is MVC 5 with the Razor rendering engine. Below is the entire section:

<div id="divSendEmail">
        @using ( Ajax.BeginForm( "SendEmail", "Contact",
            new AjaxOptions { UpdateTargetId = "result", LoadingElementId = "loading", OnBegin= "sendEmailLoad()", OnComplete= "completeSendEmailLoad()" } ) )
            <div id="loading" style="display: none; position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; width: 100px; height: 100px;">
                <img src="~/Content/images/gears_animated.gif" />
                Name: <input type="text" class="form-control" id="textName" name="textName" required="required" maxlength="255"><br>
                Email: <input type="email" class="form-control" id="textEmail" name="textEmail" required="required" maxlength="255"><br>
                Message: <textarea class="form-control" rows="5" id="textMessage" name="textMessage" required="required"></textarea><br>
                <input type="submit" id="buttonSubmit" name="buttonSubmit" value="Send Email" class="btn btn-primary" />
            <div id="result" class="container">
        function sendEmailLoad() {
            document.getElementById("buttonSubmit").disabled = true;
            return false;

        function completeSendEmailLoad() {
            document.getElementById("buttonSubmit").disabled = false;
            return true;

First is the AjaxBeginForm. We pass the Action, Controller, and AjaxOptions we want to use. The LoadingElementId is a div we have defined that contains an image that is centered in the middle of the screen with an animated gif that is set to not display. The OnBegin is a javascript function that disables the submit button to prevent multiple postbacks. The OnComplete is a javascript function that enables the submit button once the AJAX call is done.

Sunday, February 28, 2016

MFC getting the current date and time

I've been updating some older MFC/C++ applications and I found I needed to get the current system time. There's a way in the Win32 API but it's clunky. MFC gives you a simple way.

CTime t = CTime::GetCurrentTime();
CString s = t.Format("%m%d%Y");
The Format method can take a wide variety of parameters.
See this MSDN link

Sunday, February 14, 2016

ASP.NET dynamically load AJAX toolkit accordion panes

I love the Accordion pane from the AJAX toolkit, but I've found myself needing to dynamically add accordion panes to it. To do this you need to some work on the back end. The following code loops through a DataSet and dynamically creates a Label control for the header and content. It then adds those controls to a new AccordionPane and then add it to your Accordion.

 for ( var i = 0; i < ds.Tables[10].Rows.Count; i++ )  
           Label lblContent = new Label();  
           lblContent.ID = Guid.NewGuid().ToString();  
           Label lblTitle = new Label();  
           lblTitle.ID = Guid.NewGuid().ToString();  
           lblTitle.Text = ds.Tables[2].Rows[i + 1][1].ToString();  
           lblContent.Text = ds.Tables[10].Rows[i][1].ToString();  
           AjaxControlToolkit.AccordionPane pane = new AjaxControlToolkit.AccordionPane();  
           pane.ID = Guid.NewGuid().ToString();  
           pane.HeaderContainer.Controls.Add( lblTitle );  
           pane.ContentContainer.Controls.Add( lblContent );  
           this.Accordion1.Panes.Add( pane );  

Wednesday, November 25, 2015

C# Read File one line at a time

This might seem simple, but often times you find yourself needing to read a file one line at a time no matter what language you do it in. C# makes this very easy with a StreamReader. You simply create the stream reader passing in the file name to the constructor and then call ReadLine on it. See the code below:

string line = null;

// always use a using with  a stream, this ensures it gets disposed of properly
 using(StreamReader sr = new StreamReader(fileName))
    // we use a while loop until line == null which means end of file
     while( (line = sr.ReadLine() ) != null )
           // Do something here                       

Wednesday, August 21, 2013

Three simple tricks for better C# code

Here are 3 tricks that once you start using them can save you a lot of typing when dealing with C#.

1. The Null Coalescing Operator (??) This is a short-cut for the ternary operator (?:) checking against a null:
string name = value;  
   if (value == null)  
     name = string.Empty;  
Can now be condensed into one line:
 string name = value ?? string.Empty;  
2. Auto properties There is no need to define a variable for simple backing fields for most properties in C#. In fact most things like int, strings, double i just let the compiler handle it.
 public class MyPoint  
    public int X { get; set; }  
    public int Y { get; set; }  
3. Is vs As You should try and avoid the is operator when you can do an as cast. The is requires two casts where the as does just one. Even with the added null check it's always going to be faster to do an as vs is.
 var sq = Square as Shape;  
   if ( sq != null )  
     volume = sq.CalculateVolume();  
     // ...  

Thursday, March 28, 2013

ASP.NET User Control with Template Content user controls are great.  I use them all the time when working on .net websites.  I was working on a site using the ajax extender toolkit.  I created a panel that could be expanded collapsed with a button click.  I inserted a few into the site and liked them so much I made some more.  Well after the 7th panel it started getting tedious.  What a perfect place for a user control.  The problem was I needed to be able to place whatever custom content I wanted inside the panel.  After much searching around I wasn't finding what I wanted.  The answer it turns out is an user control with custom templates.

Create a new user control for your site.  Mine is called CollapsiblePanel.  In the code behind for the page you need to add a new class MessageContainer that inherits from Control and implements the INamingContainer Interface.   Then in the user controls OnInit method you need to check for content and add it to your user control.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test.UserControls
    // this is a message container, it contins the data we want to display
    // as well as the index of the container
    public class MessageContainer : Control, INamingContainer
        private int index;
        internal MessageContainer(int index) { this.index = index; }
        public int Index { get { return index; } }

   // this is the user control I have created
   //its an ajax extended collapsible panel with some custom content
    public partial class CollapsiblePanel : System.Web.UI.UserControl, INamingContainer
        private ITemplate _contentTemplate = null;

        public ITemplate Content
            get { return _contentTemplate; }
            set { _contentTemplate = value; }
        protected override void OnInit(EventArgs e)

            // if we have a content template in the markup then add it to our container
            if (_contentTemplate != null)
                MessageContainer container = new MessageContainer(0);

Now to use our new user control in an aspx page with some content.

<uc:CollapsiblePanel runat="server" ID="CollapsiblePanel1">
          CONTENT GOES HERE,You can drop anything, controls, etc.            

C++ convert char * to to wide string wstring

Often times when working with older code you find yourself staring at some old char* variables. I often find myself having to convert them to wide strings for unicode support (wstring). I created a handy function that makes this simple.
wstring charToWideString( const char* src )
    return std::wstring( src, src + strlen(src) );
Now simply call thus:
wstring thus = charToWideString( "thus" );
Drop this function in a static class or header file and use it anywhere.

Thursday, March 14, 2013

ASP.NET Create Javascript Alert on Server Side

Many times in you find yourself needing to create an alert on the client side but you're processing on the server side. The trick is to register a Javascript to the client from the server. I have found a nifty way of creating a class that will allow you to do this.

public static class ClientMessageBox

    public static void Show(string message, Control owner)
        Page page = (owner as Page) ?? owner.Page;

        if (page == null)

            "ShowMessage", string.Format("<script type="text/javascript">;alert('{0}')</script>",



// Example of using class and method
protected void Page_Load(object sender, EventArgs e)
    ClientMessageBox.Show("Hello World", this);

You can now call ClientMessageBox.Show('text', this ); anywhere server side and get a nice javascript alert. Now of course there are AJAX control toolkits and other things that do this for you but this is a bare bones pure C# solution.

Friday, January 25, 2013

C# Numeric Only TextBox

Once in a while you find yourself needing to stop certain keypresses in a C# desktop application.  I've found the best way is to handle this in the keypress event of a text box.  This is some very small code that shows how to only allow numeric digits to be pressed.

private void textBox_KeyPress( object sender, KeyPressEventArgs e )
     e.Handled = !char.IsDigit( e.KeyChar );

Now if you want to allow other characters, like the decimal, etc you need to get a bit fancier.

private void textBox_KeyPress( object sender, KeyPressEventArgs e )
       if( char.IsDigit( e.KeyChar ) || 
           e.KeyChar == '.' )
          e.Handled = false;
          e.Handled = true;

To allow more characters you just need to modify that first if parameter to your needs.

Friday, November 30, 2012

C# Form Application in Kiosk Mode/Fullscreen

Sometimes you need to have a C# windows form application run in full screen mode.  Like you see on a kiosk at a mall or some stand alone machine.  It's fairly easy you just need to set some of the properties on the Form either in it's OnLoad method or directly in the designer.

In the OnLoad method of the main Form set these values, or again set them directly in the designer.

this.MaximizeBox = false;
this.TopMost = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;