Wednesday, September 05, 2012

Knockout Model and Validating "inner" Models

More and more technologies, projects and products are basing their foundation on MVC and MVVM principles. The reason is that it makes the project or product to be maintained easily without much headache. The latest trend in client based web development is also shifting towards MVVM model and the tool that is getting most widely used is the Knockout javascript library. It’s a great tool that eases binding making even the complex javascript tasks to be designed pretty easily like for example dynamically rendering design for multiple contacts and collecting details, etc..,

Basic Knockout Model Validation

Validating a basic knockout model is a straight forward task. We just have to use the extend method on the observable attributes and set the necessary parameters. Consider the following model:

function ClientModel (id, firstName, lastName, email) {
        var self = this;
        self.Id = ko.observable(id);
        self.FirstName = ko.observable(firstName).extend({ required: true, maxLength: 50 });
        self.LastName = ko.observable(lastName).extend({ required: true, maxLength: 50 });
        self.Email = ko.observable(email).extend({ maxLength: 50, email: true });

        self.save = function () {
            if (self.errors().length != 0) { //verifying the errors attribute using the count of errors
                self.errors.showAllMessages(); //displaying the corresponding error messages
                return; //returning the control providing user a chance to correct the issues
            }

            $.ajax({
                type: "POST",
                url: "Save",
                data: ko.toJSON(self),
                contentType: 'application/json',
                success: function (mydata) {
                    alert("Success");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("save method error status: " + xhr.status);
                    alert("save method error thrown: " + thrownError);
                }
            });
        };
};

$(document).ready(function () {
var clientModel = new ClientModel(1, "Hello", "World", "hell0@world.com");
clientModel.errors = ko.validation.group(clientModel); //setting up the errors attribute to the model to capture the validation error message
ko.applyBindings(clientModel);
});

The above is a basic model with validations added for the attributes using the extend method (More validation can be found here). The validation error messages are shown when the save method of the model is executed.

Deep Knockout Model Validation

Often we face situation where we will have a requirement for a complex model than the basic one. For example: our client may request us to design a solution to allow multiple contact numbers for a customer to be collected. In this case, the underlying model is changed as follows.

function Contact(id, phoneType, phone) {
        var self = this;
        self.ClientId = ko.observable(id);
        self.PhoneType = ko.observable(phoneType).extend({ required: true });
        self.Phone = ko.observable(phone).extend({ required: true });
};

function ClientModel (id, firstName, lastName, email, contacts) {
       var self = this;
       self.Id = ko.observable(id);
       self.FirstName = ko.observable(firstName).extend({ required: true, maxLength: 50 });
       self.LastName = ko.observable(lastName).extend({ required: true, maxLength: 50 });
       self.Email = ko.observable(email).extend({ maxLength: 50, email: true });

self.Contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (aContact) { return aContact; }));

       self.save = function () {
            if (self.errors().length != 0) { //verifying the errors attribute using the count of errors
                self.errors.showAllMessages(); //displaying the corresponding error messages
                return; //returning the control providing user a chance to correct the issues
            }

            $.ajax({
                type: "POST",
                url: "Save",
                data: ko.toJSON(self),
                contentType: 'application/json',
                success: function (mydata) {
                    alert("Success");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("save method error status: " + xhr.status);
                    alert("save method error thrown: " + thrownError);
                }
            });
       };
};

$(document).ready(function () {
       var contacts = { new Contact(1, "Home", "1234567890"), new Contact(1, "Work", "9876543210") };
var clientModel = new ClientModel(1, "Hello", "World", "hell0@world.com", contacts);
clientModel.errors = ko.validation.group(clientModel); //setting up the errors attribute to the model to capture the validation error message
ko.applyBindings(clientModel);
});

The above is a also a model with validations added for the attributes using the extend method. The validation error messages excepts the contacts will be displayed when the save method of the model is executed. The reason is that we have not made the validation “deep” so the inner validations are not executed. In order to achieve this, we will have to include the following Knockout initialization block:

ko.validation.init({grouping: { deep: true }, messagesOnModified: false });

Adding the above line of code should make the inner validations work in most cases. But if it still doesn’t work, then we will have to add the errors attribute to the Contact model just like we have added for the ClientModel. The below listing shows the updated Contact model with errors attribute added:

function Contact(id, phoneType, phone) {
        var self = this;
        self.ClientId = ko.observable(id);
        self.PhoneType = ko.observable(phoneType).extend({ required: true });
        self.Phone = ko.observable(phone).extend({ required: true });

self.errors = ko.validation.group(self); //setting up the errors attribute to the Contact model to capture the validation error message
};

Having added the errors attribute to the Contact model, we also need to update the save method of the ClientModel to verify the errors collection attribute and return if in case there are errors. The updated save method is listed below:

self.save = function () {
       var errorExists = false;

if (self.Contacts().errors().length != 0) { //verifying the errors attribute from the Contact model
              self.Contacts().errors.showAllMessages(); //displaying the corresponding error messages
              errorExists = true; //set error flag to stop further processing
       }

if (self.errors().length != 0) { //verifying the errors attribute using the count of errors
              self.errors.showAllMessages(); //displaying the corresponding error messages
              errorExists = true; //set error flag to stop further processing
       }

if (errorExists) {
              return; //returning the control providing user a chance to correct the issues
       }

      
       $.ajax({
              type: "POST",
              url: "Save",
              data: ko.toJSON(self),
              contentType: 'application/json',
              success: function (mydata) {
                     alert("Success");
              },
              error: function (xhr, ajaxOptions, thrownError) {
                     alert("save method error status: " + xhr.status);
                    alert("save method error thrown: " + thrownError);
              }
            });
};

From the above updated save method, all the errors corresponding to the main model (ClientModel) and the child model (Contact) will be displayed.
Hope this helps!!!

Saturday, July 21, 2012

MVC ~ Transferring data from one page to another

Lot of times we would need to pass data from one page to another. The data could be a simple data or it can also be a complex data. In case of simple data, we can transfer using query string parameter and this does the job but when the size of the data is really big or if it is a complex type, then we need a different mechanism.

 

With MVC, we get the dictionary object to store the values at one end and retrieve it at the other end. These values are actually stored in session and lasts until the session terminates. Here is how we can make use of it:

 

//store the data to temp data dictionary. Data can be of any type

TempData[“myUniqueKey”] = value;

……

……

//retrieve the data from temp data dictionary.

if (TempData.ContainsKey(“myUniqueKey”))

myComplexData = TempData[“myUniqueKey”] as MyComplexData;

 

Happy Programming!!!

Sunday, July 15, 2012

Resolving HTTP Connection Timeout with Android applications

Response time of any application greatly matters especially those dealing with network operations. Sometimes the response from the server is reasonable but at times servers get busy and takes much time in responding. In such situation, we generally set timeout (in the range of 20-30 seconds) for method execution and handle the operation accordingly. This range of timeout is fair for web application but coming to mobile devices the response time has to be much quicker in the range of 3-5 seconds.

We define the connection timeout as follows:

HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);

Here in the above snippet the connection timeout is set to 3000 milliseconds or 3 seconds. But executing the operation, we will notice that the execution does not return after 3 seconds though set rather it waits for a long time. In order to resolve this issue, along with setting the connection timeout, we also need to set the socket timeout as follows:

HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);

Now executing the operation, we will notice that the execution of code block returns in 3 seconds.

Hope this solves your problem…
Happy programming !!!

Thursday, July 12, 2012

Eclipse build error: The project was not built since its build path is incomplete. Cannot find the class file for xxxxx. Fix the build path then try building this project

We are creating a project in Eclipse studio, building the project and it executes. Everything goes fine and smooth. Next time we open the Eclipse studio and see red cross mark error beside our imports on basic java class references. To be more specific, we get the following issue:

The project was not built since its build path is incomplete. Cannot find the class file for xxxxx. Fix the build path then try building this project

Here xxxxx can be any of the java class file. We wonder why we get this and that it didn’t happen when we worked on the project just before Lunch!!! Annoying huh.. Ok so what is the problem and how to get rid of this ASAP? Well…the problem is with the reference of java library in our project. Sometimes Eclipse loses the reference path and require us to help it out. And how do we do that…here are the steps:

1.       Right click on the project from the Project Explorer and select “Properties”. Alternatively we can also select “Properties” from the Project menu.
2.       From the Properties dialog, select “Java Build Path” from the left side view.
3.       Clicking the “Libraries” tab we can see the libraries referenced in the project and will also see that something is wrong with JRE library referenced in the project as shown below:


4.       Next we select this library and remove it. Then we click the “Add Library…” button on the right and then select the “JRE System Library” and then click the “Next” button as shown below:


5.       By default, we will see that “Workspace default JRE” is selected as shown below. We can leave this as is and then click the “Finish” button


Now that we have the JRE library referenced to the project, we should see the error go away. But sometimes not. In this case, we do the regular clean-up of the project as follows:

1.       Project Menu -> Clean

2.       Right click on the project from “Project Explorer” and “Refresh”

3.       Right click on the project from “Project Explorer” and under "Android Tools" click “Fix Project Properties”

4.       May be even restart Eclipse if the above 3 steps doesn’t work and then repeat the 3 steps after restarting

Finally we see the error go away. Whew….
Hope this helps reduce your headache and…

Happy Programming!!!


Tuesday, July 10, 2012

Resolving ~ uncaught exception: [CKEDITOR.editor] The instance "myCKEditor" already exists.

Having added the CKEditor successfully to our web application, we see that it loads fine but during post-back we get a javascript error message as

uncaught exception: [CKEDITOR.editor] The instance "myCKEditor" already exists.

The error states about the existence of the CKEditor in the browser. So, we have to get rid of the ones that already exists using the following method:

<script language="javascript" type="text/javascript">
    if (CKEDITOR.instances['myCKEditor']) { delete CKEDITOR.instances['myCKEditor'] };
    if (CKEDITOR.instances['myCKEditor']) { CKEDITOR.instances['myCKEditor'].destroy(); }
</script>

The above code will remove the existence of the ‘myCKEditor’ editor from the browser memory and recreates it thereby resolving the issue.

Happy Programming!!!

Sunday, July 08, 2012

Delivering Compressed and Combined files for MVC 3 applications

It is very difficult to stay in the race without delivering application that performs “The Best” in the web world. To help us be in the race, we have lot of resources available in the internet to search for and plug in to our web application to gain optimal performance. One such tool is Squish It.

SquishIt is a framework for ASP.NET web application that compresses and combines javascript and css files. There are lot more options available with the SquishIt framework, but let’s walk-through the quick process of setting up the framework for ASP.NET MVC 3 application to compress and combine the css and javascript files.

Ok here we go…

1.       Download the latest framework from the GitHub from the following location: https://github.com/jetheredge/SquishIt/downloads

2.       Extract the zip file and reference the SquishIt.Framework.dll and SquishIt.Mvc.dll in your MVC application.
Note: If the dlls are not available in the bin folder of the extracted zip file, then you will have to open the solution in VS and built it (in release mode) and then reference the dlls in your MVC application.

3.       Next open the page (cshtml) where you have references to javascript and css files

4.       Add the following library references at the top of the cshtml page:

@using SquishIt.Framework
@using SquishIt.Mvc

5.       Next we have to transform the code that references the css files from:

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
       <link href="@Url.Content("~/Content/ jquery.alerts.css")" rel="stylesheet" type="text/css" />
       <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />

                to

                @(Bundle.Css()
            .Add("~/Content/Site.css")
            .Add("~/Content/jquery.alerts.css")
            .Add("~/Content/bootstrap.css")
            .ForceRelease()
            .MvcRender("~/Content/Site_#.css")
       )

6.       And then we transform the code that references the javascript files from:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>

                to           

       @(Bundle.JavaScript()
            .Add("~/Scripts/jquery.validate.min.js")
            .Add("~/Scripts/jquery-ui-1.8.11.min.js")
            .Add("~/Scripts/MicrosoftAjax.js")
            .ForceRelease()
            .MvcRender("~/scripts/combined_#.js")
)

And that’s it! Go ahead and run your application. Open the Firefox YSlow plugin and verify the number of requests for the css and javascript files. It should be two. Also, you would find that the size of the output file is a reduced one.

Happy programming!!!


Monday, July 02, 2012

MVC 3 Get the Html ID of a control for jQuery calls

jQuery makes the life of web developer simpler by addressing most of the browser compatibility issues. Every developer wants to make use of jQuery library to leave (most of) the browser related compatibilities to be taken care of by jQuery and concentrates on the actual requirements instead of worrying about other factors.

Integration of jQuery in any web project is as easier as it can be. The only important thing is to carefully pass the correct or appropriate id to jQuery calls. It is easier to view the generated source and hard code the corresponding ID to the jQuery calls. Ofcourse this would work and good for short term projects however for long term projects hard coding is not the best idea and nor is it recommended.

With traditional ASP.NET application, we use the following method to get hold of the Html ID that will  be generated for a control:

var id = $(“#<%=aspNetDotnetControl.ClientID %”>

This technique doesn’t work with ASP.NET MVC architecture. The following is one of the easiest way to do this in MVC 3:

1.       Define the extension method for the HtmlHelper class to return the fully qualified name for the given html (partial) field
2.       Define another extension method that just takes the fully qualified name and return the ID of the HTML element

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),
        System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static string NameFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            return htmlHelper != null ? htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)) : string.Empty;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"),
        System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static string IdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            return HtmlHelper.GenerateIdFromName(NameFor(htmlHelper, expression));
        }

                After defining the above two extension methods, we are now ready to make use of it in our cshtml files as follows:

                $('#@Html.IdFor(m => m.Service.Name)')

       And that’s it.

Saturday, June 23, 2012

Issue installing Packages from Android SDK Manager

I was interested in testing my android application using different packages and tools that is available from the Android SDK Manager. I clicked the SDK Manager and I was presented with the tools/packages already installed in my system as well as those that are not installed into my system.

I selected the packages, accepted the licensing of the package and clicked the “Install (x) Packages…” button. The download started but after few seconds I noticed that the download and installation of the selected package was not successful and I got the “Connection reset” message in the log window. I wasn’t sure what could be the issue but I was able browse the internet.

After having googled about this issue, my colleague recommended to try the installation on another machine. I tried in one my colleague’s machine and saw that the download of the package and the installation succeeded. Next what I did is copied all these packages from the my colleagues system under the folder: <android-sdk-directory>/add-ons and copied to my system’s <android-sdk-directory>/add-ons directory. Then I restarted my Eclipse studio and opened the SDK Manager. I noticed all these packages marked as installed.
Hope this helps someone solve this type of issue…

Thursday, June 21, 2012

Eclipse TFS Plugin Source control issue

At times when working with Team explorer, connecting to TFS Server from Eclipse studio can be a painful experience. Assume that you are working in a project and the source code is controlled from TFS server. Every changes are checked id and you are good for the day.

Next day you open the Eclipse studio ready to work on your project and notice that your project is not getting connected to TFS server (though all internet connectivity and your TFS server is up). You notice from the “Team” menu (right click your project to find this menu) that all command of TFS are disabled but “Return online…”. Clicking “Return online…” You will notice a window shows up displaying progress trying to connect to TFS server to associate source control binding to your project but fails in the first attempt but still continues and then displays the projects you have permission on. You select the project from the list of projects displayed and click the Finish button believing your project would now be associated but still no luck. You will find that all commands are still disabled under “Team” menu except “Return online…”. Annoying huh…

In this situation we can notice that if we double click the source control from the Team Explorer window, nothing will show up in the Source Control Explorer window…arrrr

We can try cleaning the project, restarting the eclipse studio, etc.., but nothing helps and we continue to face this issue and the Team Explorer will continue its struggle trying to connect to the TFS Server.

Ok so what’s the solution then…well...In this situation, instead of spending more time researching on this issue, we can perform the following actions to restore source code binding with TFS:

1.       Delete the project (remove only) from eclipse studio (Important Note: Not physical delete of the project from the system)
2.       Restart Eclipse studio and connect to TFS server. This time you will notice that it connects successfully without any issues.
3.       From the Source Control Explorer, right click on your project and click Import… button.
4.       Provide appropriate details in the “Import Project from Team Foundation Server” wizard and…

Things are back to normal….
Hope this help you solve your problem…

Saturday, June 16, 2012

Debugging Android Application directly from Android Mobile

We develop the android application and 75% of the time test using android simulator and witness the application working perfectly all right. We are happy and deploy the application to our android mobile (same target platform) and test verify. 90 to 95% of the time we see the application working alright with the actual device but sometimes we face issues.

What do we do next…we check back the application in simulator atleast once following the same scenario and see if we are able to replicate the issue. We see that the application works just fine in the same scenario in case of the simulator.

OK what next…what are our options…Well we have different mechanism to troubleshoot and the popular amongst those are as follows:

1.       Write to the log and then work through the application in the device with the same scenario reproducing the issue and then pull the log from the device and identify and solve the issue.
Yes but this type of troubleshooting is less preferable if the owner of the mobile is our pocket!!! This type of troubleshooting is more suitable when the user of our application lives in remote location.

2.       From the eclipse studio start debugging the application directly from the android device.
This is one of the easiest way to quickly troubleshoot and fix if we are facing the issue only when executing the application in the android mobile.

Ok…but how…well here is how you do this…

1.       From the Eclipse studio, pull open the “Windows” menu and select “Android SDK Manager” to view the list of target platform, additional libraries and Devices installed and/or available.

2.       From this list, expand the “Extras” folder and make sure “Google USB Driver” is installed as shown below in the screenshot. If this is not installed, then check mark the “Google USB Driver” and get this installed. Note: If any updates are available to the packages already installed, then they are selected by default. It is upto us if we want those updates or not.


3.       On your phone, click Settings > Applications > Development and make sure USB Debugging is on.

4.       After installing the “Google USB Driver”, connect the device to the system using the USB cable. A window opens up and prompt about installing drivers. Wait for it to complete.

5.       Open the command prompt window and navigate to the “platform-tools” directory under android-sdk directory. In my case it was (D:\Program Files\Android\android-sdk-windows\platform-tools)

6.       Type “adb devices” in the command prompt and this will list the devices installed. From this list you should see a serial number (some sequence of digits) and this happens to be the serial number of your android mobile. If you see so, then you are set to go.

7.       Now, instead of following the regular way of executing/running the application, this time it will be different. Right click on your project and from the context menu select Run As > Run Configurations…

8.       From the “Run Configurations” window, click the “Target” tab and select the “Manual” option from the “Deployment Target Selection Mode” panel as shown below


9.       Now click the “Run” button from the “Run Configurations” window and you will be prompted with the “Android Device Chooser” window.

10.   From the “Android Device Chooser” window, select “Choose a running Android device” option and then select the serial number (this will match with the serial number that displayed in the command window) and click the “OK” button.

11.   This time the application (apk file) is loaded directly in the android mobile and you can follow the same mechanism to debug it (Setting breakpoints and so on)

Hope this helps troubleshooting your issue…

Happy Androiding…

Saturday, June 09, 2012

Simulating an Incoming Call in the Android Simulator

At times, when developing the application or after developing the application, we are interested to test and break our application with all possible ways we can so that end users don’t end up facing such issues. One such scenario that we possibly miss out while testing our application using simulator is when a call arrives and our application is active.

This scenario is easy to simulate in the android simulator and this is done as follows:

1.       Start the Android Simulator and we can notice the number that is displayed on the title bar (as showing using the arrow mark in the screenshot below). In this case it is 5554.


2.       Open the command prompt window and type the following command to start the telnet session to localhost with port number as the number identified in the above step i.e., 5554

telnet localhost 5554

3.       This will open the telnet command session to the simulator. In this session, we can type help command and this will display all possible actions that we can perform on the simulator.


4.       From the displayed list of commands, we are interested in performing an incoming call to the simulator. The command is gsm and to know the syntax we type the following command:

help gsm

This command will display all sub-commands that can be used as part of gsm operation and they are as follows:


5.       From the above list, we are interested in the gsm call sub-command and this can be issued as follows:

gsm call 9999999999

here we can use any 10 digit number and not less or more. Issuing this command we can see an inbound call in the simulator as shown below:


                This helps us by providing a new level of testing using the android simulator and not depend on android devices in such scenarios.

                Happy Androiding…

Wednesday, June 06, 2012

Eclipse displaying error icon on Android Project

When working with Android Project files, sometimes we work directly from within Eclipse studio and sometimes outside of the studio. Assume that in one our android project, we are in need of one complex functionality to be performed. We Google and get hold of java source that does exactly what we require. So, we go ahead and download the java source file and add it using Eclipse studio to our android project. Having added that we notice a couple of errors in the downloaded java file. Instead of fixing it right away, we decide to fix at a later point of time and close the eclipse editor (assuming a long break time).

Returning back we learn that our R & D team have implemented the complex functionality and now we decide to get rid of the downloaded java file. We move to the src folder location using windows explorer and delete the file. (Note that this file was added using the eclipse studio and on top of that the downloaded file had errors). Now we open the eclipse studio and notice that there are no error icons displayed for any files but the android project.

We try the following ways to get rid of the error but all goes in vain:
1. Clean the project but still the error remains
2. Refresh the project but still the error remains
3. Fix Project Properties from Android Tools but still the error remains

The fix that worked in our case is removing the .metadata folder from the project root location. This folder seems to hold reference to all the files added using eclipse studio.

Friday, June 01, 2012

Android ~ Facebook login issue from Android application

When developing android applications that uses Facebook’s LoginButton to authenticate and authroize, there will be no issues running on the emulator. But when the same apk file (android installation file) is installed in an android device and executed it won’t work. The Facebook’s LoginButton, after clicking, progresses a while and returns back to the same screen taking us nowhere.

There could be several reasons for this behaviour but I have came across a couple of symptoms and was successful in addressing those:

1.       You might have not set the hashkey for your application in facebook or you might have messed up/changed your working android debug.keystore file locally in your system.

If you have not yet set the hashkey for your application, please generate hashkey for your application first, then set the hashkey for the facebook application. Here is the article that explains in a step by step manner to create your hashkey: http://hemant-vikram.blogspot.in/2012/05/generating-hashkey-for-android-facebook.html

At times when working with our android application we may sometimes use other’s debug.keystore file and replace our’s to see if some of our issues go away. Now if we generate the apk file and install in the device to test it out, we will notice this issue. To resolve we will have to re-generate hashkey and set that in the facebook apps.
2.       You might have missed the invocation of super method in the protected void onActivityResult(int requestCode, int resultCode, Intent data) method block

If you have missed, then add the following as the first line in your method block:
super.onActivityResult(requestCode, resultCode, data);

Edit: There is one another problem that I dealt with the signed apk file. I used the following steps to sign the apk file:
Right Click on the Project -> Android Tools -> Export Signed Application Package...
I provided the project name and clicked next and selected the keystore location path that has an empty space in it. Having generated the keystore file, signed apk file, generated the hashkey using the keystore file and setting it to facebook app settings page I was seeing that I was not able to get past the login screen. I was seeing a facebook progress dialog and after few seconds it disappears. I was running out of clues as what could be missing. Later along with my colleague, went thru the same process of generating the keystore and all that but this time without an empty space character in the path. We ran the apk file and tried the facebook signon and bingo. It worked!!!

Hope this helps you to resolve your problem and importantly save some time…

Happy Androiding

Wednesday, May 30, 2012

Eclipse & TFS ~ Ignoring file from commit

The TFS plugin for Eclipse doesn’t have a direct way to support ignoring the files from committing directly from IDE just like SVN does. For example, we prefer not to commit the “bin” directory. In order to ignore certain files or directory, we will have to create a file with the name .tpignore and save it in the root directory of the project. For example, to ignore bin directory and all of its files, the content of the .tpignore file should be as follows:

/bin/
/bin/.*

Generating Hashkey for Android Facebook Application Integration

Step 1


Step 2

Extract to a folder (in my case d:\android\openssl)

Step 3

Copy your debug.keystore file to the Java JDK folder where keytool.exe is present
In my case debug.keystore was in C:\Users\hemant\.android\debug.keystore
And
keytool.exe was in D:\Program Files\Java\jre7\bin folder

Step 4

Open the command prompt in the jdk bin folder where keytool.exe is and execute the following command:
keytool -exportcert -alias androiddebugkey -keystore debug.keystore > d:\android\openssl\bin\debugkey.txt
Provide password as android when prompted

Step 5

Navigate to openssl\bin folder (here we have debugkey.txt) in the command prompt and execute the following commands:
a.       openssl sha1 -binary debugkey.txt > debugkey_sha.txt
b.      openssl base64 -in debugkey_sha.txt > debugkey_base64.txt

That’s it! We are done. The debugkey_base64.txt contains the hashvalue. We need to copy paste this key to the Basic Settings page of our facebook application as shown below using the green arrow.

Friday, May 25, 2012

Android ~ Manually terminating an application or an activity

Best Practice recommended for Android development is to leave memory management to Android OS itself. What this means is when user moves out of our activity/application, we need not call the finish method to destroy it and release memory rather leave the application running without “finishing” it. When Android OS runs low in memory, it may decide to terminate the running activities.

Ok having said that and during development, assume we are interested to start the application fresh. In order to achieve this, we have four ways to do it and they are as follows:

1.       Restart the emulator    
This will take longer time but you can achieve your expectation

2.       Re-run the application 
This too will take longer time but comparatively less than that of restarting the emulator and you will achieve your expectation

3.       Stop Process from DDMS view 
This is quickest method and can be done only from the Eclipse studio
Eclipse Studio -> DDMS Perspective view -> Devices panel -> select process -> click stop button

4.       Force stop from Settings             
This is also the quickest and the safest method you can do directly from the Android device.
                Android Emulator -> Settings -> Applications -> Manage Applications -> Running Tab -> Select Application -> Force Stop

Android LogCat does not show anything !!!

Sometimes when working with Android applications, we may come across a situation where we will not see anything showing up the log no matter even if we select application specific log or all verbose messages. So what went wrong and how can this be fixed.

Here is the easiest way to fix this….


Open the DDMS perspective view. From the top left panel (Devices panel), select your application and that’s it…You will see the next moment logs get pouring in the logcat window.

Thursday, March 29, 2012

Deploying WCF Service on IIS 6.0

After deploying WCF service to IIS 6.0, we will notice that the page will not load when requesting http://mydomain.com/myservice.svc instead we would get 404 page not found exception. If you place a sample HTML file in the same directory and try to visit the page, the page will show up.

 

After googling, I learnt that after installing .NET Framework 4.0 Client Profile redistributable in the server, by default the ASP.NET 4.0 ISAPI extension is not enabled. This can be determined using the following command in the command prompt:

 

C:\>cscript c:\WINDOWS\system32\iisext.vbs /ListFile

 

Executing the above command will list all the extension files of IIS as

 

Status / Extension Path
------------------------
0  C:\WINDOWS\system32\inetsrv\httpodbc.dll
0  C:\WINDOWS\system32\inetsrv\ssinc.dll
0  C:\WINDOWS\system32\inetsrv\asp.dll
1  C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll
1  C:\WINDOWS\system32\MQISE.DLL
0  C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll

 

From the above listed extension files, you will see that the status is 0 for aspnet_isapi.dll of ASP.NET Framework 4.0. This means it is not enabled and this is preventing ASP.NET 4.0 processing your request. To enable the extension use the following command:

 

C:\>cscript c:\WINDOWS\system32\iisext.vbs /EnFile C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll

 

Once the above command is executed successfully, you should be able to see your WCF service coming up in the browser.