Posts

C# Producer Consumer using Rabbit MQ

So I've been learning about the different message queuing systems and discovered rabbit MQ, an open source and very popular message queuing system. I've created a very basic producer/consumer system that sends a message to a rabbit MQ queue. Producer/Consumer is pretty simple, you have two systems a producer that writes to a queue and a consumer that reads from a queue. This is desirable because it splits responsibility and allows for scalability. The code below is going to assume you have a rabbit MQ instance installed on your local machine. You can get rabbit MQ here:  https://www.rabbitmq.com/ Now the code is broken down into 3 parts, the main program, the producer, and the consumer. This is a basic example so its using old school threading rather than the new async/await .net prefers. But this is just to show how to use rabbit MQ in C# and to demonstrate a producer/consumer example. You will need to make sure your project has the rabbit MQ client nuget package installed...

C# DateTime Formatting

C# Offers a wide variety of formatting date times using the ToString method. Below you will see the various options you can use and the results. Format Result DateTime.Now.ToString("MM/dd/yyyy") 05/29/2015 DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50 DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50 AM DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50 DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50 AM DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss") Friday, 29 May 2015 05:50:06 DateTime.Now.ToString("MM/dd/yyyy HH:mm") 05/29/2015 05:50 DateTime.Now.ToString("MM/dd/yyyy hh:mm tt") 05/29/2015 05:50 AM DateTime.Now.ToString("MM/dd/yyyy H:mm") 05/29/2015 5:50 DateTime.Now.ToString("MM/dd/yyyy h:mm tt") 05/29/2015 5:5...

C# Getting your IP address

Sometimes you need to know your ip address in code. With the following snippet you can! var hostName= new HostInformation(); var address = Dns.GetHostEntry(hostName).AddressList[0].ToString();

Old School C++ guess the number game

It's been a while since I blogged but I've got some old fashioned code I've updated using the latest versions. This is some C++ code for a simple guessing game. You get 10 tries to guess a number between 1 and 100. The game picks the number randomly and tells you if you've guessed to low, to high, or correctly. This is written using the newer C++ 11 standard so you'll notice some weird stuff with the random number generating. I will post some links to this below. #include <iostream> #include <random> using namespace std; int main() { random_device randomDevice; mt19937 mt(randomDevice()); uniform_real_distribution<double> dist(1.0, 100.0); int numberOfTries = 0; int numberToGuess = dist(mt); int maxNumberOfTries = 10; int currentGuess = 0; bool wonGame = false; cout << "Welcome to guess the number" << endl << endl...

Raspberry PI 3+ python blinking LED

I've recently been getting into the raspberry PI world. I have a model 3+ that one of my first projects was to get an LED to blink. The following below will make an LED blink for a random amount of time for a random amount of times. import RPi.GPIO as GPIO import time import random from random import * # set the output mode of the GPIO pins GPIO.setmode(GPIO.BCM) # don't show warnings in the console GPIO.setwarnings(False) # this sets the output to pin 18 (positive) GPIO.setup(18,GPIO.OUT) # we randomly pick some numbers numberOfBlinks = randint(10,30) blinkLength = randint(1,5) print(numberOfBlinks,blinkLength) print("LEDs on") counter = 0 # loop through and turn the LED on and off while counter <= numberOfBlinks: # set the output to high (ON) GPIO.output(18,GPIO.HIGH) # wait for X seconds time.sleep(blinkLength) # set the output to low (OFF) GPIO.output(18,GPIO.LOW) counter = ...

WPF create a grid splitter

You will often find yourself needing to have two panels on a screen with a slider between them. WPF gives you a nice way to handle this with the GridSplitter control. You will need to create a column for the actual splitter and it will use the width you give it in the column definition. <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="5" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock FontSize="55" HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap">Left side</TextBlock> <GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" /> <TextBlock Grid.Column="2" FontSize="55" HorizontalAlignment="Center" VerticalAlignment="Center" Te...

WPF Bind a combobox to an enumeration

I've often found myself needing to bind a combo box to an enumeration I've created. You can do this in WPF but it's a bit complicated. You end up needing to create a static resource. I had mine in a user control. First the enumeration I was using: namespace XmlCoderBI.Enums { /// <summary> /// An enumeration that represents the type of conversion we're doing /// </summary> public enum ConversionType { /// <summary> /// The binary /// </summary> [Description( "Binary" )] Binary = 0, /// <summary> /// The base64 /// </summary> [Description( "Binary" )] Base64 = 1, /// <summary> /// The hexadecimal /// </summary> [Description( "Hexadecimal" )] Hexadecimal = 2, /// <summary> /// The UTF-8 /// </summary> [Description( ...

C# async and await

The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods. The following example shows an async method. Almost everything in the code should look completely familiar to you. The comments call out the features that you add to create the asynchrony. // Three things to note in the signature: // - The method has an async modifier. // - The return type is Task or Task<T>. (See "Return Types" section.) // Here, it is Task<int> because the return statement returns an integer. // - The method name ends in "Async." async AccessTheWebAsync() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new H...

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)); } Task.WaitAll(tasks); The second way allows us to no block. var task1 = DoWorkAsync(); var task2 = DoMoreWorkAsync(); await Task.WhenAll(task1, task2);

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

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

jqGrid get data from MVC Controller

So ever since MVC for asp.net 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 ASP.net 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 ...

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");

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() { try { //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 ); ...

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" /> </div> <fieldset> Name: <input type="text" class="form-...

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

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

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 } }

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.Calcul...

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 cont...