Archive

Author Archive

Attached Behaviors & MVVM

April 22, 2012 Leave a comment

When you think of MVVM and other patterns involved, it is often about separation of concerns as much as possible, unit testability and code maintainability. These type of patterns help in high quality of code and efficient development of business functionality. If you are new to MVVM then you may want to check out some of the articles by various intellects like Josh Smith, Laurent Bugnion and few others from XAML Disciples group(or just Google Smile).

There are lot many frameworks on MVVM out there and to be frank there isn’t any right or the wrong one. You need to evaluate and decide on the one that fits your need! Most often people land up writing one on their own and in a way it is good!

I personally like a framework written by Brette Esterbrooks because it is a skeleton of code that you need and helps you get started. I tweaked it a bit(basically removed the ones that I don’t need) and thus the sample attached on this blog will have a tiny little framework of MVVM.

All it has is just a few helper classes:

  1. ViewBase,
  2. ViewModelBase,
  3. RelayCommand,
  4. ObservableObject.

Attached Behaviors

 

Attached behavior is achieved by simply attaching a behavior to a control that otherwise wouldn’t have anything of its own.

And as per Josh Smith-

The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.

Ever since I am hooked to MVVM pattern, I try and avoid all the code that usually goes to the code behind. For e.g. a click event handler usually written in the code behind can be omitted and a RelayCommand in the ViewModel be used instead.

But what would happen if you want to handle a double click or a focus event of a control? Just retaining those kind of events to the code behind defeats the pattern itself. And thus Attached Behavior comes to rescue! Demo included in this post explains the DragDropBehavior.

Before you go further with this approach, I just want you to know that you can achieve this by Behavior<T> class included in the system.windows.interactivity.dll. However this dll is available only through Expression Blend installation.

In my demo I have explained both of the implementation and it’s usage. Here we go!

Screenshot of the Demo:

 

AttachedBImage

 

IBehavior

 

The view models can hold the reference of this contract and change at runtime if needed:

  1. public interface IBehavior
  2.     {
  3.         void OnEnabled(DependencyObject dependencyObject);
  4.         void OnDisabling(DependencyObject dependencyObject);
  5.     }

 

 

AttachedBehavior – A static class!

 

A static class AttachedBehavior is introduced which holds the attached properties “Behavior” and “IsEnabled”.

When toggled from Enabled state to Disabled State – OnDisabling() method of the IBehavior is called. Use this method to unwire your event handlers.

 

  1. /// <summary>
  2.         /// Attach a Behavior of type IBehavior
  3.         /// </summary>
  4.         public static readonly DependencyProperty BehaviorProperty = DependencyProperty.RegisterAttached("Behavior", typeof(IBehavior), typeof(AttachedBehavior), new UIPropertyMetadata(null));
  5.  
  6.         /// <summary>
  7.         /// Is Enabled, when set to true, fires Behaviors OnEnabled Method
  8.         /// </summary>
  9.         public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(AttachedBehavior), new UIPropertyMetadata(false, OnIsEnabledChanged));
  10.  
  11.         /// <summary>
  12.         /// Handles IsEnabledChanged
  13.         /// </summary>
  14.         /// <param name="d"></param>
  15.         /// <param name="e"></param>
  16.         private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  17.         {
  18.             if (d == null)
  19.                 return;
  20.             var behavior = GetBehavior(d);
  21.             if (behavior == null)
  22.                 return;
  23.             if ((bool)e.NewValue)
  24.                 behavior.OnEnabled(d);
  25.             else
  26.                 behavior.OnDisabling(d);
  27.         }

 

DragDropBehavior Class

 

DragDropBehavior class implements the IBehavior. Have a look at the OnEnabled and OnDisabling methods.

  1. public class DragDropBehavior : IBehavior
  2.     {
  3.         #region Private Fields
  4.         private Point _startPosition;
  5.         private Point _mouseStartPosition;
  6.         private TranslateTransform _translatetransform;
  7.         private UIElement _associatedObject = null;
  8.         private Window _parent = null;
  9.         #endregion
  10.  
  11.         #region IBehavior Members
  12.         public void OnEnabled(DependencyObject dependencyObject)
  13.         {
  14.             var uiElement = dependencyObject as UIElement;
  15.             if (uiElement == null)
  16.                 return;
  17.             
  18.             _associatedObject = uiElement;
  19.             //TODO: set the parent accordingly
  20.              _parent = Application.Current.MainWindow;
  21.             _translatetransform = new TranslateTransform();
  22.             _associatedObject.RenderTransform = _translatetransform;
  23.             _associatedObject.MouseLeftButtonDown += AssociatedObjectMouseLeftButtonDown;
  24.             _associatedObject.MouseLeftButtonUp += AssociatedObjectMouseLeftButtonUp;
  25.             _associatedObject.MouseMove += AssociatedObjectMouseMove;
  26.         }
  27.         
  28.         public void OnDisabling(DependencyObject dependencyObject)
  29.         {
  30.             _associatedObject.MouseLeftButtonDown -= AssociatedObjectMouseLeftButtonDown;
  31.             _associatedObject.MouseLeftButtonUp -= AssociatedObjectMouseLeftButtonUp;
  32.             _associatedObject.MouseMove -= AssociatedObjectMouseMove;
  33.             _translatetransform = null;
  34.         }
  35.         #endregion
  36.  
  37.         #region Event Handlers
  38.         void AssociatedObjectMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  39.         {
  40.             _startPosition = _associatedObject.TranslatePoint(new Point(), _parent);
  41.             _mouseStartPosition = e.GetPosition(_parent);
  42.             _associatedObject.CaptureMouse();
  43.         }
  44.         
  45.         void AssociatedObjectMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  46.         {
  47.             var positionDifference = e.GetPosition(_parent) – _mouseStartPosition;
  48.             if(_associatedObject.IsMouseCaptured)
  49.             {
  50.                 _translatetransform.X = positionDifference.X;
  51.                 _translatetransform.Y = positionDifference.Y;
  52.             }
  53.         }
  54.  
  55.         void AssociatedObjectMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
  56.         {
  57.             _associatedObject.ReleaseMouseCapture();
  58.             
  59.         }
  60.         
  61.         #endregion
  62.  
  63.  
  64.     }

 

HelloView

 

Attach is the behavior to the control that you want to drag:

  1. <ToggleButton Name="dragDropToggleButton" Command="{Binding ToggleDragDropBehavior}" Width="200">
  2.                 <ToggleButton.Style>
  3.                     <Style TargetType="{x:Type ToggleButton}">
  4.                         <Setter Property="Content" Value="Start Dragging"/>
  5.                         <Style.Triggers>
  6.                             <Trigger Property="IsChecked" Value="True">
  7.                                 <Setter Property="Content" Value="Stop Dragging"/>
  8.                             </Trigger>
  9.                         </Style.Triggers>
  10.                     </Style>
  11.                 </ToggleButton.Style>
  12.             </ToggleButton>
  13.  
  14.  
  15.    
  16.               <TextBlock Background="Gold"
  17.                        Text="dragMe using attached behavior"
  18.                        Behaviors:AttachedBehavior.IsEnabled="{Binding IsDragBehaviorEnabled}"
  19.                        Behaviors:AttachedBehavior.Behavior="{Binding DragDropBehavior}"
  20.                        Canvas.Left="32"
  21.                        Canvas.Top="31" />

 

HelloViewViewModel

 

And finally the ViewModel that set’s the DragDropBehavior:

  1. public class HelloViewViewModel : ViewModelBase
  2.     {
  3.         private IBehavior _dragDropBehavior;
  4.         private bool _isDragBehaviorEnabled;
  5.  
  6.         public bool IsDragBehaviorEnabled
  7.         {
  8.             get { return _isDragBehaviorEnabled; }
  9.             set { _isDragBehaviorEnabled = value; RaisePropertyChanged(()=> this.IsDragBehaviorEnabled); }
  10.         }
  11.  
  12.         public IBehavior DragDropBehavior
  13.         {
  14.             get { return _dragDropBehavior; }
  15.             set { _dragDropBehavior = value; RaisePropertyChanged(() => this.DragDropBehavior); }
  16.         }
  17.  
  18.         public RelayCommand ToggleDragDropBehavior { get; set; }
  19.  
  20.         public HelloViewViewModel()
  21.         {
  22.             DragDropBehavior = new DragDropBehavior();
  23.             ToggleDragDropBehavior = new RelayCommand(() =>
  24.             {
  25.                 IsDragBehaviorEnabled = !IsDragBehaviorEnabled;
  26.             });
  27.  
  28.         }
  29.     }

 

That’s It – you are done!! Refer DragDropBehavior2 class for implementation using Behavior<T>.

Download the Code – Read the Disclaimer of this blog before you work with this code!

/*Nish*/

Categories: C#, MVVM, WPF Tags: ,

Windows 8 on VirtualBox– File Sharing(Guest Additions doesn’t work)

April 17, 2012 Leave a comment

Guest Additions on Virtual Box can be installed by changing compatibility to Windows 7 but that doesn’t mean it can be made to work. Yeah that’s where I too got stuck and my hunt for a fix to it also stopped when I read this forum.

I found few others who have tried complicated file sharing techniques, for e.g. they  created a secondary virtual hard drive and put files into it. However being working on Windows for more than a decade, I do believe there should be a simple way to achieve it. After all they are two different windows machines on the network.

Well what would you do to access a share drive on another system? Start->Run-> and type “\\machine-name\share” and hit enter?  That wouldn’t work because your host machine name will not be recognized by your virtual machine since they are on a different network group.

Now here is the solution: Go ahead and figure out the IP address of your host machine(ipconfig) and try accessing the share by its IP address instead of the machine name. That works!

 

Access

Things are simple, we complicate it most of the time.

 

/* Nish */

Categories: Troubleshooting, Windows8 Tags:

WPF XML Browser Control

April 12, 2012 Leave a comment

Ever wondered how to get a IE like look and feel of the xml in the default WPF web browser control? If your answer is – “Just navigate the Web Browser to the xml path”; You are right! But if you have to navigate to a in-memory xml? Read on to know and apply IE like styling for xml stored in a string variable.

Idea of writing a custom based xml browser control came in because I had a requirement to edit the xml on fly and validate it against a specified schema. User is allowed to edit only the standard xml(compiled as an embedded resource) that the tool provides and not navigate to any path.

This control helps you:

  1. Load the xml from the string and apply IE like styling
  2. Edit the xml
  3. Validate the xml against the defined schema

Before I go further, here is what you get:

image

The problem with web browser when navigating to a string is that it does not load the style for it. Hence the work around is to transform the xml and navigate to it. To do so you need the Xslt that IE uses. After googling for “xml pretty print”, I finally got one originally written by Jonathan Marsh of Microsoft for IE5 and modified by Steve Muench for conversion to XSLT 1.0 REC.  Copy the xml from here.

And here is the code to transform it:

/// <summary>
        /// Executes when XmlDoc DP is changed, Loads the xml and tranforms it using XSL provided
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        public static void OnXmlDocChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var browserControl = d as XmlBrowserControl;
            if (browserControl == null) return;
            var xmlString = e.NewValue as string;
            
            try
            {

                var xmlDocument = new XmlDocument();

                var xmlDocStyled = new StringBuilder(2500);
                // mark of web – to enable IE to force webpages to run in the security zone of the location the page was saved from
                // http://msdn.microsoft.com/en-us/library/ms537628(v=vs.85).aspx
                xmlDocStyled.Append("<!– saved from url=(0014)about:internet –>");

                var xslt = new XslCompiledTransform();
                //TODO: Do not forget to change the namespace, if you move the xsl sheet to your application
                var xsltFileStream =
                    typeof(XmlBrowserControl).Assembly.GetManifestResourceStream(
                        "WPFXmlBrowser.Controls.XmlBrowser.Resources.xml-pretty-print.xsl");
                if (xsltFileStream != null)
                {
                    //Load the xsltFile
                    var xmlReader = XmlReader.Create(xsltFileStream);
                    xslt.Load(xmlReader);
                    var settings = new XmlWriterSettings();
                    // writer for transformation
                    var writer = XmlWriter.Create(xmlDocStyled, settings);
                    if (xmlString != null) xmlDocument.LoadXml(xmlString);
                    xslt.Transform(xmlDocument, writer);

                }

                browserControl.EditText.Text = xmlString;
                browserControl.WebBrowser.NavigateToString(xmlDocStyled.ToString());
                browserControl.EditButton.Visibility = System.Windows.Visibility.Visible;
                browserControl.CopyClipButton.Visibility = System.Windows.Visibility.Visible;
            }
            catch (Exception ex)
            {
                browserControl.WebBrowser.NavigateToString("Unable to parse xml. Correct the following errors: " + ex.Message);
            }
        }

 

XSLT is provided as an embedded resource and it is loaded from the code. If you are moving the xslt to your project, make sure to change the namespace in the calling code.

image

You can download the code from my share here. This code works on my machine!

Feel free to modify the code, but as usual you don’t get warranty!

/*Nish*/

Categories: C#, WPF Tags: , ,

Hello Windows 8 world–Installation on a Virtual Machine

September 15, 2011 Leave a comment

2009 was the year I wrote a post on Installing Windows 7 on VMware, and 2 years later with the same excitement here I am saying Hello to Windows 8. This time I am not elaborating on the installation but yes will share some interesting posts already on it.

Few approaches:

Installing Windows 8 Developer Preview in a virtual machine. – I did this, it worked for me!

Step by step instructions to install Windows 8 successfully on VMWare Workstation 8

Installing Windows 8 Developer Preview as bootable VHD” – It yields much better performance, this will be my next shot!

Before I decided to install it on the Virtual Box, I gave an attempt on the Windows Virtual PC which came pre-installed with my OS (if Windows XP Mode is enabled). But then the Win 8 version I wanted to install was a 64 bit developer preview and unfortunately Virtual PC does not support 64bit guest OS. You will get this error “This 64-bit application couldn’t load because your PC doesn’t have a 64-bit processor”.

Installation on a VirtualBox was a different experience for me – BSODs and Graphical driver crash. No you may not face this because unlike me; you would never attempt to run a Virtual PC in parallel with a Virtual Box Smile.

One important thing to do before you install is to check, if your processor supports Virtualization and enable it in your BIOS. If not you will get this error “Failed to start virtual machine (name of machine) VT-x is not available” when you start the VM.

If you are using an Intel Processor, check its specification at ark.intel.com, Intel Virtualization technology(VT-X) should be supported.

image

By default these features are disabled, so enable these from your BIOS settings.

Go ahead and complete your installation:

287664_10150801452540713_520785712_20554375_1592634805_o

I must say this before I conclude this post – “Win 8 without a touch monitor on a VM is just a Win 7 with painful experience!” If you are a developer and you want your machine to respond as per your original hardware then do a clean install or use a VHD!.

Some interesting links:

Windows Developer Preview Guide

Metro Style App Examples

WinRT Capabilities

Note: Please read the disclaimer on my page before you get started.

/*Nish*/

Categories: VMWare, Windows8 Tags: , , ,

Android WIFI Problem – Obtaining Address…

December 5, 2010 11 comments

Ever since I changed my broadband modem, I have been facing issues with my HTC Wildfire connecting to my WIFI router. Every time it connects to my WIFI, it gives a message “Obtaining address..” and its stuck with this message for sometime. Having just a fair knowledge on networking, it took me some steps to reach to a solution. And here it is…

For some of you it may work by simply restarting your WIFI or by restarting your Android device. If it doesn’t, read on to find out if your problem is similar to mine.

Before I jump into the solution, it is important that you understand my network and my devices. My internet broadband modem and WIFI router are two different entities – meaning my modem does not support WIFI routing, so I had to have a WIFI router separately.

  1. Modem – Binatone DT815 ADSL2+ router (supplied by Airtel India)
  2. WIFI Router – Netgear WGR614
  3. From here on for better understanding I will use the term “Modem” to represent my broadband device and “WIFI Router” to represent my WIFI device. Since both the devices are capable of DHCP, I had to disable one to avoid conflicts. I wanted the default gateway to be the modem’s, so I enabled DHCP only on my modem and disabled the other. Modem detects the WIFI router as just another device in its network and not as a router.

    My IP addresses are configured like this:
  1. Modem – 192.168.1.1
  2. WIFI Router – 192.168.1.2 (Set from router’s LAN Settings)
  3. Other devices which connect, get IPs assigned by the Modem with default gateway as 192.168.1.1

Whenever I tried connecting my android device to WIFI, it gets stuck at “Obtaining address..”. I knew the problem lies in address resolution, so it was either my device not accepting the IP issued or the modem not recognizing the android.

I logged into Modem’s configuration and checked the LAN Connection pool summary(this setting displays the connected devices and its MAC addresses). To my surprise I found that my android device was issued an IP which was same as my router (192.168.1.2) and thus the conflict.

There were two ways I could resolve this conflict:

  1. Change the WIFI router’s IP (from it’s LAN Settings – by logging into WIFI configuration)
  2. Use a Static IP Address in your android device.
    For some reason point 2 never worked for me; but point 1 did. Hope this helps someone.

Cheers

Categories: Android Tags: , , ,

Have an operation to measure? Use Stopwatch()

October 20, 2010 2 comments

Quite often we run into situations where we need to measure the elapsed time of a method/operation, and there are number of ways to do it. The simplest way to do is by using a Stopwatch. This class is available under the namespace System.Diagnostics.

To show you a demo, I have used a simple app which calculates the time taken to load a website on your local machine.

namespace Nish.Stopwatch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("WebAddress> ");
            Console.WriteLine("Your website took about " + LoadWebsite(Console.ReadLine()).Seconds + " seconds to load on your machine");
            Console.ReadLine();
        }

        /// <summary>
        /// Gets the load time of a website
        /// </summary>
        /// <param name="websitePath">Path in the format: e.g. http://nnish.com </param>
        /// <returns>Time taken</returns>
        private static TimeSpan LoadWebsite(string websitePath)
        {
            System.Diagnostics.Stopwatch stpWatch = new System.Diagnostics.Stopwatch();
            stpWatch.Start();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(websitePath);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Read the data in the stream
            StreamReader streamReader = new StreamReader(response.GetResponseStream());
            // s – will have your html content, I am not using this for now
            string s = streamReader.ReadToEnd();
            stpWatch.Stop();
            
            return stpWatch.Elapsed;
        }
    }
}

 

Time took for my website to load:

image

Look at the time Google took:

image

And now this was out of curiosity:

image

Please note: The load time depends on various factors like network speed, server location,  page content etc. So this data should not be treated as accurate. The idea of having this example is to show the usage of Stopwatch and not to determine the speed of the website.

Method Stopwatch.Start() starts the timer, and ticks in parallel until the Stopwatch.Stop() is executed. The start method does not start the elapsed time at 0, if executed again. To set the elapsed time to 0 use either Stopwatch.Restart() or call Stopwatch.Reset() before the next start(). So understand that “A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset/restarted.” – MSDN. To start a fresh timer use Stopwatch stopwatch = Stopwatch.StartNew() which is a static method.

This comes very handy when you use this for all your performance monitoring or benchmarking on/the your operations.

Cheers!

Categories: C# Tags:

Long time since I blogged!

October 20, 2010 1 comment

No laziness is not the only reason why I skipped blogging for months together. I was on a complete learning mode, when I say learning its not just the technical stuffs I am talking about. I was involved in various activities of life, which demanded a lot of my personal time. A lot of activities which were completely new to me, and had no clue on how to go about it. I am not completely done with it (that said there is no definite time frame on blogging), but have decided to pull out some of my time. My passion for technology and photography are in my breath and that keeps me alive, but off late I realized it wasn’t enough! probably I need some food to survive. And that is something which I will let you know in years to come!

My transition from an entrepreneur to a full time employee was a tough decision, but have to do that to sustain and to overcome the loses! Am I complaining? No I am lucky enough in doing something what I always wanted to do and that is programming! The point is having bitten by the entrepreneur bug in some time of my life, has not let me sleep peaceful. Regaining those momentum and going forward in that direction is even more riskier until I have some concrete things planned.

Other than the learning of life I had couple of new learning which were technical and they were completely new from my field of work. But it was necessary to keep the momentum on. Oh did I say I have some concrete plans? No not yet!

Sometimes taking a right decision is far more easier than making your decision right!

To restart blogging, I am initiating a simple technical post which is coming up next!

Cheers!

Categories: Personal Tags:

Accessing WPF controls on a non UI Thread

March 14, 2010 Leave a comment

I am sure most of you would have run into this issue before. When you try to access a WPF control on a different thread other than your regular UI thread you get a runtime exception “The calling thread cannot access this object because a different thread owns it.”. To understand why this happens, it is important to know that WPF applications run on two different threads – one for rendering the controls and the other to manage the user interface. The rendering thread runs in the background and the thread which is visible for us to work on is the UI thread. And hence most of the objects are tied to the UI thread and this is known as thread affinity. Thread affinity is handled by the Dispatcher. Each user interface related work item is channeled through the Dispatcher class, that means every work item is queued by the UI thread in an object called Dispatcher. Dispatcher runs the work items on priority basis. Supporting work item prioritization allow WPF to work on a an item for more time and hence more time is consumed on the UI thread. UI thread will have at least one Dispatcher, and each Dispatcher can execute work items in exactly one thread. So it is important to release the work item from the thread as fast as possible so as to increase the UI responsiveness.  To keep the work item small,  I spawned newer threads and executed the discrete blocks of code on these threads. This is exactly where I ran into the exception stated above (when I tried to access the  WPF control).

So here is how I got the exception:

private void myButton_Click(object sender, RoutedEventArgs e)
{
    Thread t = new Thread(new ThreadStart(
        delegate
        {
            //accessing the TextBlock.Text on a different thread – **incorrect**
            myText.Text = "HI";
        }
        ));
    t.Start();
}

 

So how to get rid of this?

Now we know why a background running thread cannot access the UI thread. To get rid of this problem it is pretty simple – “Just ask the UI thread to do it for you”. Yes the background thread can request the UI thread to update the control properties on behalf of it. This is achieved by calling the Invoke or the BeginInvoke method of the DispatcherObject class. This will register the work items to the Dispatcher. Invoke is a synchronous call – that is, it doesn’t return until the UI thread actually finishes executing the delegate. BeginInvoke is asynchronous and returns immediately. So as stated above Dispatcher orders work items by priority and hence you can pass the priority using DispatcherPriority enumerator while registering the work item to Dispatcher. 
So here is the code below which solved my problem:

private void myButton_Click(object sender, RoutedEventArgs e)
{
    Thread t = new Thread(new ThreadStart(
        delegate
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new Action<TextBlock>(SetValue), myText);
        }
        ));
    t.Start();
}

private static void SetValue(TextBlock txt)
{
    txt.Text = "HI";
}

In the Dispatcher.Invoke() method used above takes three parameters – DispatcherPriority Enum, Delegate to execute the code and the parameter object. I used the Action<T> generic type to pass the control to the method to set its property.

It is suggested to use the setting of the control properties in the UI thread itself, and only move those code like say calculations to another thread. This will provide a better code maintenance.

However in the above example we do not improve the UI responsiveness, as the Invoke() method is called synchronously. Instead use BeginInvoke() method. My intention was to give an insight of the exception – why, and how to deal with it. If you need details on writing better responsive applications refer Shawn Wildermuth’s article

Wow another weekend in research -Cheers!

Success in entrepreneurship is for the one who is prepared

January 19, 2010 Leave a comment

Everyone say “Entrepreneurship isn’t easy and not meant for all”. As an experienced kid I do agree. But why isn’t it easy for all? When college drop outs like Bill Gates, Steve Jobs and Mark Zuckerberg can do it then why can’t others? I looked back to see what went wrong in my case. I am writing this down so that, I don’t forget these in my next venture. If this helps you do let me know.

Have A Great Idea, But Sellable –
Just because you have a great idea, it doesn’t mean that you have customers for it.It is important to have a market. Identify the need, make sure your solution is unique and deliver with quality.

Have A Vision -
Vision is the key. If you have an idea and a market you are sure shot to go. But will you sustain? Can you resist the change? Vision is not just a statement you need to add it to your about us page. It should be the one which you strictly follow at every stage. Have milestones and look back if you are aligned to the vision.Make sure every one in the company values the vision and follows it. Write down your vision on the paper and put it into a the board discussion. Remember how Microsoft is committed to its vision “Computer on every desk and in every home”. Today almost every one has a computer which is personal and running a Windows in it.

Choose Right Partners -
Your best friend is not always a right business partner for you. Because you care for your relationship you shouldn’t bring him/her into your business- That’s why they say “Mind Your Own Business”. Money plays a major role in business and but in relationships it is negative. So if you care for them then DO NOT. Your partner is one who stays by you during success as well as failure. Usually it happens the other way when you have your friend in business – He stays with you during success but blames you when you fail. Your partner should think like you, have passion like yours, should be committed like you and should have his/her own capability to make things right. Things fall into place faster when you have partners in different domains like marketing, technology, human resource etc. As they say the Lions, Tigers and other animals constitute a Jungle :) .

Plan Your Capital, Have A Business Plan -
$$$$Money$$$$ Where is the money to invest? What if i loose? I am a family man. The fear – setback. “Money is everything” Money is not everything but money is needed for everything. Its not right to believe that only a rich kid can do a business. Anyone with a smart business plan can do. A business plan is a written description of your business’s future. It should have key inputs like:

1. Executive summary
2. Business description
3. Market strategies
4. Competitive analysis
5. Design and development plan
6. Operations and management plan
7. Financial factors
*source: entrepreneur.com
If you have the fear of investing but you believe in your idea you still can do a great business. I agree that you cannot bring in huge capital into your business, instead approach a venture capitalist with your business plan. Convince him on the Return On Investment(ROI), if it interests him; he will help. VCs just eat up your stake because they are the risk takers. Don’t be greedy just sell your idea and give returns.

Hire Smart People -
Hire smart people on board and give them your best – the Google way. You should have managers who understand your business, maintain business secrets and take right decisions for you. Do not get involved in micromanagement it spoils everything. If you have hired a smart guy, you should leave the decision to him. Make them feel special and motivated at every stage. They are not just your employees, they are the people who are committed to you and the company. They are the reason for your success and you are the reason for the failure.

Have A Process -
You need not be a CMM level company to have a process. If you define a process now, you don’t have to repent later. Your process need not be complicated, but simple enough to take care of everyday activity. In your process make sure you keep milestones and measure your progress.

Change is Constant
Keep changing with times. No business can last long everything has a saturation. Identify the change early and get ready for the future. Once you have the idea which is already in the market, a great vision, hired smart people, and put a process in place then whats your job? – Smell the future, plan, and get ready!

These are just few of the points I remembered when I looked back at my failure. May be this is just right to my situation. Let me know if you guys have some other key points that I should keep in mind.

Some resources:
5 Myths That Can Kill a Start-Up
Entrepreneur

Cheers!

Categories: Entrepreneurship

Animated Gif in WPF using Windows Forms Control

January 11, 2010 3 comments

Loading an animated gif into WPF has been a challenge since the version 1 release. WPF does not support loading an animated gifs directly into an declarative <Image> or by code, and hence developers have come out with various workarounds. Some use a raw technique – writing few lines of code which extracts the frames of the GIF and animate them.  One other way to do is using the <MediaElement> FrameworkElement which is in the namespace System.Windows.Controls. <MediaElement> wraps the MediaPlayer class for declarative use and hence it supports both audio and video files. Using MediaElement you can load the animated gif the following way:

<MediaElement Source="file://D:\anim.gif"/>

Remember it is important to use “file://” and an absolute path for loading the gif. So you cannot embed the image to a resource file and now you know one of the limitations of it. Every approach does have advantages and limitations of its own, its important to use the right approach based on the project needs.

Another possible way is by making the working Jack do the trick – Yeah I meant lets go back to Win Forms picture box to do the magic. We know PictureBox seamlessly loaded the animated gifs in Win Form days. Wait a minute did I say lets change the project from WPF to Win Forms? No I didn’t. What I said is lets integrate the PictureBox alone to the WPF project. To use the right word, I should say that we need to host the Windows Forms Control in WPF. To host a Windows Forms Control you need to make use of the class WindowsFormsHost which appears in the System.Windows.Forms.Integration namespace in assembly WindowsFormsIntegration.dll.

Lets get to the code. The first step to do is add a reference to System.Windows.Forms.dll and WindowsFormsIntegration.dll to your WPF based project.

References

Add the following namespaces to your XAML Code.

<Window x:Class="WpfApplication2.Window1"
    xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

Now you can host the PictureBox inside the WindowsFormsHost and set its Name.

    <Grid>
        <wfi:WindowsFormsHost>
            <winForms:PictureBox x:Name="pictureBoxLoading">
            </winForms:PictureBox>
        </wfi:WindowsFormsHost>
    </Grid>

In your code behind(Window1.xaml.cs), add this code to the Window_Loaded Event:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.pictureBoxLoading.Image = System.Drawing.Image.FromFile("anim.gif"); ;
        }

Key points before execution:

  1. Make sure you provide the right path to load the image
  2. You can also load it from a resource file.

Since Windows Forms has several interesting built in controls that WPF lacks, using this technique you can make your favorite Windows Forms control work in WPF.

Cheers!

Follow

Get every new post delivered to your Inbox.