Google+

Tuesday, January 10, 2012

7 Mistakes Developers make when implementing Windows Phone Custom Controls


Generally, Custom Controls are skinable, themable and reusable controls that once created can be used by simply loading the assembly in any project.  All controls that are used in Silverlight for Windows Phone 7 (eg., Button, TextBlock, ListBox) and UserControl are also Custom Controls. Usually Custom Controls inherit from Control,ItemsControl, ContentControl, etc.
NOTE: You can also take a look at the following article for reference: Creating a WP7 Custom Control in 7 Steps
Mistake #1: Wrong choice of whether to implement a Custom Control or a UserControl
Generally when talking about Windows Phone controls you have two options: either to implement a User Control or a Custom Control.

User Control: a reusable control that combines existing controls and can implement its own logic.  User-Controls can be reused but  cannot be skinned or themed.
Custom Control: skinable, themable and reusable controls that once created can be used by simply loading the assembly in any project.
Good for static layout
Good for dynamic layout
Easier to create
Harder to create
Usually used to compose a set of existing controls
Usually used to create a new control
Usually used to allow reusability on a larger scale
Usually used to allow reusability on a smaller scale
Provides less flexibility
Provides greater flexibility (ex: the control template can be replaced with a completely different one)
Does not require  too much knowledge of Silverlight UI model
Requires better understanding of Silverlight UI model
Example1: Correct choice  of using Custom Control
Control Description: We want our control to :
  • contain a collection of items
  • expose ItemsSource
  • be easily reusable
  • allow automatic sorting, filtering,etc. based on some condition
  • have multiple Views/States, i.e. FullScreen mode, Minimized mode, Standard mode, etc.
  • allow item selection
  • expose custom properties
  • be fully customizable
Control Usage: We will use this control multiple times in our application and in several other applications.
Our Comment: In this case we would suggest that you implement a Custom Control that derives from ListBox or optionally directly from ItemsControl. The control will be compiled into a separate assembly (.dll) so that it can be easily reused in other applications as well.
Example2: Incorrect choice of using Custom Control
Control Description: We want our control to:
  • have ListBox which will be automatically sorting, filtering,etc based on some condition. For example Button click.
  • consists of a ListBox, two Buttons and a TextBlock
  • exposes several custom properties
  • not necessarily provide great flexibility in appearance customization
Control Usage: We will use this control only a couple of times in a single application.
Our Comment: In this case we would suggest that you implement a UserControl instead of Custom Control because you will use it only a couple of  times in the same project and it will be easier to implement the desired functionality in code behind rather than trying to implement a Custom Control from scratch.

Mistake #2: Deriving from an inappropriate base class
When implementing a Custom Control you need to derive from an appropriate base type . Here are some suggestions:
ItemsControl: When you want to implement a control that has multiple items usually using the ItemsControl is a good choice.
ContentControl: When you want to implement a control that displays a single element (through the Content property), possibly using different templates.
ListBox: When you want to implement a selectable ItemsControl
Control: When there is no other suitable type to derive from.
Controls such as Button, CheckBox, ScrollViewer, etc.: When you want to implement a specific type of control and need some of the properties/method of the parent control.

Mistake #3: Forgetting to set DefaultStyleKey in the constructor
It is very important not to forget to set the DefaultStyleKey in the constructor of your custom control.
NOTE: DefaultStyleKey gets or sets the key that references the default style for the control.
?
1
2
3
4
5
6
7
public class MyCustomControl : ContentControl
{
    public MyCustomControl()
    {
        DefaultStyleKey = typeof(MyCustomControl);
    }
}
Mistake #4: Control theme(default Style) in the wrong place
This is one of the most common mistakes that we have seen. In short the base structure of a Custom Control is:
MyCustomControl.cs + Themes/generic.xaml
  • MyCustomControl.cs: place the C#/VB code here
  • Themes/generic.xaml: place the UI here
    NOTE: You must  create a Themes folder(the name is very important) and place the generic.xaml there
42-2For now in Silverlight for Windows Phone Mango there is no suitable VisualStudio Template for adding a XAML file or ResourceDictionary  as a file in your project. So in order to add generic.xaml file you can create a new Class by choosing Add->NewItems->Class  and rename it to generic.xaml.
NOTE: The name is important!
NOTE:It is very important that you remember to set the generic.xaml file's build action to Resource. This is necessary in order  to make sure that the template is packed in the same assembly as the control otherwise the template wont be available.




Mistake #5: generic.xaml defined or used in a wrong way
Example1: Correct
  • Themes/generic.xaml
  • Build Action: Resource
  • ResourceDictionary without any x:Key or x:Name
  • include
xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows" if using any VisualStates
Example2: Incorrect
  • /generic.xaml
  • Build Action: Content
  • ResourceDictionary with x:Key or x:Name
Mistake #6: Wrong Style
The default style and the ControlTemplate of the custom control determine how the control will look like.
When creating the default style(theme) of a Custom Control it is very important to consider the following things:
  • You must define a valid ControlTemplate
  • Add a valid TargetType
  • No x:Key
  • No x:Name
Example1: Correct Style
?
1
2
3
4
5
6
7
8
9
<Style TargetType="local:MyCustomControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyCustomControl">
               ..
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

where local is your new Custom Control namespace for example:
?
1
xmlns:local="clr-namespace:CustomControlSample"
Example2: Incorrect Style
Here is an example of incorrectly defined Style.
114-0

Mistake #7: Using Binding instead of TemplateBinding
TemplateBinding links the value of a property in a control template to be the value of a property on the templated custom control!
Example1: Correct
114-1
Example2: Incorrect
114-2
In this article I talked about 7 common mistakes that developers make when implementing a Custom Control in Silverlight for Windows Phone.
I hope that the post was helpful.





 

Thursday, November 10, 2011

Soap Request in android

Well you need to understand what a soap request is made of:.



Code:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://www.example.org/stock">
      <m:StockName>Google</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>

The message has a soap:envelope with a soap:header and a soap:body.

The content type of a soap requests is application/soap-xml

Now to send a soap request with Android you have to use a URLConnection and 2 streams.
An inputstream and an outputstream.


Code:
URL u = new URL(url.toString());
URLConnection cnn = u.openConnection();
cnn.setDoOutput(true);
cnn.setDoInput(true);

((HttpURLConnection)cnn).setRequestMethod("POST");
cnn.setRequestProperty("Content-Type", "application/soap-xml; charset=utf-8");
cnn.setRequestProperty("SOAPAction", method);

OutputStream outStream = cnn.getOutputStream();
outStream.write(soapXML);

InputStream in = cnn.getInputStream();

  1. You need to open the URLConnection.
  2. You set the requestMethod to POST.
  3. You set the content-type to application/soap-xml.
  4. You set a SOAPAction header to the method you want to use. (This is not shown on the previous example which I have from wikipedia.)
  5. You write the soapXml envelope to the outputstream.
  6. You read the response from the inputstream.


You can parse the response with an XmlParser if you want to.

I have combined the send and receive code into a class called Webservice. And I made a class called SoapMessage to handle the construction of a Soap envelope.
Then I send the SoapMessage using the send method of the Webservice class and I add an OnReceiveListener to wait for the response.

This is not the most sophisticated method and probably not the most complete method to send and receive Soap messages but it works in android 2.2 perfectly. As SAX Parser not getting proper response.




SAX Parser example coming soon in next Post




source : http://androidforums.com/developer-101/233069-how-create-weservice-client-android.html

Monday, October 3, 2011

How to Create MD5 Hashed Code in Android

Dear Blog Viewer,


What is the MD5 hash?
The MD5 hash also known as checksum for a file is a 128-bit value, something like a fingerprint of the file. There is a very small possibility of getting two identical hashes of two different files. This feature can be useful both for comparing the files and their integrity control.
Let us imagine a situation that will help to understand how the MD5 hash works.
Alice and Bob have two similar huge files. How do we know that they are different without sending them to each other? We simply have to calculate the MD5 hashes of these files and compare them.
MD5 Hash Properties
The MD5 hash consists of a small amount of binary data, typically no more than 128 bits. All hash values share the following properties:
Hash length
The length of the hash value is determined by the type of the used algorithm, and its length does not depend on the size of the file. The most common hash value lengths are either 128 or 160 bits.
Non-discoverability
Every pair of nonidentical files will translate into a completely different hash value, even if the two files differ only by a single bit. Using today's technology, it is not possible to discover a pair of files that translate to the same hash value.
Repeatability
Each time a particular file is hashed using the same algorithm, the exact same hash value will be produced.
Irreversibility
All hashing algorithms are one-way. Given a checksum value, it is infeasible to discover the password. In fact, none of the properties of the original message can be determined given the checksum value alone.
The algorithm was invented by:
Professor Ronald L. Rivest (born 1947, Schenectady, New York) is a cryptographer, and is the Viterbi Professor of Computer Science at MIT's Department of Electrical Engineering and Computer Science. He is most celebrated for his work on public-key encryption with Len Adleman and Adi Shamir, specifically the RSA algorithm, for which they won the 2002 ACM Turing Award.
Simple Code for Android:

public static final String md5Digest(final String text)
{
     try
     {
           // Create MD5 Hash
           MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
           digest.update(text.getBytes());
           byte messageDigest[] = digest.digest();

           // Create Hex String
           StringBuffer hexString = new StringBuffer();
           int messageDigestLenght = messageDigest.length;
           for (int i = 0; i < messageDigestLenght; i++)
           {
                String hashedData = Integer.toHexString(0xFF & messageDigest[i]);
                while (hashedData.length() < 2)
                     hashedData = "0" + hashedData;
                hexString.append(hashedData);
           }
           return hexString.toString();

     } catch (NoSuchAlgorithmException e)
     {
           e.printStackTrace();
     }
     return ""; // if text is null then return nothing
}


Google+