Using the mobile ready project template in vs.net

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/

[youtube:4k1LzJ7joi8]

Tags: , , ,

Execute multiple Tasks in .Net 4.0

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

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

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: , ,

IsString C# and VB.NET Extension method

by Sammy Ageil 28. May 2011 21:19

Here is a quick and dirty regex based IsString() .Net extension method.

C# version

 

public static bool IsString(this object word)
        {
            return word == null ? false : Regex.IsMatch(word.ToString(), @"^[A-Za-z]+\Z");
        }

 

VB.Net version

<System.Runtime.CompilerServices.Extension> _
Public Shared Function IsString(word As Object) As Boolean
	Return If(word Is Nothing, False, Regex.IsMatch(word.ToString(), "^[A-Za-z]+\Z"))
End Function
 

 

The method will match strings only no spaces or other characters will be matched

Enjoy

Tags: , ,

IsNumeric .Net extension in C # and VB.NET

by Sammy Ageil 27. May 2011 11:10

Here is a quick and dirty IsNumeric extension method in C#. the method uses Regex to determine the result

C# version

public static bool IsNumeric(this object number)
        {
            return number == null ? false : Regex.IsMatch(number.ToString(), @"^[-+]?[0-9]+(\.[0-9]{1,2})?\Z");
           
        }

 

VB.NET version

<System.Runtime.CompilerServices.Extension> _
Public Shared Function IsNumeric(number As Object) As Boolean
	Return If(number Is Nothing, False, Regex.IsMatch(number.ToString(), "^[-+]?[0-9]+(\.[0-9]{1,2})?\Z"))

End Function
 

 

The pattern will match -##.##, +##.## ,##.## and #.#

 

Enjoy :-)

Tags: , ,

Post strongly typed model with jQuery ajax and ASP.NET MVC 3.0 and json

by Sammy Ageil 15. May 2011 15:47

Today I needed to post a strongly typed model using jquery and MVC 3.0 using razor engine.

My first thought was this should be easy, just hijack the submit button and send the request. well to my surprise, I was wrong :-)

The post was processed OK but my model didn't have ant of its properties populated.all of model's properties were null

The solution was to hijack the form's submit event and post the serialized form using jQuery's ajax function.

Note, the $(this).serialize() call in the body of the ajax function.

HTML and javascript

 

<form id="frmCreateUser" action="" method="post" >
    
    <div class="bordered" id="UserForm">
        <fieldset>
            <legend>User Information</legend>

           
                @Html.LabelFor(m => m.UserName, "UserName:")
                @Html.TextBoxFor(m => m.UserName, new { @class = "text-box" })
                @Html.ValidationMessageFor(m => m.UserName) <br /> 

                @Html.LabelFor(m => m.Password, "Password:")
                @Html.PasswordFor(m => m.Password, new { @class = "text-box" })
                @Html.ValidationMessageFor(m => m.Password) <br />

                @Html.LabelFor(x=>x.Email,"Email:")
                @Html.TextBoxFor(x=>x.Email)
                @Html.ValidationMessageFor(x=>x.Email)<br />


                <input id="createButton" type="submit" value="Create" />
           
        </fieldset>
    </div>

 

<script type="text/javascript">
        $(document).ready(function () {
         
            $("#frmCreateUser").submit(function (event) {
               
                $.ajax(
                {
                    url: '@Url.Action("CreateUser", "dashboard",new {area="Security"})',

                    dataType: 'json',
                    data:$(this).serialize(),
                    type:'POST',
                    success: function (result) {
                        
                        alert(result);
                    },
                    error: function (xhr) {
                        alert(xhr.statusText);
                    }

                });
                event.preventDefault();
            });
        });
    </script>

 

here is my action.

[HttpPost]
        public JsonResult CreateUser(User model)
        {
            bool isSuccess=false;
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
            return Json(createStatus.ToString(), JsonRequestBehavior.AllowGet);
        }

Tags: , ,

Request is not available in this context exception in Global.asax's Application_Start IIS 7 Integrated mode

by Sammy Ageil 8. May 2011 23:11

Recently we started upgrading an old Asp.NET 2.0 application to Framework 4 and IIS 7. Upgrades went OK and the application started working on test environment hosted on an older Windows 2003 server. Once the application went to production we started seeing "Request is not available in this context".
We knew the application calls a licensing service in the Application_Start() event.

obviously this exception related to IIS7 because the application worked without any issues on the test environment. After some research we found out this issue is related to IIS 7 Integrated mode. The solution was easy. I created a static constructor in global.asax and used a static readonly variable to use in the Application_Start() event.

Here is the code

static readonly HttpRequest initialRequest;
        static MyApplication()
        {

            initialRequest = HttpContext.Current.Request;
           
            
        }

    protected void Application_Start()
        {
      //Get the IP Adddress of the host to send for the licensing service
      var domainUrl= initialRequest.ServerVariables["LOCAL_ADDR"];
            
        }

I hope this can help some

Tags: ,

Poorly named domains - a must see

by Sammy Ageil 7. May 2011 07:48

This page is a must see

http://www.blabla.co.za/2011/04/01/top-list-7-poorly-named-websites/

That's why we should think first then act?

Tags:

Get all IP Addresses in .Net

by Sammy Ageil 9. April 2011 06:02

For licensing reasons, we needed to get all of the IPV4 IP Addresses of the server hosting one of our products.
The major question I had to answer what if the server is configured using IPV6?
Here is what I came up to solve this issue.
I hope it help someone else the time to resolve this issue.

First add the following namespaces

using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

Code

var ipv4 = NetworkInterface
           .GetAllNetworkInterfaces()
           .SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Where(nip => nip.IPv4Mask != null && nip.Address.AddressFamily== AddressFamily.InterNetwork ).Select(ip => ip.Address.ToString())).ToArray();

            var ipv6 = NetworkInterface
           .GetAllNetworkInterfaces()
           .SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Where(nip => nip.Address.AddressFamily == AddressFamily.InterNetworkV6).Select(ip => ip.Address.ToString())).ToArray();

            var allIPS = NetworkInterface
            .GetAllNetworkInterfaces()
            .SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Where(nip =>  nip.Address.AddressFamily == AddressFamily.InterNetwork || nip.Address.AddressFamily == AddressFamily.InterNetworkV6).Select(ip => ip.Address.ToString())).ToArray();

VS.NET version

Imports

Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation
Code
Dim ipv4 = NetworkInterface.GetAllNetworkInterfaces().SelectMany(Function(ni) ni.GetIPProperties().UnicastAddresses.Where(Function(nip) nip.IPv4Mask IsNot Nothing AndAlso nip.Address.AddressFamily = AddressFamily.InterNetwork).[Select](Function(ip) ip.Address.ToString())).ToArray()

Dim ipv6 = NetworkInterface.GetAllNetworkInterfaces().SelectMany(Function(ni) ni.GetIPProperties().UnicastAddresses.Where(Function(nip) nip.Address.AddressFamily = AddressFamily.InterNetworkV6).[Select](Function(ip) ip.Address.ToString())).ToArray()

Dim allIPS = NetworkInterface.GetAllNetworkInterfaces().SelectMany(Function(ni) ni.GetIPProperties().UnicastAddresses.Where(Function(nip) nip.Address.AddressFamily = AddressFamily.InterNetwork OrElse nip.Address.AddressFamily = AddressFamily.InterNetworkV6).[Select](Function(ip) ip.Address.ToString())).ToArray()
 

Enjoy

Tags: , , , ,

Month List

Powered by BlogEngine.NET 2.5.0.6 - Eco Theme by n3o Web Designers