Tuesday, May 31, 2011

Silverlight Panels: How to use Canvas Layout in Silverlight?

Silverlight Panels: How to use Canvas Layout in Silverlight?

In this article let us learn how to use Canvas Layout panel in a Silverlight applicationCanvas Layout panelis another most useful panel we ever use in SilverlightUsing this we can place any content any where inside the canvas. Canvas is mostly useful whenever we want place any objects in layered fashion. We can put our content in specific location by providing absolute left and top position to Canvas Layout

As usual, open visual studio and select Silverlight project. We can notice that there is a Grid layout in our MainPage.xaml.  Remove the default Grid layout and just drag and drop the Canvas Layout into our application. The code for this looks like as

    <Canvas Name="canvas1">
        <Rectangle x:Name="rectFirst" Fill="Blue" Height="100" Width="100" />
        <Rectangle x:Name="rectSecond" Fill="red" Height="100" Width="100" />

From the above code we can notice that I placed two rectangles in our canvas layout. If we compile this without using Canvas.Left and Canvas.Right to both the rectangles, then we can able to see only second rectangle. This is because size of both the rectangles are same and we dint give absolute positions to our rectangles, so they both got overlapped each other.

Now let us give absolute positions to our rectangles. The code for this looks like as

   <Canvas Name="canvas1">
        <Rectangle x:Name="rectFirst" Fill="Blue" Height="100" Width="100"
        Canvas.Left="50" Canvas.Top="50" />
        <Rectangle x:Name="rectSecond" Fill="red" Height="100" Width="100"
        Canvas.Left="200" Canvas.Top="100" />

From the above code we can notice that I gave left and top positions to both the rectangles using Canvas.Left and Canvas.Right properties.

That's it!!!! Just press F5 and see the result

The output for the above code looks like as

Note: For the people who find it difficult to integrate the above code, I am pasting the complete code here.


<UserControl x:Class="SilverlightTest2.MainPage"
    d:DesignHeight="300" d:DesignWidth="400">

    <Canvas Name="canvas1">
        <Rectangle x:Name="rectFirst" Fill="Blue" Height="100" Width="100"
        Canvas.Left="50" Canvas.Top="50" />
        <Rectangle x:Name="rectSecond" Fill="red" Height="100" Width="100"
        Canvas.Left="200" Canvas.Top="100" />


If you have any doubts in this article or have any suggestions for me please don't hesitate to leave a comment. If you like my articles do subscribe to my blog so that you can get my articles directly to your inbox. Thanks for reading!!!!

“Not able to view the solution file in Visual Studio” – Hide and Show solution file in Visual Studio

Sometime you may came across with this problem that, you are not able to view the solution file in Visual Studio though you have solution file in proper place and the file physically exists in solution folder . You may just wonder why you are not able to view the solution file. Yeah, it could be some missing settings with in visual studio.

If you create any Visual Studio Project, by default you will get below view in Solution Explorer ( Solution file and the Project files associated with in solution ).

More Detail at Original Source

How do you convert a string into an enum?

How do you convert a string into an enum?

 it's one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:

   object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So you can write the following kind of code:

   enum Colour    {       Red,       Green,       Blue    }      // ...    Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);    Console.WriteLine("Colour Value: {0}", c.ToString());     // Picking an invalid colour throws an ArgumentException. To    // avoid this, call Enum.IsDefined() first, as follows:    string nonColour = "Polkadot";     if (Enum.IsDefined(typeof(Colour), nonColour))       c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);    else       MessageBox.Show("Uh oh!");

What a time saver - thanks

Windows Phone 7 Tutorials Jump Start with Mango - 2 - Know more about Page

Windows Phone 7 Jump Start with Mango - 2 - Know more about Page

In my previous post, we discussed on how to create a Windows Phone 7 application and what are the different parts of the MainPage.xaml. We also created a small and simple HelloWorld application as the quick start. I guess, now we are comfortable to create a basic application with a good UI (if you already know how to design a XAML page).   It's time to explore more in depth about the page. In this post, we will discuss about the base class called "Page". Read to know more about it.     Introduction to Page Like "MainPage.xaml", every Windows Phone 7 page inherits from "PhoneApplicationPage" by default, which is part of Microsoft.Phone.Controls namspace. PhoneApplicationPage itself derives from the base class called "Page", part of System.Windows.Controls namspace. Every "Page" is nothing but a derived class of UserControl and if you are already familiar with the UserControl hierarchy, you know that the most...

Read more at: Original Source

Monday, May 30, 2011

Classes for fetching and parsing XML or JSON via HTTP


In my experience, "fetching data via HTTP" is probably the second most common task that iOS applications perform after "displaying a list of things in a table". Since I wrote a recent post showing how I handle display in tables, showing my reusable classes for fetching via HTTP seemed like a reasonable follow up.

As with the post on UITableView management, this post is all about trying to make the HTTP fetching, handling and processing as simple and reusable as possible.

What I hope to demonstrate is that even though the Cocoa API makes it look like you need to boltNSURLConnection delegate methods onto your own classes every time you need a network connection, it doesn't mean that you actually need to do all this work every time you need a network connection. For the most common tasks like this, you should develop your own, reusable approaches that you like, that serve your needs and that make new code easier.

There are lots of alternative approaches around that demonstrate similar ideas. My implementation is a simple implementation compared to full frameworks (for a more thorough implementation along similar lines, you may want to look at RestKit). I hope you'll still be able to see the contrast compared to ad hoc solutions though, especially if you've ever jammed HTTP communication into your projects without thinking about keeping the interface clean and simple.

You can download the four classes discussed in this project: HTTPXMLJSONFetchers.zip(16kB)

HTTP connections in Cocoa

BSD sockets and CFHTTPStream are generally too low level to use regularly. Unless your program requires meticulous control of the network layer, you probably want to use NSURLConnection for handling HTTP fetching.

More at Original Source

How to validate a DropdownList - ListBox.

Original Source

In this article, we are going to learn how to validate a DropdownList/ListBox.


Normally we validate a TextBox to make it mandatory by usingRequiredFieldValidator, however sometimes we need to validate aDropDownList/ListBox so that user doesn't select the default selected item from it. To validate a DropDownList/ListBox as a mandatory field so that user has to select an item other than the default selected item we can still useRequiredFieldValidator however with one extra property.

Let's see this with example. First create a .aspx page and paste below code.


Select age:

<asp:dropdownlist id="dropDownAge" runat="server">

<asp:ListItem Text="Select Age" Value="0" />

<asp:ListItem Text="18" Value="18" />

<asp:ListItem Text="19" Value="19" />

<asp:ListItem Text="20" Value="20" />

<asp:ListItem Text="> 20" Value=">20" />


<asp:requiredfieldvalidator id="reqAge" runat="server" errormessage="Please select age" forecolor="Red" controltovalidate="dropDownAge" initialvalue="0" />


<asp:button id="btnSubmit" runat="server" text="Submit" onclick="SubmitData" />



protected void SubmitData(object sender, EventArgs e)




In the above code snippet, the first item of the DropDownList is "Select Age" with value as "0"; we want the user to select any age apart from "0". To do that we can specify the RequiredFieldValidator's "InitialValue" as "0", this will cause the RequiredFieldValidator fail unless user select any age other than "0" from the DropDownList.

Now when we run the page with above code snippets, its output should appear something like below image and when we click the Submit button without selecting any age apart from "0" that is "Select Age" item, we shall get error like below

Note: Similarly we can perform the validation for ListBox control as well.


Hope this was useful article, keep reading, learning and sharing !

Windows Phone 7 Jump Start with Mango - 1 - Creating a Hello World Application

Windows Phone 7 Jump Start with Mango - 1 - Creating a Hello World Application

Recently thought to take some break from core Silverlight programming and start learning something new. As I will be working on Silverlight in office, hence decided to start exploring Windows Phone 7 in my off time. Though, it is also in Silverlight, but there we can learn something new apart from the actual Silverlight development. Now onwards, I will write about Windows Phone 7 programming and whatever I will explore, will post here in my blog.   Jump started with my first exploration to create a "Hello World" application in Windows Phone 7.1 (Mango) public Beta. This is the first post of the series. As a beginner I will be contributing to the series and if something that I can improve in any of the posts/demos, please let me know by providing your inputs using the Comment box. Hope this series will help the beginners to learn about it.     Prerequisite If you are new to Windows Phone 7, you need to install the Developer Tools. Currently Windows...

Read more at: Original Source

Sunday, May 29, 2011

User interface strings in Cocoa

Introduction (the wrong way)

Putting a text string in your user interface is not a difficult thing to do on a technical level. In code, filling in text can be as simple as setting the text property of a UILabel to a literal string:

 someUserInterfaceLabel.text = @"Text to display";

(This code is for an iOS UILabel. On Mac OS X, you would set the stringValue property of anNSTextField but otherwise the step is the same.)

While this will work, you should never set a user interface string this way.

More at Original Source

Handling unhandled exceptions and signals


This post will present a sample application that deliberately raises Objective-C exceptions,EXC_BAD_ACCESS exceptions and related BSD signals. All exceptions and signals are caught, presenting debug information and allowing the application to continue after these events.

More at Original Source

Tips & Tricks for conditional iOS3, iOS3.2 and iOS4 code

A project or target that supports multiple versions of iOS

To make an application target that runs on multiple versions of iOS is relatively simple:

  • Set the "Base SDK" in your projects settings to the newest version number of iOS whose features you may want.
  • Set the "iPhone OS Deployment Target" to the oldest version number of iOS that you will support

However, getting the target settings correct is the easy part of the problem. The hard part is using new features on newer iOS versions without breaking the app on older versions.

Running in the 3.1.3 simulator

A ZoomingViewController to animate a UIView to fullscreen

ZoomingViewController is a class you can attach to any existing view that will let you zoom the view to fullscreen with a single tap, rotate the view while in fullscreen by rotating the device and tap to return to the original inline state.


The ZoomingViewController class in this week's sample project handles the zooming in the following sample app:


The animation between the inline and fullscreen states is smooth and you can rotate the device in fullscreen to rotate the view.

You can attach the ZoomingViewController to any view to add this behavior.


Size-to-Fit Text in UITextView (iPhone)

The UITextView is a very useful view. You're able to show and interact with large amounts of text. However, I recently found the need to size the UITextView in Interface Builder to fit nicely in a pre-layed out interface. Well, low-and-behold the client I was working for started sending large amounts of text that was to be displayed here. We didn't want scrolling but needed to display all the text. So, we needed to resize the text until it would fit and all would be displayed. Below is a very simple way of resizing the text in the UITextView to fit within its current bounds.

At some point define the max size you want the font to be. I typically put this in my .h file

 #define kDefaultFontSize 24.0

Then in your .m file where you add the text to the UITextView you would place something like:

 myTextView.text = @"Some long string that will be in the UITextView"; myTextView.font = [UIFont systemFontOfSize:kDefaultFontSize];  //setup text resizing check here if (myTextView.contentSize.height > myTextView.frame.size.height) {     int fontIncrement = 1;     while (myTextView.contentSize.height > myTextView.frame.size.height) {         myTextView.font = [UIFont systemFontOfSize:kDefaultFontSize-fontIncrement];         fontIncrement++;     } }

Hope this helps! Enjoy!

Key inputs to avoid Apple’s iOS app rejection

An app idea or product app takes much of time and money investment to get into app world existence. The major hurdle to it's success could be Apple's review process. There can be numerous reasons for Apple's rejections for your app. With our superior knowledge of iOS apps development since the day Apple launched their SDK, we are able to gain valuable insights into Apple's review process.

This will help:

1. Developers to save their precious time and efforts.

2. Let you plan for a better user experience which is the key reason behind all the app store guidelines.

There are few key points which every iPhone/iPad developer should know when developing an app for Apple devices.

Key things to avoid Apple's app rejection:

1. Bugs/Crashes- The most common reason for any app to get rejected are freezing and frequent crashes. Make sure you test it on multiple devices, different OS versions and specifically under varying network conditions. Peer-to-peer reviews/testing done by developers would certainly help. If your app crashes or doesn't respond during the app review by Apple's testing team then it will definitely be rejected.

2. Code Download- You cannot create an app that downloads and executes code that was not present in the app bundle submitted to Apple.

3. Similar Icons- The app store 512×512 icon should be same as the app's 57×57 icon. Even though there is no such direct rule in contract/agreement with Apple, its their store and they make the rules for reviews. If your app's icon on phone and app store icon do not match, Apple will state having un-matching icons to reject the app.

4. Network Connectivity- You must notify the user if network is unavailable. Just having the spinning busy icon display and a message saying "trying to connect" is against the guidelines. Proper message is needed at all the screens to convey clear message if network is not available after certain period of time. Many developers put their connectivity checks on Apple's Reachability code, which is using that sample code for the wrong purpose. If you need to get data from a specific server, then try to download some data from that domain.

5. "Free+Paid" apps- Apple reported to few developers that app may get rejected, if it contains visually disabled buttons, prompting the user to upgrade for the full version or displaying the price of full version in the Free version. So, iPhone developers must ensure that they follow all the rules.

6. Consistent Button Images- If an iPhone developer wants to use Apple's existing image for his button then see that functions are identical because you can use a standard button in a non-standard way if your app is providing a "immersive environment" so it is better to create your own button. If there are any variations with function then again Apple might reject the app.

It is always advisable for an iPhone developer to use their own custom buttons in the app

7. iOS version support- If you plan on submitting and app which runs with 3.0 and higher versions, you should be sure that it works perfectly on all the versions from the iOS 3.0 to the most current version. Apple will test it with the latest version to see the potential of the app but if the app fails to prove itself Apple will definitely rejected your app.

8. Transactions outside The App Store-

Apple do not allow developers to conduct any transaction/business outside the app store. In App purchases are the recommended way to implement these transaction. Recent announcement to allow outside payment transaction with certain restriction and Apple's percentage take from money for the same is trickier and would take more time to settle down in business plan of apps sale.

9. Private API:s

Apple strictly reject apps which are implementing programs using Private APIs. Apple has scripts that can scan your app codes for violations. If you want to prevent app rejection from app store make sure you read the developer guidelines carefully before implementing any API marked private by Apple.

10. Popovers-

It is definitely not recommended to launch one popover from within another popover. The iPad Human Interface Guidelines clearly provides this information that only one popover element should be shown onscreen at a time.

There can be many more reasons behind Apple's rejection of any iOS app. However, the list provides very obvious ones.


Grouping Records in Silverlight DataGrid using PagedCollectionView

Do you work with Silverlight DataGrid and want to group your records inside the DataGrid in a proper manner? If so, this article is for you. Here we will learn about data grouping inside a DataGrid.


In this article, we will learn how to group data inside a Grid. We will discuss all these steps-by-step and with proper images, so that, you can understand it very easily.


The full source code has been attached. You can freely download it and that will be more helpful for you to understand. Read the complete article to learn it.

Detail here at Original Source

Saturday, May 28, 2011

Collection Initializers in .NET

Many of you have used property initializers in your code. Object initializers and property initializers are common operations of every program. But do you know, .NET supports Collection initilization directly for all IEnumerable objects ? In this post lets take a brief introduction of Collection Initializers in .NET.

Suppose you want to create an array which holds some values, you might write :

string[] myarray = {"Abhishek", "Abhijit", "Atul", "Jaberson" };

Oh, it works. myarray is going to initialize with values specified inside the curl braces.

You might think, this is very common syntax that we all know from basic programming languages. But yet, C# puts this further, lets demonstrate :

List mylst = {1,2,3,4,5};

Yes even this works as well. Actually curl braces produces an IEnumerable which you can cast to any custom collection type.

You can even use this syntax to do like this :

List mylst = { 1, 2, x * 20, this.GetInt(), 44 };

The 3rd value will be x times 20 and this.GetInt will be called for 4th value.
Hence it is nice to have feature for C#.
I hope this would help you.

How to store custom objects in web.config ?

In this Post, I am going to discuss about web.config. Normally in our daily life, we used to have some data inappSettings section of web.config and read it when required. That is in string form. But there are lot more than this. We can update the data in web.config programmatically as well .

Now another main point is, we can store some object of custom type in web.config as well, which we normally don't do it. But this can be very useful in several scenarios.

Have anyone tried to update some value or add some value in web.config? W'll have brief discussion on this.

First, This is very common to have some constant data atappSettings section of web.config and read it whenever required. So how to read this ( for beginners).

 //The data is stored in web.config as <appSettings> 		<add key="WelcomeMessage" value="Hello All, Welcome to my Website." /> </appSettings>  // To read it string message = ConfigurationManager.AppSettings["WelcomeMessage"]; 

Now if we want to update some data of appSettings programatically. One can do like this.

 //Update header at config         Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);         config.AppSettings.Settings["WelcomeMessage"].Value = "Hello All, Welcome to my updated site.";         config.Save(); 

Now what do you do, if you want to add some data in appSettings . You can add some app.config data as below.

 //Update header at config         Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);         config.AppSettings.Settings.Add("ErrorMessage", "An error has been occured during processing this request.");         config.Save(); 

The above code is adding one new key value pair in web.config file. Now this can be read anywhere in the application.

Now, the question is, Can we store some custom data at config?


We can store some object. Let's see how

I have created a sample example. In this example, I have saved an object of my custom class NewError in web.config file. And also updating it whenever required.

To do this, Follow the below steps.

a) Create a Class that inherit From ConfigurationSection (It is available under namespace System.Configuration ). Every property must have an attribute ConfigurationProperty, having attribute name and some more parameters. This name is directly mapped to web.config. Let's see the NewError class

 public class NewError:ConfigurationSection {     [ConfigurationProperty ("Id",IsRequired = true)]     public string ErrorId {         get { return (string)this["Id"]; }         set { this["Id"] = value; }     }     [ConfigurationProperty("Message", IsRequired = false)]     public string Message {         get { return (string)this["Message"]; }         set { this["Message"] = value; }     }     [ConfigurationProperty("RedirectURL", IsRequired = false)]     public string RedirectionPage     {         get { return (string)this["RedirectURL"]; }         set { this["RedirectURL"] = value; }     }     [ConfigurationProperty("MailId", IsRequired = false)]     public string EmailId     {         get { return (string)this["MailId"]; }         set { this["MailId"] = value; }     }     [ConfigurationProperty("DateAdded", IsRequired = false)]     public DateTime DateAdded     {         get { return (DateTime)this["DateAdded"]; }         set { this["DateAdded"] = value; }     } } 

as you can see every property has attribute ConfigurationProperty with some value. As you can see the property ErrorId has attribute

 [ConfigurationProperty ("Id",IsRequired = true)] 

it means ErrorId will be saved as Id in web.config file and it is required value. There are more elements in this attribute that you can set based on your requirement.
Now if you'll see the property closely, it is bit different.

 public string ErrorId { get { return (string)this["Id"]; } set { this["Id"] = value; } } 

Here the value is saved as the key "id", that is mapped with web.config file.

b) Now you are required to add/register a section in the section group to tell the web.config that you are going to have this kind of data. This must be in and will be as

 <section name="errorList"  type="NewError" allowLocation="true"      allowDefinition="Everywhere"/> 

c) Now one can add that object in your config file directly as

 <errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="xyz@hotmail.com" ></errorList> 
 <errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="xyz@hotmail.com" ></errorList> 

d) And to read it at your page. Read it as follows.

 NewError objNewError = (NewError)ConfigurationManager.GetSection("errorList"); 

And also a new object can be saved programmatically as

 NewError objNewError = new NewError()        {          RedirectionPage="www.rediff.com",          Message = "New Message",          ErrorId="0",          DateAdded= DateTime.Now.Date        };        Configuration config =            WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);         config.Sections.Add("errorList", objNewError);        config.Save(); 

Even one can add a custom group and have some custom elements in in this section.

ASP.NET provides very powerfull APIs to read/edit the web.config file easily.