Sunday, August 10, 2014

Mobile Events

Recently I got opportunity to solve some issues on a webapplication which was supposed to run on desktop browsers and smartphone broswers both.

Since it was designed to work with mobile browsers also javascript was written to handle events which occurrs on mobile browsers.

So in this post I will share my experience of the same.

First problem assigned to me was that there was a dropdown which had different options like "Upcoming. Monthly, Past Week" So user has to select one option and based on that option filtered result list will be populated on screen.

So problem here was when ever user was trying to select any option from this dropdown in mobile website browser dropdown does use to open and close again so user was not able to select any option from that dropdown.

After looking into the code I found there one mobile browser event "touchstart" wired up and handler on this event code was written to just close this dropdown if its opened and this event was handled on document level or would say at top level like  $('html').on("touchstart", function () { // code to hide dropdown });

Also when I looked at dropdown code its onclick was properly wired up to handle click and selection of item but in case of mobile browsers this click event doenst use to fire instead touchstart use to fire before and its handler as defined above use to execute.

Also one point which learned was that in browsers click event is fired after 300ms delay since user touched the screen and touchstart has been fired. This delay has been kept just to check if user is actually going to click or just tap or do touchstart.

Then what I thought is that if I define a handler of touchstart at dropdown level then event will bubble up. And guess what it worked!!

I simply handled ontouchstart like onclick and copied handler in onlcik to ontouchstart now when user use to touch dropdown first touchstart of body used to fire defined at top level and then touchstart handler of dropdown fired which read the selection and filtered the list.

It was amazing learning for me since it was first time I was handling any mobile browser related issue.

Then I cam to know that there are plethora of mobile browser event like touchstart, touchmove, touchened and swip and etc. which one can handle to show desired results in mobile browsers.

Keeeeep listening!!

Friday, August 8, 2014

Best Practices UI:

1. Include the name of plugin at the top of page whether aspx or ascx. Like if I am using TouchSwipe jquery plugin it should be in comment at the top of the page so that any one who works on that page can look at that page and section to know plugins used in that.

// Plugin Used: TouchSwipe
// Plugin URL: http://labs.rampinteractive.co.uk/touchSwipe/demos/
// Used on:

Monday, July 21, 2014

Anonymous types were introduced in c#3.0 mainly to support LINQ. But it has find its good use in other places also like in HTMLHelper classes available in MVC.

Anonymous types are classed which do not have any name assigned to them. They only have properties defined and initialized then and there only.

Anonymous types are not public.

Friday, July 18, 2014

Extension Methods in c#


If one wants to extend a property of a class without modifying the existing code of class and compile it again one can use Extension methods concept which has been introduced in .Net 3.5 and C#3.0.

Previously if one wants to extend any particular class one had to inherit that class and create a new class and then give its implementation but using extension methods one can easily extend functionality of an existing class.

To explain the concept better I will take example. Lets say I have a following class BookMyShow which provided different methods to provide booking of different shows. On top of that this class is sealed which means this class cant be inherited further which means in future if I want to extend the functionality of this class I need to have either access to the source code of this class and then change the source code and compile it and then re-distribute the same..........ufffffffffffffffff.... lot of things to do.

namespace BookingPlaza
{
    class BookMyShow
    {
        public bool Book(string[] strppl)
        {
            /// ;;.......
            return true;
        }

        public int CancelBooking(string[] strArrBook)
        {
            return 0;
        }

        public DateTime GetShowBooking(string strWhen)
        {
            DateTime dtm = new DateTime();
            switch (strWhen)
            {
                case "AM":
                    {
                        DateTime.TryParse("10:00 AM",out  dtm);
                        break;
                    }
                case "PM":
                    {
                        DateTime.TryParse("10:00 PM", out dtm);
                        break;
                    }
                default:
                    DateTime.TryParse("03:00 PM", out dtm);
                    break;

            }

            return dtm;
        }
    }
}


Here comes the extension method to rescue.

Using extension method one can extend the functionality without source code access of the type to be extended

namespace ExtensionOfBMS
{
    static class ExtendBookMyShow
    {
        public static bool AdvanceBooking(this BookMyShow objBMS, DateTime timings)
        {
            return true;
        }

    }
}

As you can see above we extended the BookMYShow class but you might be wondering how this happened as I was so whole magic lies in the first parameter of the static method.

So first I will explain some syntax:

1. You need to create a static class having static method which will have extended functionality of the type to be extended.
2. Here comes the magic ;) . First parameter of the function should be type to be extended with this modified specified. As in this case it was BookMyShow.
3. Now where ever you want to use it you just need to put using directive. Like using ExtensionOfBMS.; and then you can access the extended method just like a instance method. As you can see in the screen shot AdvanceBooking is available as the extension method.




I would say amazing thing in this extension method implementation is that a static method is just available as instance method of the class when IL code is generated its actually static class call to static methods.

One more thing to point here is binding. If you create a same method as extension method which is already defined in the class and when you call this extension method it will always going to call the type implementation instead of the extended one. So for example I try to create one more extension method having same signature as already existing method compiler will always pick base class implementation.

Extension methods cant access the private methods or variables of the type or class which they are extending hence encapsulation is still intact in the design.

Keep extending!!!!!!!!!!!!!!!!!!!!!!!

Thursday, July 17, 2014

Impersonation - A holistic approach


What is impersonation?
When you try to execute current request in a different user's context instead of default one so that means you are impersonating.

Any windows process runs under a windows identity assigned to that process or a user account under which a process executes.So all permissions applicable to that identity as per that only process can execute.
 In Asp.Net the process runs under its ASPNET account. It has limited privileges. So if sometimes if we want to access resources which are not allowed to be accessed by default windows identity account under which that process is running we might have to use windows account credentials which have access to the resource to be accessed. So running the process under user provided authenticated account instead of default account is called impersonation.

Impersonation can significantly affect performance and scaling. It is generally more expensive to impersonate a client on a call than to make the call directly.

One can set impersonation through IIS at application or page level using Authentication feature.
There are scenarios where you dont want to set impersonation at application level and dont want to share your credentials with the site administrator for security reasons. In that case developer have option where he can change the windows account context which is be default Network Service or ASPNET account to user users domain account.

Following blog entry explains very clearly how to impersonate programatically. In this author has nicely explain the caveats also. http://weblog.west-wind.com/posts/2005/Feb/24/Using-programmatic-Impersonation-from-an-ASPNET-Page

As shown in this link one has to use interop to call Win32 LogonUser and CloseHandle functions. We have to use interop because .NET doesn’t provide the equivalent methods.

So.... IMPERSONATE!! ...but only when required :)!!

Wednesday, July 16, 2014

Awesome sayings

Scott Gu's BOss says:

"Guy walks into support, sez he needs a bigger mobile phone antenna. Doe he need a bigger antenna or does he really want better reception? Don't let your users dictate your solution with their statement of the problem."

Tuesday, July 1, 2014

base64 encoding and decoding

There are numerous instances where we want to serialize or de-serialize our object. In order to do the same different type of serialization techniques are being user like binary serialization, xml serialization, json serialization.

Recently I came across base64 serialization. Using this approach you can serialize your object as a base64 text string which means your object will be converted into string of characters represented by string.

Also same set of string can be de-serialized back to object.

This serialization can be used where we are not sure of the transport medium or protocol which will be used to transfer the data. Since text are treated as text so its safe to send it as base64 encoded object.

Encoding defined how a character is stored on your hard disk. Mostly Unicode encoding is used since it defines all the characters any language can have under the sky. So if we are using UTF for decoding or encoding that means you are able to interpret that character and now just to show the same you need fonts of that language.

Saturday, June 14, 2014

Asp.Net 4.5 Request Validation


In Asp.Net 4.5 there is a major improvement from point of view of security by RequestValidationMode.


Now with asp.net 4.5 requestvalidation for all HttpRequests (emphasis on "all") there is one flag set which checks all the request data for any malicious data which is hinting towards any malicious attacks in terms of XSS, or sql injection or any anonymous script block to be executed. 


Prior to 4.5 and 4.0 requestvalidation was available for only Page requests but now with 4.5 with all HttpRequests since nowdays httprequests comes in form RESTApi also and now Http is more prominent language of the web then the html istelf and web has started talking more in terms of Http then HTML.


In Asp.net 2.0 if we want to ever save any data with any special character like <b>Bob<./b> coming from any of the textbox we have to put whole page at risk by putting @ValidateRequest attribute to False but with asp.net 4.0 request validation you dont have to put whole page at risk since you can control it at request level, page level and yes not at control level also.


Asp.Net 4.5 has introduced concept of lazy request validation feature which says that request validation will be triggered only if the control which is accessed is code have some malicious code inside it like <b>Bob</b> if that control is not accessed it will not be validated thus improving upon the performance also since its last implementation.


In order to utilize lazy request validation feature of Asp.Net 4.5 one has to make following entry in web.config 


<system.web>
<httpRuntime requestValidationMode="4.5" />
</system.web>


Any value less then 4 for requestValidationMode like 3,3.9,2.5 will  make the requestValidation behave in 2.0 mode.Now if we want to access the value while taking benefit of request validation following the format to access the value. Using following we can access the unvalidated value of txtName.


Request.Unvalidated.Form["txtName"];


Another new feature which is very useful it ValidateRequestMode property which is set to Enabled by default so if for any control or set of control if you want that its values are not validated you can set ValidateRequestMode property to Disabled.


Thursday, June 5, 2014

img input type on click and return

Yday I faced a very strange problem

there is one user control who have a image button:

<input type='image' src=<URL of the image> onlick=removrrow(190,120)>

definition of removerow function was returning false.

<script>
function removerow(j,k)
{
...
...

return false;
}
</script>

Now the problem which was occurring was that when ever this image button gets clicked its was reloading the page. This image button was inside a usercontrol which loaded on a page which is opened inside a iframe which in turn is hosted on another page.

So this click was actually reloading the iframe which was opened on a click on another image button.

In order to stop this behavior I have returned false from removerow function since I have read in order to stop the page to submit or postback(you guessed it correct Asp.Net background) one can return false which I was already doing in this function but still it was reloading the iframe content.

My mind was gobbling arround what suddenly went wrong in this I tried lot of methods stoppropogation and cancelBubble= true but it was till posting the form.

In the end what I did I changed the way it was called from button click

Before:   <input type='image' src=<URL of the image> onlick=removrrow(190,120);>

After:    <input type='image' src=<URL of the image> onlick=javascript: return removrrow(190,120);>

And it worked. Yes putting return keyword as shown above made all the difference.

Happy Coding !!

Sunday, June 1, 2014

My Day 2 Day jQuery issues collections

Hi Folks!!

In this post I am trying to put my day 2 day jquery problems which I face and fix. Hope you will enjoy reading as much as I enjoyed collecting them for you:

Problem:

     Textbox which should only allow time in HH:MM format and textarea should be disabled till the value is        in correct format.

Solution:

$('#txtTimeInout').keypress(function()
{
var data  = $('#txtTimeInout').val();
var patter = /^\d{2,}:\d{2}:\d{2}$/

if(data.match(patter))
{
 $('#txtarea').prop('disabled',false);
}
else
{
 $('#txtarea').prop('disabled',true);
}
}
)

Problem:

There was a iframe inside a window and inside the page loaded in that window there was a javascript function SaveQuestion() which I was supposed to call from page outside the iFrame in which that window is hosted.

Solution:

So on page on a button click I had to call that method. Following was the solution I implemented/

$('#btnSave').click(function() {
 
   if( windows.frames.length >=1)
 {
    if(typeof(windows.frames[0].SaveQuestion) === "function")
    {
         //Here function is being reference as object so we need to call it using call()
         windows.frames[0].SaveQuestion.call();
    }
 }

});

Hope it will be of help to someone.

Happy Solving!!

Sunday, March 23, 2014

Get Ready for getting project

As an IT freelancer I have lots of opportunities where I need to sent a proposal to my client for his o her project and if they like it they call me for an interview.

Interview which I do with my client is usually online through Skype video chat or any of the collaboration tools.

This is my first and last chance to convince client about my understanding of the project and prove my capability that I am fully 100% fit to do his or her job and its not only safe but will provide value for the money which he is going to invest in me.

So the journey of winning client starts from moment I see a job post on oDesk,elance, or in email or any direct client.

I am hereby trying to put steps which I keep in mind while approaching any opportunity.

(Note: I will cover steps which I normally follow once I am going for the interview with client)

Client Question: Tell me something about your self?

Preparation Plan: Go through your resume or CV thoroughly make main points of your experience which reflects your capability. This gives a first impression. Be confident in your reply.

Go through the post details thoroughly. For eg client wants a POS system.

1. Go through job post thoroughly and go through any sample application if you haven't worked on any that kind of application and understand its features thoroughly.

2. Never give any estimate on call no matter how small it is. Just ask client "I will review the requirement and discussion will come back to you with the effort estimation."

3. Discuss about UI. No matter if client is not particular about UI do provide him UI in next 2-3 days event client says default theme.

4. Make internal activities or ToDos list.

5. Send status reports to clients daily. Don't try to fool client as one day truth prevails so be better to be sure to be open in communication in day one.

6. Provide feedback and value to the client suggest him new ways or methods through which you can add value to the customer business process.

7. If you are going to create a public facing site always make sure to ask client which is his or her site to which he wants to compete with or wants to look like.


These few steps can improve your confidence a lot.

Happy Reading......





 

Saturday, March 22, 2014

Special characters in action parameters : MVC handling


Special Characters in URL:

We have one scenario in which our complete sign up URL was containing encrypted key. Encrypted key was base64 encoded string which was generated by a crypto algorithm. This encrypted key was having special character like %,#,<,>,/,!,@&* any of them in one or more combinations.

So our sign up URL was forming something like this:

http://mysite/completesignup/ADSD$%@#$sdfdf?sdfsdf&^sdf++==/dfdfdfdf?/

And this link was sent to potential users in their email. So if user wants to complete its sign up operation.

But due to default request filter settings of IIS request pipeline user was getting error 404.1 Bad Request.

to fix this first step was to specify following in application web.config.


 <security>
            <requestFiltering allowDoubleEscaping="True" />
</security>

This fixed issue when ever we have double escaping

Another point to understand here is instead of passing special characters in action parameters we should pass it as query string.