IValidatableObject and IDataErrorInfo

At the beginning it was IDataErrorInfo. Next , it came IValidatableObject. And , because some GUI frameworks implement one and not other, I must think to a common way to validate once .

My choice was to validate with IValidatableObject and IDataErrorInfo just re-send data.

I made an example with a class User which has UserName, UserEmail and UserPassword.

Without much ado, this is the code:

 public class User : IValidatableObject, IDataErrorInfo
    {
        public string UserEmail { get; set; }
        public string UserName { get; set; }
        public string UserPassword { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (string.IsNullOrEmpty(UserEmail))
                yield return new ValidationResult("UserName", new string[1] { "UserName" });

            if (string.IsNullOrEmpty(UserEmail))
                yield return new ValidationResult("UserEmail", new string[1] { "UserEmail" });

            if (string.IsNullOrEmpty(UserEmail))
                yield return new ValidationResult("UserPassword", new string[1] { "UserPassword" });

            
        }

        //IDataErrorInfo - you can copy this code to each class
        public string Error
        {
            get { return this[""]; }
        }

        public string this[string columnName]
        {
            get
            {
                string ret = null;
                var data = this.Validate(new ValidationContext(this, null, null));
                switch (columnName)
                {
                    case "":

                        foreach (var item in data)
                        {
                            ret += item.ErrorMessage + Environment.NewLine;
                        }
                        break;
                    default:
                        foreach (var item in data)
                        {
                            if (item.MemberNames.Contains(columnName))
                                ret += item.ErrorMessage + Environment.NewLine;
                        }
                        break;
                }
                return ret;
            }
        }
    }

And you can verify like this:

User u = new User();
            
            Console.WriteLine("-----from  IDataErrorInfo");
            string err = (u as IDataErrorInfo)[""];
            Console.WriteLine(err);
            
            Console.WriteLine("-----from  IvalidatableObject");
            foreach(var item in (u as IValidatableObject).Validate(new ValidationContext(u, null, null)))
            {
                Console.WriteLine(item.MemberNames.First());
            }


            Console.WriteLine("-----from  Validator");
            try
            {
                Validator.ValidateObject(u, new ValidationContext(u, null, null), true);
            }
            catch (ValidationException EX)
            {

                Console.WriteLine("JUST " + EX.Message);
            }

You can find the code also there
Validation

Azure

I am working at a new application ( Azure + MVC + logging) and I am having a good time  – when I know resources. This are the steps that works for me:

  1. Azure SDK ( it would be good if you have Sql Server). Now version 1.6, download from http://www.microsoft.com/download/en/details.aspx?id=28045
      1. Optional : run DSInit , http://msdn.microsoft.com/en-us/library/windowsazure/gg433005.aspx , to modify default SqlServer instance
  2. Windows Azure ASP.NET Providers Sample – good to fast use membership in Azure.
      1. for local , the .config keys are

        <add key="AccountName" value="devstoreaccount1" />
            <add key="AccountSharedKey" value=""></add>
            <add key="BlobStorageEndpoint" value="http://127.0.0.1:10000/devstoreaccount1" />
            <add key="TableStorageEndpoint" value="http://127.0.0.1:10002/devstoreaccount1" />

      2. for azure, the .config keys are

           <add key="AccountName" value="…………………………" />
          <add key="AccountSharedKey" value="………………"></add>

          <add key="BlobStorageEndpoint" value="https://logcollectorazure.blob.core.windows.net" />
          <add key="TableStorageEndpoint" value="https://logcollectorazure.table.core.windows.net" />

  3. Add Table Storage Provider- either from samples, either from here  http://blogs.msdn.com/b/jnak/archive/2010/01/06/walkthrough-windows-azure-table-storage-nov-2009-and-later.aspx  ( read http://blogs.msdn.com/b/jnak/archive/2008/10/28/walkthrough-simple-table-storage.aspx too)
      1. for local , the .config keys are
      2. <add key="BlobStorageEndpoint" value="http://127.0.0.1:10000/devstoreaccount1" />
        <add key="TableStorageEndpoint" value="http://127.0.0.1:10002/devstoreaccount1" />

      3. for azure, the .config keys are

<add key="BlobStorageEndpoint" value="https://logcollectorazure.blob.core.windows.net" />
<add key="TableStorageEndpoint" value="https://logcollectorazure.table.core.windows.net" />

From now, you do have

a) An Membership Provider -  to create users

b) Azure Tables that can be searched with IQueryable .

This is all you need for now. Later you will enquire about caching / session / application. I would post them when I will be programming more. However , for caching I will be starting at http://code.msdn.microsoft.com/windowsazure/Using-AppFabric-Cache-595454bb and for session at http://code.msdn.microsoft.com/windowsazure/Using-AppFabric-Cache-595454bb

Kinect

imageimage

I have the opportunity to borrow a Kinect hardware  – to make an application( I will make a simple anti-theft application).

The steps for developing in Kinect are:

  • Download the SDK from http://www.microsoft.com/en-us/kinectforwindows/develop/overview.aspx – it contains the drivers also
  • Connect Kinect to USB , plug in the socket
  • Run the Kinect Explorer or Kinect Shape Game from Kinect SDK Sample Browser installed at 1.  Ensure it works.
  • Read the Kinect Explorer source –it is SO clear!
  • Read documentation – finally, you should RTFM Winking smile

Optional resources:

  1. http://kinectcontrib.codeplex.com/ – Visual Studio template for Skeleton, Audio, Video. Simple example that works ( simpler than Kinect Explorer !)
  2. http://c4fkinect.codeplex.com/ – added methods to Kinect.
  3. http://kinecttoolbox.codeplex.com/ – detection of gesture.

Example 1: Integrating saving image in Kinect Explorer when a skeleton is detected

Add reference to optional resource 2( either download , either via Nuget)

Search for  KinectAllFramesReady in KinectSkeletonViewer.xaml.cs and put this code

						var takePic = this.skeletonData.Count(item => item.TrackingState == SkeletonTrackingState.Tracked) > 0;

						if (takePic)
						{
							DateTime imgDate = DateTime.Now;
							string imageName = "andrei" + imgDate.ToString("yyyyMMdd_HHmmss") + ".jpg";
							if (!File.Exists(imageName))
							{
								using (var image = e.OpenColorImageFrame())
								{
									if (image != null && this.skeletonData.Length > 0 && this.skeletonData.Count(item => item.TrackingState != SkeletonTrackingState.NotTracked) > 0)
										if (image != null && takePic)
										{
											var x = image.ToBitmapSource();
											var b = Save(x, ImageFormat.Jpeg);

											var t = Task.Factory.StartNew(

												(img) =>
												{

													imgDate = DateTime.Now;
													imageName = "andrei" + imgDate.ToString("yyyyMMdd_HHmmss") + ".jpg";
													if (File.Exists(imageName))
														return;
													byte[] i = img as byte[];
													if (i != null)
													{
														File.WriteAllBytes(imageName, i);
													};
												}, b);
											//t.Start();
										}
								}
							}
					}

Example 2 : Detecting circle by right hand in Kinect Explorer when a skeleton is detected

Add reference to optional resource 3( either download , either via Nuget)

Download circleKB.save file and put in your project. Ensure “Copy to output directory” is “copy always/copy if newer”

Add a variable named

TemplatedGestureDetector circleGestureRecognizer;

In KinectSkeletonViewer.xaml.cs in constructor put

			using (Stream recordStream = File.Open("circleKB.save", FileMode.Open))
			{
				circleGestureRecognizer = new TemplatedGestureDetector("Circle", recordStream);
				circleGestureRecognizer.OnGestureDetected += new Action<string>(circleGestureRecognizer_OnGestureDetected);
//TODO : implement circleGestureRecognizer_OnGestureDetected : void circleGestureRecognizer_OnGestureDetected(string obj)
			}

Search for KinectAllFramesReady in KinectSkeletonViewer.xaml.cs and put this code


foreach (Joint joint in skeleton.Joints)//existing code
							{
								Point mappedPoint = this.GetPosition2DLocation(depthImageFrame, joint.Position);//existing code
								jointMapping[joint.JointType] = new JointMapping//existing code
									{
										Joint = joint,
										MappedPoint = mappedPoint
									};
//new code from here:
									 if ((joint.TrackingState == JointTrackingState.Tracked) && (joint.JointType == JointType.HandRight))
									{
											circleGestureRecognizer.Add(joint.Position, Kinect);
									}

							}

That will be all…
If you have developed with Kinect, please share your sources as comments.

Attach macro

A visual studio macro to attach to a program to your choice:

Public Sub AttachPRogram()
        Try
            Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
            Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
            Dim compName As String = System.Net.Dns.GetHostName()
            Dim procAll = dbg2.GetProcesses(trans, compName)
            For Each proc2 As Process2 In procAll
                If (proc2.Name.ToLower().Contains("your program name here")) Then

                    proc2.Attach()

                End If
            Next proc2

        Catch ex As System.Exception
            MsgBox(ex.Message)
        End Try
    End Sub

friday links 18

MVC 4 beta was the release of the month : http://www.asp.net/mvc/mvc4 

  1. NETFx3 Samples – Home – dynamic calling WCF services
  2. Alan Turing’s reading list (with readable links) | John Graham-Cumming
  3. Six Whys – Or, Never Trust Your Network Switch – Blog – Stack Exchange
  4. In a New Era for Marketing, Parental Discretion Advised – Leslie Gaines-Ross – Harvard Business Review
  5. Dynamic Proxy and Memory Footprint – Vipul Modi’s Blog – Site Home – MSDN Blogs
  6. A look at ASP.NET MVC 4 | Techdays 2012 the Netherlands | Channel 9
  7. How to: Create Custom Configuration Sections Using ConfigurationSection
  8. RESTful Services with ASP.NET MVC and XHTML
  9. ASP.NET MVC Localization: Generate resource files and localized views using custom templates | Rui Jarimba
  10. ASP.NET: Downloading files from a UNC share | Rui Jarimba
  11. Single Page Application Overview: The Official Microsoft ASP.NET Site
  12. XML Visualizer v.2 – CodeProject®
  13. Calling a WCF service from a client without having the contract interface – CodeProject®
  14. 52 Things People Should Know To Do Cryptography
  15. Must-have Tools on Windows – Part 1 of 2 – Punit Ganshani
  16. Download HelpNDoc Personal Edition | HelpNDoc
  17. HelpNDoc’s feature tour | HelpNDoc
  18. Recruiting: 8 Qualities Your Best Employees Should Have | Inc.com
  19. Ubuntu for Android Effort Takes Flight – InternetNews.
  20. Mark Shuttleworth » Blog Archive » Ubuntu in your pocket
  21. Simple Talk Newsletter
  22. Automated Script-generation with Powershell and SMO
  23. How to Kill a Company in One Step or Save it in Three

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.