David Sandor

Build succeeded.

Resize Images in a batch in C#/WPF with an MVVM application.

clock January 21, 2012 19:11 by author dsandor

I am working on a project where I need to resize a bunch of raster images from miscellaneous sizes to fit within a certain frame.  More specifically, I need a bunch of icons for an iPhone application and I need them to fit within a 64px by 64px frame.  I found a bunch of Photo Shop scripts, some console apps, and a few spamware solutions.  I figured half an hour and I would have one that works well.  I was right.

image

So here is how the app works:

Drag and drop the graphics files you wish to resize into the application.  The files will show in the list view area.  Next, enter the Max Height and Max Width values and then click the Resize button.

The application will write the resized file next to your original with _MaxHeightxMaxWidth appended to the filename.  Original files are not modified in any way during this process. 

So if you found this blog post in hopes that you would find a quick and simple image resizer for free, here is the link to the binaries: 

A little about the application source code.  The application is a .NET 4.0 WPF application that follows the M-V-VM (MVVM) design pattern.  Since there is drag and drop support in the application there is a little code behind to support this.  The rest of the application follow the MVVM pattern.

There is a tiny image resizer class in the project that you are free to use.  This is located in the DevSQL.Imaging assembly. 

The source code can be found below.



Align your code in Visual Studio 2010

clock January 21, 2012 16:47 by author dsandor

I love this Visual Studio Extension.  Wanted to keep it in the blog so I do not forget.  Chris also wrote a notepad++ plug-in for the same thing.  Kudos.

http://visualstudiogallery.msdn.microsoft.com/7179e851-a263-44b7-a177-1d31e33c84fd

Align by... (Dialog) Ctrl + Shift + =
Align by position... (Dialog) Ctrl + =, Ctrl + backspace
Align by Equals Ctrl + =, Ctrl + =
Align by m_ Ctrl + =, Ctrl + m
Align by " Ctrl + =, Ctrl + '
Align by . Ctrl + =, Ctrl + .
Align by Space Ctrl + =, Ctrl + Space



Netduino: Day 1.1 - Thermistor / Thermometer

clock August 2, 2011 20:07 by author dsandor

So the Variable Resistor (POT) was cool and really easy.  So there is another sensor in the box which should work pretty much the same way.  The thermometer also has a red, black, and white wire so this tells me it works the same way.  Analog circuit based thermometers are called thermistors which mean they are variable resistors that change the impedance based on a temperature.  So my code should look the same as my Day 1's blog entry.

I added a debug statement to output the actual thermometer value.  I quickly noticed that my room temperature reading was a 422 or 424.

public static void Main()
{
    OutputPort led = 
new OutputPort(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.ONBOARD_LED, false); AnalogInput variableResistor =
new AnalogInput(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0); while (true) { led.Write(!led.Read()); Thread.Sleep(variableResistor.Read()); Debug.Print(variableResistor.Read().ToString()); } }

The output window looked like this:

423
422
423
423
422
422
422

So breathing on the thermometer yielded about a 500 reading.  So there was a 78 point difference, the LED was blinking slower as the temperature went up but not noticeably.  So enter some math to make the spread more apparent.  I decided on a simple algorithm, take the value from the thermometer, subtract 422 to get the difference and multiply by 10.  I figure this would generate a more obvious change in blink rate.

I added the System.Math.Abs() method call to ensure that I did not pass a negative number to the Thread.Sleep() method call.  The code looks like this and flashes faster as the temperature nears room temperature and slower as it gets warmer.

public static void Main()
{
    OutputPort led = 
new OutputPort(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.ONBOARD_LED, false); AnalogInput variableResistor =
new AnalogInput(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0); while (true) { led.Write(!led.Read()); Thread.Sleep(System.Math.Abs((variableResistor.Read() - 422) * 10)); Debug.Print(variableResistor.Read().ToString()); } }
 



Netduino: Day 1 - Variable resistor (analog input) controlling onboard LED flashing.

clock August 2, 2011 19:19 by author dsandor

My friend Todd stuck four red boxes in the trunk of my car and told me I needed to master embedded programming against one of the three boards in the boxes: Netduino, Arduino, and a FEZ Panda II.  This is the beginning of my endeavors into embedded programming.  I have tinkered with electronics in the past but could not quote any of the electrical laws.  I have been programming for 15 years though most of that with .NET / C# since it was in pre-beta so this should be pretty simple.  I decided to blog my learning process in case another electrically challenged developer finds him(her)self in the same position as me.

My first blind project I decided to tackle is blinking an LED on the netduino board with a delay controlled by a variable resistor (knob).

So I grabbed an E-BLOCK POT VARIABLE RESISTOR which has 3 wires: red (positive), black (negative), and white.  The red and the black were pretty obvious.  I hooked the red up to the 3.3v on the netduino's power block and the black to ground. 

image

The white I figured was the output.  This is clearly an analog device so I figured I should hook up the white to the Analog 0 (zero) pin on the netduino.

I saw some articles on flashing the LED on the board and that seemed pretty simple so I just needed to figure out how to get the resistance value from that white wire.  I quickly found the AnalogInput class and with some intellisense I found out that the constructor took a Cpu.Pin value to read the analog input.  Further object browsing showed me a higher level class supplied in the netduino SDK that humanizes the Cpu.Pin enums.  The SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0 pin looked like the one I wanted.

Next I found the OutputPort class that let me play with the LED.  I passed SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.ONBOARD_LED to the constructor there and this lets me set the LED on and off.

public static void Main()
{

    OutputPort led = 
     new OutputPort(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.ONBOARD_LED, false);
    AnalogInput variableResistor = 
     new AnalogInput(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0);

    while (true)
    {
        led.Write(!led.Read());
        Thread.Sleep(variableResistor.Read());
    }
}

Executing the code resulted in the video below.  As I turn the knob of the POT the value read from the analog input changes thus changing the value input into the Thread.Sleep() method. So the LED flashing is relative to the amount of resistance on the variable resistor.

The final product, I showed the wife and she was not that impressed ;)


Dynamics Ax 2009 Logon/Logoff overhead, Business Connector, AIF.

clock April 17, 2011 17:54 by author dsandor

So last week I attended Convergence 2011 in Atlanta to prepare for Dynamics AX 2012.  I attended a few interactive discussions and met some folks that made some rather wild claims that I knew for a fact were wrong.  I advised them that they were probably missing something or there was a problem with their installation / database / or code.

The claim was that there is a 2 or more second authentication delay when logging on to Dynamics Ax from the AIF (and others claimed from the Business Connector as well).  Someone stated that it took them 5 hours to import 30,000 sales orders via the BC.  I import a heck of a lot more data then that on a routine basis and I am confident I could import 30k sales order in less than 2 mins.

The proof that they are wrong.

To prove this I wrote an application that logs on to AX and then off of AX and times the process with the Stopwatch class.  The system running AX is a Dynamics AX 2009 SP1 installation on a Dell i7 920 with 12G of RAM.  AOS, App files, and DB (SQL 2008R2 with 4GB of ram allocated to SQL) all run on the same machine.  So this is a basic low end developer workstation running everything.  Your production servers should run circles around the performance of my test machine.

Here are the results:

I ran the loop to logon and logoff 100 times.  You will see the first call takes 220ms and each subsequent call is at about 14ms.  This is a far cry from the 2,000+ ms claims from the interactive discussion at Convergence.

Start time: 0
sessionId: 5
Stop time: 220
Elapsed time: 220

Start time: 220
sessionId: 6
Stop time: 237
Elapsed time: 17

Start time: 237
sessionId: 7
Stop time: 256
Elapsed time: 19

Start time: 256
sessionId: 8
Stop time: 270
Elapsed time: 14

Start time: 270
sessionId: 9
Stop time: 284
Elapsed time: 14

Start time: 1629
sessionId: 103
Stop time: 1643
Elapsed time: 14

Start time: 1644
sessionId: 104
Stop time: 1658
Elapsed time: 14

What I suspect is that the code these folks are using is very poorly written.  Potentially executing a Refresh() call for each session that is constructed.  If you are running into a performance problem with your AIF or Business Connector code feel free to contact me to help you track it down.  My consulting rates are reasonable :)

The code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Dynamics.BusinessConnectorNet;
using log4net;
 
namespace AxConsoleForTests
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));
 
        static void Main(string[] args)
        {
            
 
            using (Axapta ax = new Axapta())
            {
                string aosConnString = string.Format("{0}@{1}:{2}",
                    "ceu",
                    "devsql-s-06",
                    "2713");
 
                log.InfoFormat("MyMethodName - Connecting to AX Server: {0}", aosConnString);
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                long startTime = 0, stopTime = 0;
 
                for (int i = 0; i < 100; i++)
                {
                    try
                    {
                        startTime = sw.ElapsedMilliseconds;
                        Console.WriteLine("Start time: {0}", startTime);
 
                        ax.LogonAs("axTestUser", "",
                            new System.Net.NetworkCredentials
                              ("axTestUser", "password", "devsql.local")
                            ,
                            "ceu", "", aosConnString, "");
 
                        Console.WriteLine("sessionId: {0}", ax.Session());
 
                    }
                    catch (Exception ex)
                    {
                        log.ErrorFormat("MyMethodName - Failure: {0}\r\n{1}", ex.Message, ex);
                        throw ex;
                    }
                    finally
                    {
                        ax.Logoff();
                        stopTime = sw.ElapsedMilliseconds;
 
                        Console.WriteLine("Stop time: {0}", stopTime);
                        Console.WriteLine("Elapsed time: {0}\r\n", stopTime - startTime);
                    }
                }
 
                sw.Stop();
            }
            
            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}

In order to thwart any comments that I cheated by placing my loop inside a using statement, I looped outside of it as well and the results are the same. 



iPhone / iTouch barcode scanning Hello World application with MonoTouch and LineaSDK

clock January 5, 2011 10:33 by author dsandor

This example is the result of many hours of trial and error.  With the resources provided in this post you will be able to create a small application that will let you scan a barcode into a textbox.  In future parts we will make a more useful application.

The barcode scanning functionality is provided with a hardware device.  If you are reading this you have likely already acquired the SDK and hardware from Infinate Periferals

The application will be developed in MonoDevelop and will utilize MonoTouch.net and MonoTouch.Dialog.  Please use this linkto get all these applications installed and working first.  Please be sure to compile the MonoTouch.Dialog assembly before getting started with this example.

Lets get started

First, Create a project in MonoDevelop of type iPhone Window-based project and give it a name.

Screen shot 2011-01-04 at 1.28.08 PM

When MonoDevelop has completed creating the templated project and solution files you will have something like this:

Screen shot 2011-01-04 at 1.34.28 PM

Here we will add a reference to the MonoTouch.Dialog assembly.  First I will copy it into my project folder by right clicking on the project name in MonoDevelop and choosing Open Containing Folder.  This opens the folder that contains your project files.  Copy the MonoTouch.Dialog.dll file into the project folder.  Right click on the References node in MonoDevelop and chose Edit References.

image

Locate the MonoTouch.Dialog.dll assembly

image

Double click on the MonoTouch.Dialog.dll assembly to add the reference and click OK.

We are now going to create a simple View that displays a message and an input field.  This View (aka form, dialog, screen, page) will be created using MonoTouch.Dialog to simplify things.  Please read up on MT.D on your own.  More examples will follow in the future for that.

Add a navigation controller to the application by double clicking on the MainWindow.xib file.  This will launch Interface Builder.  In the library window choose Objects and drag the Navigation Controller object to the MainWindow.xib window.  You will now have a navigation controller listed.  See image below.

image

Now we need to create an Outlet (aka property) for the navigation controller.  This is used to push views.  Think of the navigation controller as a Push / Pop frame and your Dialog is a view that will be pushed to the visible surface of the application.

imageTo create the Outlet you need to click on the Classes tab of the Library then click on the AppDelegate class at the top of the list.  Then at the bottom of the Library window you need to choose Outlets in the combo box. 

Click the little plus sign + to add a new outlet.  Name it navigation. 

Now we need to link the outlet to the Navigation Controller object in the MainWindow.xib.

image

Click on the App Delegate object in the MainWindow.xib interface builder window.  In the App Delegate Connections window you will see your new navigation outlet.  Hook this outlet up by clicking on the empty circle next to it and dragging it to the Navigation Controller object in the MainWindow.xib window.

image

When you have done this, your App Delegate Connections window will look like this:

image

Save your changes in the interface builder (Command + S).

Go back to MonoDevelop, you are ready to code.

Create an empty class file and call it:  MyBarcodeDialog.cs

Paste the following code, it creates a view with a textbox that we are going to scan into.

using System;
using MonoTouch.Dialog;

namespace MTBarcodeExample
{
    public class MyBarcodeDialog : DialogViewController
    {
        public MyBarcodeDialog () : base(null)
        {
            initView();
        }
        
        EntryElement txtBarcode;
        
        private void initView()
        {
            var root = new RootElement("Simple Barcode Example");
            var section = new Section("Collect Barcode");
            
            txtBarcode = new EntryElement("Barcode", "Please scan a barcode.", "");
            
            section.Add(txtBarcode);
            root.Add(section);
            
            this.Root = root;
        }
    }
}

Save your new class and double click on the Main.cs file.  We are now going to have the application load the NavigationController and then have the navigation controller push your MyBarcodeDialog view to the foreground.

To accomplish this we are going to modify the FinishedLaunching method.

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        
{
     // If you have defined a view, add it here:
            
     window.AddSubview (navigation.View);

     navigation.PushViewController(new MyBarcodeDialog(), true);

     window.MakeKeyAndVisible ();
    
     return true;
        
}

Basically what we did here was to add the navigation controller to the window’s SubView.  Then we use the navigation outlet (property) to push our new MyBarcodeDialog view controller into view.

Running the application now will result in the following form:

image

We now have a simple iPhone / iTouch application.  Now we will hook up the code for barcode scanning.

First we need to copy the libLineaSDK.a library file into our project folder.  This file is not distributed with the example code here because you need to sign up to be a developer with Integrated Peripherals and sign an NDA in order to acquire the SDK.

Next, we need to tell MonoTouch how to find the LineaSDK library and how to link it in to the project.  This next section allows no room for error.  Everything must be as described here or it will not work.  This has to do with the way that the LineaSDK is compiled and a nasty bug in the XCode linker.

Right click on the project and choose Options.

image

Click on iPhone Build and choose iPhone from the platform combo box.

Choose Don’t link in the linker behavior and paste the Extra arguments below.

-v -gcc_flags "-L${ProjectDir} -lLineaSDK -framework AudioToolbox -framework CoreGraphics -framework ExternalAccessory -ObjC"

Click OK to close the options window.

In order to use the barcode hardware, we need to edit the .plist file.  This file contains properties and values that tell the iOS information about your application.  In this case we need to tell the iOS that we want to allow the Linea hardware to talk to our app.  Double click on the Info.plist file to open up the plist editor.

image

Here we have to add two properties.

First, click on the Information Property List node and then click Add Child.

For the name enter UISupportedExternalAccessoryProtocols.  Click enter then right click on the property, choose value type and select Array.  Now we need to add two items to the array.

image

Click the button to the right of the property value.  This will add a child to the property.  It will auto name the property Item 0.  Enter com.datecs.linea.pro.msr

Click the button again to create Item 1.  Enter com.datecs.linea.pro.bar

Save and close the plist editor.

Now we need to create a class file that will provide an interface to the LineaSDK library.  This class file will be compiled with the btouch compiler provided with MonoTouch.  I will not go through that process here but I included the compiled DLL and the .CS class file used to generate the DLL.  This class is basically an interop class that provides an interface for the C# managed mono code to talk to the native LineaSDK.

The class I used looks like this:

using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using MonoTouch.ExternalAccessory;

namespace LineaSDK
{
    [BaseType (typeof (NSObject))]
    [Model]
    interface LineaDelegate {
        
        //-(void)connectionState:(int)state;
        [Abstract]
        [Export( "connectionState:" )]
        void ConnectionStateChanged( int state );
        
        //-(void)buttonPressed:(int)which;
        [Export ("buttonPressed:")]
        void ButtonPressed (int which);

        //-(void)buttonReleased:(int)which;
        [Export ("buttonReleased:")]
        void ButtonReleased (int which);

I attached this code here:

Here is the compiled DLL

You can learn how to compile this on your own here.

We now need to reference this class.  Right click on references and add the LineaSDK.dll to your project.

Your solution should now look like this:

image

We are getting close now.  We need to create two more classes to use with the LineaSDK.  An event message class and a LineaDelegate implementation. 

First we create the BarcodeMessageEventArgs.cs class in the project.  The code should look like this:

using System;
namespace MTBarcodeExample
{
    public class BarcodeMessageEventArgs : EventArgs
    {
        public BarcodeMessageEventArgs ()
        {
        }
        
        public BarcodeMessageEventArgs (string message)
        {
            Message = message;
        }
        
        
        public string Message {
            get;
            set;
        }
    }
}

Next, we need to implement the Linea Delegate interface.  Add a new class to your project named MyLineaDelegate.cs.

Use the following code:

using System;
namespace MTBarcodeExample
{
    public class MyLineaDelegate : LineaSDK.LineaDelegate
    {
        public override void ConnectionStateChanged (int state)
        {
            System.Diagnostics.Debug.WriteLine("ConnectionStateChanged: " + state.ToString());
        }
        
        public override void BarcodeDataReceived (string barcode, int type)
        {
            System.Diagnostics.Debug.WriteLine("Got barcode: " + barcode);
            
            if ( GotBarcode != null )
                GotBarcode.Invoke(this, new BarcodeMessageEventArgs(barcode));
        }
        
        public event EventHandler<BarcodeMessageEventArgs> GotBarcode;
    }
}

Now we can start using the LineaSDK and interact with the barcode scanner.

In the MyBarcodeDialog.cs class file we are going to add a method and an event handler.  This code will setup the SDK interface, connect to the hardware and update our textbox in the event of a barcode scan.

private void initHardware()
{
    Linea             = new LineaSDK.Linea();
    LineaDelegate     = new MyLineaDelegate();
    Linea.Delegate     = LineaDelegate;
    
    LineaDelegate.GotBarcode += HandleLineaDelegateGotBarcode;
    
    Linea.Connect();
}

void HandleLineaDelegateGotBarcode (object sender, BarcodeMessageEventArgs e)
{
    this.InvokeOnMainThread( delegate { txtBarcode.Value = e.Message; } );
}

The last thing to do here it to update the constructor to make sure the initHardware method is called.

public MyBarcodeDialog () : base(null)
{
   initView();
   initHardware();
}

Compile the code, deploy to the device, then run the application.  When the view loads you should see your form.  Clicking the scan button on the laser barcode hardware should scan barcodes into the Barcode field on the view.

image

 

There were a great many steps in this example but once you get this far you have a base scanning application.  Your next step should be to explore MonoTouch.Dialog and make a more complex application.

Download the full MonoDevelop solution below.  Please note that the LineaSDK library and any bits that belong to Infinate Periferals has been removed from this project.  You will need to add the libLineaSDK.a file in to the project folder yourself.

Download Source: MTBarcodeExample.zip


Download Source: MTBarcodeExample.zip



About the author

David Sandor is a Software Architect working in Chicago, IL.  My development focuses around the Microsoft Stack including Azure, AppFabric, Silverlight, WPF, .NET Framework, and various mobile devices including iOS (iPhone/iTouch), Android, Windows Mobile and Windows Phone 7.

Month List

Sign in