Sammy Ageil

Lead by example

Create an Asynchronous findControl function in WinRT javascript

September 25
by Sammy Ageil 25. September 2012 00:37

In our last tutorial we created a findControl function and used it to return a valid winRT's winControl.
Today we will add the Asynchronous version of our method. Asynchronous operations in javascript's WinRT are handled using javascript Promises or deferreds patterns.
So what is a promise pattern?
A promise or deffered is an object which represents the output of some computation which hasn't necessarily happened or completed yet. When you try to use the value in a promise, the program waits for the computation to complete then returns the computed value to the caller. It is critical to understand that Promises DO NOT create new threads.Promises simply provide a convenient way to do something when something else is done.

Now we understand what is a promise pattern, lets see our Asynchronous findControl and use it.

/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
"use strict";
WinJS.Namespace.define("MyApplication.Utils", {
        findControl: function (ctrlId) {
            return document.getElementById(ctrlId).winControl;
        },
        findControlAsync: function (ctrlId) {
            return new WinJS.Promise(function (completed, error) {
                var ctrl = document.getElementById(ctrlId);
                if (ctrl !== undefined && ctrl !== null) {
                    completed(ctrl.winControl);
                }
                else {
                    error();
                }
            });
        }
    });

this script is the exact script from our previous tutorial. The only addition here is the new function declared as findControlAsync. This function uses WinJS.Promise to create our findControlAsync. To call our function we use the following script

MyApplication.Utils.findControlAsync("lView").then(function (ctrol)
        {
		//write to console findControlAsync result is true when the control is found
            console.log("findControlAsync result is = ", ctrol !== null && ctrol !== undefined);
        }, function () { console.error("The specified control was not found in the DOM") });

Note "the lView string parameter is the control id for a winJS listView I have in my default html page"

So what does our call exactly mean?, this call simply calls the findControlAsync, if the call succeeds we use the control to print the specified message otherwise we print a message indicating "the specified control was not found in the DOM".

 

Tags: , ,

javascript | Windows 8 | WinRT

How to create a winRT javascript helper function

September 24
by Sammy Ageil 24. September 2012 22:11

In this tutorial we will write a static helper function to find an element in the Document Object Model “DOM” and return it as a valid a WinRT’s control “winControl”.
Our helper function is called findControl, it will find a winRT control by using its host's Id
Let's start by looking at our js file;

/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
"use strict";
WinJS.Namespace.define("MyApplication.Utils", {
        findControl: function (elementId) {
            return document.getElementById(elementId).winControl;
        }
    });

The first thing you will notice in our script is the presence of these reference path comments look a like.
  /// <reference path="//Microsoft.WinJS.1.0/js/base.js" />. These lines are not comments, they references and they only exists so Visual Studio.Net to provide us with its glorious intellisense. you can safely ignore them if you like.

The second new part is more interesting, our script file includes a “use strict”; directive, what is this use strict you say?
The “use strict”; directive is part of ecmascript 5  it can be applied to an entire script file or a function.
This feature is documented and thoroughly explained in Mozilla References And http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
The third part is the new way of defining a javascript namespace this is functionality only exists in WinRT. While there is nothing to stop you from defining namespace the natural way, this function is the preferred one when using winRT.
The last new part you will notice is the “.winControl”, this part a native function of the winRT ui.js.
The function simply uses the winControl property of the host control and return it as a valid winControl

Finally to use our function we need to call it like this

var lview = MyApplication.Utils.findControl("listviewCotrol"); //where listViewControl is the ID in the DOM.

of course you will need to reference the script file in your html just like you would do in any web page

Next time we will add an async function using javascript's promise pattern

Hope this helps

Tags: , , ,

javascript | WinRT

Create windows 8 shutdown logoff and restart using C#

September 18
by Sammy Ageil 18. September 2012 23:12

If you installed Windows 8 you probably noticed the effort it takes to shutdown, restart or logoff your computer.
In this tutorial, we will relieve ourselves from this effort by creating the power shortcuts, place them on Windows 8 Tiles and assign them hotkeys.
Let's start..

  1. The first thing to do is to create a visual studio project, I choose a console application for simplicity reasons.
  2. Right click on References and add the following two references from the COM tab "Interop.IWshRuntimeLibrary & Interop.Shell32"
  3. Click on each of the added references and in the property window set Embeded Interop Types to false as shown in the screen capture

  4. Open the program.cs, delete all of the program class content "only leave the class declaration"
  5. Type in the following snippet
    const string LOGOFF = @"%systemroot%\System32\shell32.dll,44";
            const string REBOOT = @"%systemroot%\System32\shell32.dll,176";
            const string SHUTDOWN = @"%systemroot%\System32\shell32.dll,27";
    
            static void Main(string[] args)
            {
                Console.WriteLine("Enter one of the options to add the shortcut or pres esc or any other key to exit");
                Console.WriteLine("Z to add all shortcuts");
                Console.WriteLine("S to add shutdown only");
                Console.WriteLine("R to add a restart only");
                Console.WriteLine("L to logg off only");
              
                var response = Console.ReadKey(true);
                switch (response.Key)
                {
                    case  ConsoleKey.R:
                        CreateShortCut("r",REBOOT);
                        Exit();
                        break;
                    case ConsoleKey.S:
                        CreateShortCut("s", SHUTDOWN);
                        Exit();
                        break;
                    case ConsoleKey.L:
                        CreateShortCut("l", LOGOFF);
                     
                        break;
                    case ConsoleKey.Z:
                        CreateShortCut("s", SHUTDOWN);
                        CreateShortCut("r", REBOOT);
                        CreateShortCut("l", LOGOFF);
                        Exit();
                        break;
                    case ConsoleKey.Escape:
                        Exit();
                        break;
                    default:
                        Console.WriteLine("Invalid entry, restart the application and try again");
                        Console.ReadLine();
                        break;
                }
            
            }
            static void Exit()
            {
                Environment.Exit(0);
            }
            static void CreateShortCut(string option, string iconPath)
            {
                WshShell shellClass = new WshShell();
                var linkPath = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
                var shortCutDescription = Description(option.ToLowerInvariant());
                var shortcut = (IWshShortcut)shellClass.CreateShortcut(String.Format("{0}\\{1}.lnk", linkPath, shortCutDescription));
                shortcut.IconLocation = iconPath;
               
                shortcut.WindowStyle = 1;
                shortcut.TargetPath = @"%systemroot%\System32\shutdown.exe";
                shortcut.Arguments = option == "l" ? "-l" : string.Format("-{0} -t 0", option.ToLower());
                shortcut.Hotkey = CreateHotKey(option);
                shortcut.Description = shortCutDescription;
                shortcut.Save();
            }
            static string CreateHotKey(string shortcut)
            {
                switch (shortcut)
                {
                    case "r":
                        return "Ctrl+Alt+R";
                    case "s":
                        return "Ctrl+Alt+S";
                    case "l":
                        return "Ctrl+Alt+L";
                    default:
                        return string.Empty;
                }
            }
            static string Description(string shortcut)
            {
                switch (shortcut)
                {
                    case "r":
                        return "Restart";
                    case "s":
                        return "Shutdown";
                    case "l":
                        return "LogOff";
                    default:
                        return string.Empty;
                }
            }
  6. Press F5 to start the application
  7. If you leave the code as is and press Z to add all power shortcuts, your shutdown hotkey will be Ctrl Alt S, reboot is Ctrl Alt R and logoff will be Ctrl Alt L
  8. Leave a comment if you need any assistance or you can download the code to play with

ShutDownConsole.zip (97.74 kb)

Tags: , ,

Windows 8

Deleting browser's IndexedDB files

July 03
by Sammy Ageil 3. July 2012 22:58

Today the team started working on an offline ready intranet application. The application requirement states "User should be able to track all activities and view his or her profile information excluding the password online and offline". fun eh? Well, our options were limited to Cookies, offline storage and IndexedDB.

  1. Cookies, are too restricting size wise
  2. Offline storage  is based on key, value pair (I know we can convert the object to a json string and store it but why we will have to prompt the user to increase offline storage size)
  3. IndexedDB is what I went with (it is part of the HTML5 standards even though its a draft)
 
Once we started writing code to set up the database schema, we noticed we couldn't delete the databases without going directory to the APPData folder and look for the browser's "Firefox and Chrome" specific directories. the idea of keeping two additional Windows Explorer windows open at all time was not a good solution.
 
The solution was to create a tool and share it with the team to do the clean up. here is the VS.Net solution IndexedDBFinderVSSolution.zip (3.00 mb)

 and the stand alone executable IndexedDBFinder.zip (5.26 kb)

Screen capture

IndexedDB Finder

 Hope it saves someone some time :-)

Stay tuned for the IndexedDB fun post coming soon.

Tags: , ,

HTML5 | MVC | Offline Applications

User friendly captcha in MVC

June 18
by Sammy Ageil 18. June 2012 08:32

 While we all agree on the need to have CAPTCHA validation components, most of us hate them. 

Most ASP.NET applications use Recaptcha which work quiet well, sometimes it’s too good, even a human being cannot read it.
Others it just spits out some no so user friendly words for the users to validate.

Have a look

Imagine how a user would feel if asked to type in one of the words listed on CAPCHA’s shown on the previous link. Some would say, no big deal, users can regenerate the CAPTCHA if they can’t read or don’t like the challenge words/characters. For those I would highly recommend a web usability book called “Don’t make me think”.

For an ASP.NET web form solution, please see Phil Haak’s honeybotcaptcha control.

To apply the same idea using MVC, I came up with this solution.

The solution utilizes MVC’s ActionFilterAtteribute to perform the validation.

Enough talking and let’s see the code.

First, here is our big helper method.
 

 

public static HtmlString Captcha(this HtmlHelper htmlHelper)

        {

            string captchainput = string.Format("<input type=\"{0}\" name=\"{1}\" value=\"{2}\" style=\"{3}\"  />", "text", "Captcha", string.Empty, "display :none;  speak: none;");

            return new HtmlString(captchainput);

        }

Two things to notice from this code, 

  1. Our input always has an empty value
               
    • Display is set to none to hide it from humans “spam bots ignore css”
    • Speak is set to none to avoid confusing screen readers
  2. The inline style sets both display and speak to none.

Second, our Filter 

public class ValidateCaptcha : ActionFilterAttribute

    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            base.OnActionExecuting(filterContext);

              var captcha = filterContext.HttpContext.Request.Form["Captcha"];

      if(!string.IsNullOrEmpty(captcha))

          

            ((Controller)filterContext.Controller).ModelState.AddModelError("", "SPAM SUCKS");



        }

      
    }

Since the solution utilizes an AtionFilter, this code will only run when a control action is marked with 

[ValidateCaptcha]

Third, our view we would use our helper like this.

@using (Html.BeginForm("create","index", FormMethod.Post,null)) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Comment</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Subject)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Subject)
            @Html.ValidationMessageFor(model => model.Subject)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Message)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Message)
            @Html.ValidationMessageFor(model => model.Message)
        </div>
        @Html.Captcha()
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

     

And finally our ActionResult 

[ValidateCaptcha]

        [HttpPost]

        public ActionResult Create(Comment model )

        {

            if(TryUpdateModel(model))

            {

                return View(model);

            

            }

            return View("index");

        }

 

 A spam bot will end up seeing this page when the form is submitted.

Tags: ,

Asp.Net | C# | Captcha | MVC

Get remote IP address in .Net

June 07
by Sammy Ageil 7. June 2012 21:53

Sometimes we need an application to identify the machine’s IP address.
This is an easy task if the machine uses a single Network card and is a standalone machine.

If these were your requirement, the following code will return the machine’s IP Address

var currentIp = (
                       from address in Dns.GetHostEntry(Dns.GetHostName()).AddressList
                       where address.AddressFamily== AddressFamily.InterNetwork
                       select address.ToString()
                ).FirstOrDefault();

But what if the machine is a server with multiple NICs and part of a network connected via a hub or a router?
if you use the previous code snippet, the returned IP Address will not be the remote IP Address. What you will get is the NAT address “something like 192.168.2.10”

The framework does not have a utility or method to provide us with the remote address.
in order to retrieve this type of data, we need to be creative or sneaky if you like.
the only way I found to be valid and doesn’t have any dependencies on external services is using the ole ping command.

The ping command uses different switches; we will be using two of them, “ping google.com -r x –n x”
when the x represent a numeric value.
if you run the following command from the command window, the result will be

C:\Users\sammy>ping google.com -r 1 -n 1
Pinging google.com [74.125.226.68] with 32 bytes of data
Reply from 74.125.226.68: bytes=32 time=25ms TTL=55
    Route: 70.50.75.187
Ping statistics for 74.125.226.68:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 25ms, Maximum = 25ms, Average = 25ms


the command explained,
ping google.com  and Record route for 1 hop one time only.

Given this data, we can use the following code to return the remote address.

public static string RemoteIP(string hosttoping="google.com")
        {
            string ipAddress = string.Empty;
    string pingResult = string.Empty;

            using (var pingProcess = new Process())
            {
                //the command arguments
                    string param = String.Format("/c ping -r 1 -n 1 {0}", hosttoping);
                    pingProcess.StartInfo = new ProcessStartInfo("cmd.exe", param)
                                                {RedirectStandardOutput = true, UseShellExecute = false};
                    pingProcess.Start();
                    pingResult=pingProcess.StandardOutput.ReadToEnd();
                    // Set the regular expression to match IP addresses
                    string ipPattern = @"Route: \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";

                 
                    var regex = new Regex(ipPattern, RegexOptions.Compiled);

                    var match = regex.Match(pingResult);
                    if (match.Success)
                    {
//remote the word Route from the string and return only the IP Address
                        ipAddress = match.Value.Replace("Route: ", string.Empty);
                    }
            }


            return ipAddress;
        }

 

Tags: ,

C#

Using the mobile ready project template in vs.net

July 12
by Sammy Ageil 12. July 2011 18:05

The Mobile Ready HTML5 MVC project template is a template I created to speed up my team's jQuery mobile learning curve and development using the API.
While some of the team members had lots of experience using jQuery, no one have ever used the mobile version.

The template setup is easy.

1. Download the template extension from visualstudiogallery.com
2. Create a Mobile ready project using file, new, project "watch Video for more help"

Points of interests:

               1. In the project's Web.config App settings

 

<add key="HasMobileSpecificViews" value="true"/>
<add key="MobileViewsDirectoryName" value="M"/>

 

The HasMobileSpecificViews setting is used to determine if the application has mobile specific views.

When set to false, all mobile views will be ignored.

The MobileViewsDirectoryName is used to determine the location of the application mobile views,

the default value is set to M.

                2. Due to the complexity of debugging client script on mobile devices.

I created an extension method "IsSupportedMobileDevice" in the Application helper class.

We used this method to enable browsing the mobile views in firefox and debug client

 scripts using firebug.

To enable client script debugging using firefox and firebox modify this method to return false as shown in the comment

 

public static bool IsSupportedMobileDevice(this HttpRequestBase request)
        {
            //return true to enable debugging client script in firebug
            bool isMobile = request.Browser.IsMobileDevice;
            string userAgent = request.UserAgent.ToLowerInvariant();

            isMobile = isMobile || (userAgent.Contains("iphone")
                || userAgent.Contains("blackberry")
                || userAgent.Contains("mobile")
                || userAgent.Contains("windows ce")
                || userAgent.Contains("opera mini")
                || userAgent.Contains("palm")
               || userAgent.Contains("fennec")
                );
            return isMobile;

        }

 

We are using iBBDemo to emulate iPhone and iPad devices, you can download this tool from http://www.puresimstudios.com/ibbdemo/

Tags: , , ,

Execute multiple Tasks in .Net 4.0

June 14
by Sammy Ageil 14. June 2011 16:17

Yesterday I exaplained one of many ways to execute multiple threads and be notified when all threads have executed.
See http://www.sammyageil.com/post/2011/06/13/How-to-detect-multiple-threads-completion-in-Net.aspx
Today we will see similar using System.Threading.Tasks namespace.

lets get to the code.

 

public static Random random = new Random();
        static void Main(string[] args)
 {
List<Task> tasks = new List<Task>
            {
                Task.Factory.StartNew(()=>FirstJob("A")),
                Task.Factory.StartNew(()=>SecondJob("B")),
                Task.Factory.StartNew(()=>ThirdJob("C"))
            };
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("--------------ALL JOBS COMPLETED---------------");
            Console.Read();
       }

 

here is the code to simulate long running tasks

 

public static void FirstJob(string s)
        {
            Console.WriteLine("First Job started at {1}, With param recieved as {0}", s, DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("First Job Completed at {1}, With param recieved as {0}", s, DateTime.Now);
        }
        public static void SecondJob(string s)
        {
            Console.WriteLine("Second Job started at {1}, With param recieved as {0}", s, DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("Second Job Completed at {1}, With param recieved as {0}", s, DateTime.Now);
        }
        public static void ThirdJob(string s)
        {
            Console.WriteLine("Third Job started at {1}, With param recieved as {0}", s, DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("Third Job Completed at {1}, With param recieved as {0}", s, DateTime.Now);
        }

 

Hint: if you are not familiar with Tasks namespace, comment Task.WaitAll(tasks.ToArray()); and run the console app again.
  Console.WriteLine("--------------ALL JOBS COMPLETED---------------"); will be the first line to execute.

Tags: , ,

How to detect multiple threads completion in .Net

June 13
by Sammy Ageil 13. June 2011 13:21

when working with multiple t threads, sometimes we need to know when all threads have completed. while there are multiple ways to achieve this. Here is one way I found to be easy.
The key class used to achieve the task is WaitHandle  . lets start with a console app in C#

 

public static Random random = new Random();

        static void Main(string[] args)
        {
          
            //Initialize the WaitHadlers
            List<WaitHandle> waitHandles = new List<WaitHandle>();

            var manualResetEvent = new ManualResetEvent(false);
            waitHandles.Add(manualResetEvent);
            var taskOne = Task.Factory.StartNew(() => new Thread(JobOne).Start(manualResetEvent));
            taskOne.Wait();

            manualResetEvent = new ManualResetEvent(false);
            waitHandles.Add(manualResetEvent);
            var taskTwo = Task.Factory.StartNew(() =>   JobTwo(manualResetEvent,"A") );
            taskTwo.Wait();

            manualResetEvent = new ManualResetEvent(false);
            waitHandles.Add(manualResetEvent);
            var taskThree = Task.Factory.StartNew(() => new Thread(JobThree).Start(manualResetEvent));      
            taskThree.Wait();

            var waitTask = Task.Factory.StartNew(() => WaitHandle.WaitAll(waitHandles.ToArray()));
            waitTask.Wait();
            Console.WriteLine("-----------------All jobs completed at {0}----------------", DateTime.Now);
            Console.ReadLine();
        }

 

 

Here is the methods JobOne, Jobtwo and JobThree

 

private static void JobOne(Object obj)
        {
            ManualResetEvent manualResetEvent = (ManualResetEvent)obj;

            // simulate a long runningt task
            Console.WriteLine("Job One started at {0} ",DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000)); // random 5 to 20 second delay
            Console.WriteLine("Job One Completed at {0} ", DateTime.Now);

            manualResetEvent.Set();
        }

        private static void JobTwo(Object obj,string a)
        {
            ManualResetEvent manualResetEvent = (ManualResetEvent)obj;

            // simulate some work:
            Console.WriteLine("Job Two started at {0} ", DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("Job Two Completed at {0} ", DateTime.Now);

            manualResetEvent.Set();
        }

        private static void JobThree(Object obj)
        {
            ManualResetEvent manualResetEvent = (ManualResetEvent)obj;

            // simulate some work:
            Console.WriteLine("Job Three started at {0} ", DateTime.Now);
            System.Threading.Thread.Sleep(random.Next(5000, 20000));
            Console.WriteLine("Job Three Completed at {0} ", DateTime.Now);

            manualResetEvent.Set();
        }

You can achieve the same results using the Tasks namespace
See http://www.sammyageil.com/post/2011/06/14/Execute-multiple-Tasks-in-Net-40.aspx

Tags: , ,

MVC ActionLink with Image the easy way

June 03
by Sammy Ageil 3. June 2011 19:12

While reviewing some ASP.NET MVC code, I noticed a call to custom helper method with the sole purpose of creating an ActionLink with an image as the background. My initial thought was "Let's do a search a find out how many calls we have to this extension method".
The result was 22 times. When I asked the developer why create a helper method for something simple as this? I got the following response

1.     Extension methods are cool

2.     Cannot think of another way to achieve the same results other than writing the href tag and embedding an img tag within the href tag

3.      If I were to choose the above (bullet 2), refactoring will be painful

I didn't want to argue the "coolness" of extension methods so I ignored the first point. Now for point 2 and 3 we can use CSS to achieve the same results.

.imageAction
{
display: block;
background: url(../content/Images/buy_32.png) no-repeat;
}

 

The MVC call using the razor engine

 

@Html.ActionLink("Buy", "Buy", null, new { title ="Buy", @class = "imageAction" })

I am hoping he meant refactoring the background image, maybe replacing the image with a new one; we can do that by changing the CSS class in one place, the rest should stay intact.


Why over complicate things?

Tags: , ,