Wednesday, February 27, 2013

Simple AsyncTask Example in Android


Any User interaction on any Android application should and must response with in 5 seconds, failure to which results in ANR Dialog. Yes "Application Not Responding" Dialog with 'Wait' and 'Force Close' inputs. Asynchronous operations can also be performed using Threads in accordance with Handler and messages to update UI about the action progress.

Here we will see how AsyncTask can be incorporated to perform Synchronous operations updated the progress of operation.

Three types are used by AsyncTask, in this case datatype is a String,

AsyncTask
First param String : This type of the parameters sent to the task upon execution.
Second param : This type of the Strings contains progress units published during the background operation.
Third param Result : This strings contains the result of the background operation.
Note : when no params are required use type void.

AsyncTask, that simplifies the creation of long-running tasks that need to communicate with the user interface.
The goal of AsyncTask is to take care of thread management.
Example :
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask {
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}

A class extend AsyncTask which triggers/perform long running tasks along side in override methods of AsyncTasks.You can specify the type, using generics, of the parameters, the progress values and the final value of the task.
  • The method doInBackground() executes automatically on a worker thread
  • onPreExecute() , onPostExecute() and onProgressUpdate() are all invoked on the UI thread
  • The value returned by doInBackground() is sent to onPostExecute()
  • You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread
  • You can cancel the task at any time, from any thread



Tuesday, February 19, 2013

Android : Stretch video to fill VideoView area


By default  Android will scale the video to fit the VideoView but keeping the video aspect ratio. That means that depending on the device's screen size there might be some black spaces left around the video the video since the it's not filling the screen.

VideoView doesn't provide an explicit way to specify the filling mode, you can achieve the same result by wrapping the video view in a Relative Layout and setting the VideoView alignments to match the parent's boundaries.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <VideoView android:id="@+id/videoViewRelative"
         android:layout_alignParentTop="true"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentRight="true"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
    </VideoView>
    
</RelativeLayout>

Reverse of string in objective C


- (NSString*)reverseString:(NSString*)string
{
   NSMutableString *reversedString;
   int length     = [string length];
   reversedString = [NSMutableString stringWithCapacity:length];
   while (length--) 
   {
      [reversedString appendFormat:@"%C", [string   characterAtIndex:length]];
   }
  return reversedString;
}

Thursday, February 07, 2013

Read Missed Call in Android

private void readMissedCallAPI() {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor cursor = null;
int MISSED_CALL_TYPE = android.provider.CallLog.Calls.MISSED_TYPE;
try{
cursor = getApplicationContext().getContentResolver().query(
Uri.parse("content://call_log/calls"),
projection,
selection,
selectionArgs,
sortOrder);
while (cursor.moveToNext()) {
String callLogID = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls._ID));
String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
String callDate = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE));
String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
String callNew = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NEW));
if(Integer.parseInt(callType) == MISSED_CALL_TYPE && Integer.parseInt(callNew) > 0){
Log.v("bharath", "Missed Call Found: " + callNumber);
}
}
}catch(Exception ex){
Log.v("bharath", "ERROR: " + ex.toString());
}finally{
cursor.close();
}
}

Note:
don't forget to add android.permission.READ_CONTACTS  in Androidmainfest.xml


Tuesday, February 05, 2013

HTTPHandler and HTTPModule in ASP.NET


Background

ASP.NET handles all the HTTP requests coming from the user and generates the appropriate response for it. ASP.NET framework knows how to process different kind of requests based on extension, for example, It can handle request for.aspx.ascx and .txt files, etc. When it receives any request, it checks the extension to see if it can handle that request and performs some predefined steps to serve that request.
Now as a developer, we might want to have some of our own functionality plugged in. We might want to handle some new kind of requests or perhaps we want to handle an existing request ourselves to have more control on the generated response, for example, we may want to decide how the request for .jpg or .gif files will be handled. Here, we will need an HTTPHandler to have our functionality in place.
There are also some scenarios where we are ok with the way ASP.NET is handling the requests but we want to perform some additional tasks on each request, i.e., we want to have our tasks execute along with the predefined steps ASP.NET is taking on each request. If we want to do this, we can have HTTPModule in place to achieve that.
So from the above discussion, it is clear that HTTPHandlers are used by ASP.NET to handle the specific requests based on extensions. HTTPModule, on the other hand, is used if we want to have our own functionality working along with the default ASP.NET functionality. There is one Handler for a specific request but there could be N number of modules for that.

Using the Code

Let us try to understand these two concepts by writing a small application for each. What we will do is we will try to have a mechanism where we can process the web pages with extension like .bspx and .cspx. Although this is a very unrealistic scenario, a similar concept is used to have search engine friendly URLs so perhaps it's not that realistic either.
Note: The HTTPHandler example here is just for demonstration purpose, I am not recommending the use ofHTTPHandlers for something that I am about to do now. HTTPHandlers should ideally be used to customize the handling of existing MIME types and not for serving search engine friendly URLs or non standard URLs.

Implementing the HTTPHandler

So with our problem definition, let us try to see how we can handle the request for .cspx pages using HTTPHandlers. First we need to have the handler class with us, so let us create the handler class.
public class CspxHandler :IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {

    }
}
The class should have a method ProcessRequest and a property called IsReusable. The property tells whether this handler can be reused or not and the method will be called whenever a request for that type comes. But wait, Where have we defined the type of request where this handler should be invoked? This can be defined either in IIS, if we have a handler common to all the sites running on that server or we can configure it in web.config file, if the handler is specific for a website. Let's do that in web.config file for now.
<httpHandlers>
    <add verb="*" path="*.cspx" type="CspxHandler"/>
</httpHandlers>
Here we registered our handler to specify that if any request for .cspx file comes, it should be forwarded to our handler.
Now, since we don't have any "real" files with .cspx extension, what we will do is we will handle the request for .cspxand in turn push the user to the corresponding .aspx file.
public class CspxHandler :IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.RawUrl.Contains(".cspx"))
        {
            string newUrl = context.Request.RawUrl.Replace(".cspx", ".aspx");
            context.Server.Transfer(newUrl);
        }
    }
}
Whenever a request for .cspx file comes, we will handle it in our handler and show the corresponding .aspx file instead. Let's see how it works.
Note: I have also changed the startup page name to Default.cspx but there is no page like that. I want my handler to handle that and show me the actual default page.

Important: I reiterate, This example is just for illustration. This is not how HTTPHandlers should be used at all.HTTPHandlers should ideally be used to customize the handling of existing MIME types.
Well the pages seems to be working fine and the user will see .cspx URL for his request. But there is one problem. The way we wrote our handler is not good to handle the postback. If I add a button on any of these pages and do a postback, the original URLs will be visible. So it is not a good solution to the problem but it sure demonstrated the way Handlers can be used.

Implementing the HTTPModule

How do we solve the problem we just saw. Well, our application needed URL rewriting and HTTPHandlers are a bad solution for that and should never be used for that. So perhaps the guys using this technique to have search friendly URLs should rethink their strategy. SO how can we solve this problem really.
Let us look at the requirement again, All we needed was to show the user URLs which are different than the real URLs and process the real URLs internally. So we don't need custom handlers, we are ok with the way ASP.NET engine is handling these requests but we need custom activities to be done during the processing phase. So it looks like we can solve it using HTTPModule.
So let's go ahead and write an HttpModule that will:
  1. Check for file extension on request.
  2. If it finds a .bspx extension it changes it to .aspx (or find real URLS if we are implementing search friendly URLs)
  3. It will pass the request to the default handler, since the page is still aspx.
  4. Once the response is generated, it will write back the original .bspx URL to users browser.
public class MyBModule : IHttpModule
{
    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        context.EndRequest += new EventHandler(context_EndRequest);
        context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
    }

    void context_AuthorizeRequest(object sender, EventArgs e)
    {
        //We change uri for invoking correct handler
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Request.RawUrl.Contains(".bspx"))
        {
            string url = context.Request.RawUrl.Replace(".bspx", ".aspx");
            context.RewritePath(url);
        }
    }

    void context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        //We set back the original url on browser
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Items["originalUrl"] != null)
        {
            context.RewritePath((string)context.Items["originalUrl"]);
        }
    }

    void context_EndRequest(object sender, EventArgs e)
    {
        //We processed the request
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        //We received a request, so we save the original URL here
        HttpContext context = ((HttpApplication)sender).Context;

        if (context.Request.RawUrl.Contains(".bspx"))
        {
            context.Items["originalUrl"] = context.Request.RawUrl;
        }
    }
}
Also we need to register our module so that it can be invoked, we will do that in our web.config file.
<httpModules>
    <add name="MyBModule" type="MyBModule" />
</httpModules>
And now let's run the application:

So here we solved the problem of URL reverting back to the original on postback. This is also the ideal way of doing that.

Points of Interest

In this article, we saw how we can implement a basic HTTPHandler and HTTPModule. We saw each of their roles in page processing frameworks. We worked on an example that tried to solve the URL rewriting first the wrong way by using HTTPHandler (but we understood how to write HTTPhandler) and then the right way of doing URL rewriting using HTTPModule (we got to understand that too.
The emphasis of this article was solely on understanding how we can have HTTPHandlers and HTTPModulesworking. The example is a little unrealistic and perhaps a little misleading too but since I made that point really clear, it shouldn't be a problem.
Before wrapping up, there is one last thing that we should know about handlers. It is also possible to handle the request asynchronously. ASP.NET provides a mechanism for creating asynchronous handler and then increases the performance of a web page (implements the IHttpAsyncHandler do that).

Wednesday, January 30, 2013

Basic Format Specifiers in iOS SDK

Format specifiers are the percent character, followed by a letter, such as %d or %f that tell NSLog or printf() to print the value or result of a variable, value, and/or expression.
Here is a list of Objective-C format specifiers:

%@Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.
%%'%' character.
%d, %DSigned 32-bit integer (int).
%u, %UUnsigned 32-bit integer (unsigned int).
%xUnsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f.
%XUnsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F.
%o, %OUnsigned 32-bit integer (unsigned int), printed in octal.
%f64-bit floating-point number (double).
%e64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent.
%E64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent.
%g64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.
%G64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.
%c8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit.
%C16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit.
%sNull-terminated array of 8-bit unsigned characters. Because the %s specifier causes the characters to be interpreted in the system default encoding, the results can be variable, especially with right-to-left languages. For example, with RTL, %s inserts direction markers when the characters are not strongly directional. For this reason, it’s best to avoid %s and specify encodings explicitly.
%SNull-terminated array of 16-bit Unicode characters.
%pVoid pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x.
%a64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent.
%A64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent.
%F64-bit floating-point number (double), printed in decimal notation.

Friday, January 25, 2013

Private assembly and Global assembly in DotNet



What is an assembly in .NET?

An assembly is a fundamental unit of any .NET application. It contains the code that is executed by CLR (common language runtime). I would like to limit the details to what is required to create and use an assembly. For more information about all nitty gritties of an assembly, please refer to MSDN documentation.
However, it is important to know a few details about assemblies before we delve into creating and using it.
  • An assembly contains name, version, types (classes and others) created in it and details about other assemblies it references.
  • An assembly may be either an executable file - .EXE or a dynamic link library - .DLL

Structure of an Assembly

The following is the content of an assembly. Each assembly contains first three parts. Fourth part may not be present in all assemblies. It is used primarily for localization - using resources according to the country or region.
  • Assembly Metadata or Manifest
  • Type Metadata
  • MSIL Code
  • Resources

Assembly Metadata or Manifest

This contains information about the assembly. Remember, assemblies in .NET are self-describing. They contain all the information that .NET needs to use them. Assembly metadata contains the following details of an assembly:
  • Assembly name
  • Version number of the assembly, which has four numbers in the format major.minor.revison.build
  • Culture - language assembly supports
  • Strong name - required only for global assemblies
  • List of files in the assembly. An assembly can be made up of multiple files
  • Type reference information - informs which type is in which file of the assembly
  • Information about referenced assemblies - Contains list of other assemblies referenced by this assembly. For each assembly referenced we have assembly name, version, culture and public key (if assembly is a global assembly)

Type metadata

This section of an assembly contains information about all classes, structure etc. created in the assembly.

MSIL Code

MSIL code of the assembly is placed in third part of the assembly. This MSIL is converted to native code by CLR at runtime.

Resource

This section contains messages and pictures used by assembly.

How to create an assembly in C#

The following are the steps to create a private assembly (by default all assemblies are private) using Visual C# 2005 Express Edition.
  1. Select File->New Project
  2. From Templates, select Class Library
  3. Enter name CounterLibrary
  4. A class library is created using a single class Class1
  5. Rename class to Counter and add the following code.
    namespace CounterLibrary
    {
        public class Counter
        {
            protected int v = 0;
            public Counter(int v)
            {
                this.v = v;
            }
            public int Value
            {
                get
                {
                    return v;
                }
            }
        }
    }
    
  6. Save project using File->Save All. When prompted to enter location for project, select the folder where you want to save your project. I use c:\csharp. Do not select checkbox forCreate directory for solution
  7. Build (not run) the project using Build->Build Solution
After the above process, we get CounterLibrary.dll assembly placed in c:\csharp\counterlibrary\bin\release directory.

Using a private assembly in a console application developed in C#

Now, let us use the class library created in C# in a console application. Though I am using a console application in C#, you can use any language supported by .NET. 
  1. Start Visual C# 2005 Express Edition
  2. Create a new console application using File -> New Project
  3. From template select Console Application as type of project
  4. Give name UseCounter for application.
    A new application is created with a single class with Main() method.
  5. Go to Solution Explorer and select project
  6. Right click on it and select Add References from the context menu.
  7. From dialog box, select Browse tab and select c:\csharp\counterlibrary\bin\release\counterlibrary.dll
  8. Solution explorer displays counterlibrary as one of the references under references node in solution explorer
  9. Add the following code in Main() method of Program.cs
    using System;
    namespace UseCounter
    {
        class Program
        {
            static void Main(string[] args)
            {
                counterlibrary.Counter c = new counterlibrary.Counter(100);
                c.Inc();
                Console.WriteLine(c.Value);
            }
        }
    }
    
As you do the above, you can notice that a copy of counterlibrary.dll is copied into BIN directory of UseCounter application. This is the case with any private library. Whenever an application makes a reference to it, a copy of private assembly is copied into it's bin directory.

If you do not see .DLL file that is copied to BIN directory of console application (UseCounter), close the application and reopen it.

Making a private assembly a global assembly

A global assembly is a public assembly that is shared by multiple applications. Unlike private assembly, a global assembly is not copied to bin directory of each application that references it. Global assembly instead is placed in GAC (Global Assembly Cache) and it can be referenced anywhere within the system. So only one copy is stored, but many applications can use that single copy.
In order to convert a private assembly to global assembly, we have to take the following steps.
  • Create a strong name
  • Associate strong name with assembly
  • Place assembly in GAC

Creating a strong name

Any assembly that is to be placed in GAC, must have a strong name. Strong name is a combination of public key and private key. The relationship between public and private keys are such, given one you cannot get the other, but any data that is encrypted with private key can be decrypted only with the corresponding public key.
Take the following steps to invoke SN (Strong Name) tool to create strong name.
  1. Go to command prompt using Microsoft .NET Framework SDK v2.0 -> SDK Command prompt
  2. Go to c:\csharp\counterlibrary folder and enter the following command.
  3. sn -k srikanth.key
    
    The above command writes private and public key pair into srikanth.key file.

Associate strong name with assembly

Once private and public keys are generated using SN tool, use the following procedure to sign counterlibrary with the key file.
  1. Open counterlibrary project.
  2. Select project properties using Project -> counterlibrary properties
  3. Select Signing tab in project properties window
  4. Check Sign the assembly check box
  5. Select srikanth.key file using Choose a strong name key file combo box
  6. Close properties window
  7. Build the solution again using Build->Build Solution
Now, counterlibrary.dll is associated with a public key and also digitally signed with private key. This ensures no one can modify this assembly as any change to assembly should re-sign the assembly with private key of the user who created it first. This protects the assembly from getting tampered with by others. A global assembly needs this projection as it is placed in common place.
You can verify whether the assembly is associated with public key using ILDASM (IL Disassembler) program provided by .NET Framework.
  • Start ILDASM using .NET Framework SDK v2.0->Tools->MSIL Disassembler
  • Select counterlibrary.dll using File->Open
  • Once assembly is opened, double click on Manifest section of the assembly to see the public key associated with the assembly.

Place assembly in GAC

In order to make an assembly a global assembly, the assembly must be associated with a strong name and then placed in Global Assembly Cache (GAC).
GAC is a folder with name Assembly in windows folder of your system. So, place counterlibrary.dll in GAC using GACUTIL tool as follows.
c:\csharp\counterlibrary\bin\Release>gacutil -i counterlibrary.dll
After you install global assembly into GAC, you can see counterlibrary.dll in windows/assembly folder.
Once, you place an assembly in GAC, any reference to the assembly will not create a copy of the assembly in BIN directory of the application. Instead all application that reference the assembly use the same copy that is placed in GAC. 


Create a list in SwiftUI with sticky section headers

 Sample Code import SwiftUI struct ContentView : View {     @State var isCustomViewControllerDisplayed = false     @State private va...