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 id="usersGrid" class="scroll container"
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"  

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

ASP.net 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

ASP.net 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

Asp.net user controls are great.  I use them all the time when working on .net websites.  I was working on a site using the asp.net 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 asp.net user control with custom templates.

Create a new user control for your asp.net 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, asp.net 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 ASP.net 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;

Wednesday, November 14, 2012

C# String Performance

In C# I have read a lot of debate over which way is the best way to do String Concatenation.  I have often read never ever use String1 + String2 due to the memory allocations and time constraints.  I decided to run some tests on the various way of doing String manipulation.  The table below shows the iterations, total times, and average times for some common way of doing string addition.  This was just a test of time, there was no memory consumption test.  All tests were doing adding 7 strings together that were stored in variable names.  There was no string a = "a" + "b";  It was all string a  = var1 + var2;  These were creating a single string for the listed iterations using the method(s) below.

I was surprised to see the + method came out ahead in all the tests.  String builder came in a close second.  String.Format was extremely slow but allows for localization which is another story.

iterations String + average String.Concat average String.Format average StringBuilder average
100 0 0 0 0 0 0 0 0
1000 0 0 0 0 1 0.001 0 0
10000 4 0.0004 7 0.0007 21 0.0021 4 0.0004
100000 38 0.00038 82 0.00082 69 0.00069 44 0.00044
1000000 272 0.000272 525 0.000525 784 0.000784 306 0.0003067
10000000 2569 0.0002569 5133 0.0005133 6245 0.0006245 2917 0.0002917

Sunday, July 29, 2012

C# Use a stored procedure to fill a dataset/table

When you fill a DataSet/Table in C# you use a SQL Data Adapter. The code for this is geared towards a SQL SELECT statement. However I'm not a big fan of raw SQL in my code so I found a way to use a stored procedure instead.

 public static DataTable GetTable()  
       DataTable dt = null;  
         using( SqlConnection connection = new SqlConnection( "your connection string" ) )  
           using( SqlDataAdapter sda = new SqlDataAdapter() )  
             using( SqlCommand command = new SqlCommand( "your stored procedure", connection ) )  
               command.CommandType = CommandType.StoredProcedure;
               // this line needs to be added for every parameter the SP expects
               command.Parameters.AddWithValue( "parametere value", paramValue ); 
               sda.SelectCommand = command;  
               dt = new DataTable();  
               sda.Fill( dt );  
       catch( Exception ex )  
         Debug.WriteLine( ex.ToString() );  
       return dt;  

C# execute a stored procedure using SQL Server

Below we have some code that opens a connection to a database using a connection string then executes a stored procedure. This obviously needs to be placed in some method or class. You will need to add your own connection string and parameter values.
         using( SqlConnection connection = new SqlConnection("some connection string" ) )  
           using( SqlCommand command = new SqlCommand( "stored procedure name", connection ) )  
             command.CommandType = CommandType.StoredProcedure;  
             // this line needs to be added for every parameter the SP expects
             command.Parameters.AddWithValue( "parametere value", paramValue );    

             // based on the what the SP does, call the execute non query, execute scalar, or execute reader method

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