Rabu, 28 Mei 2014

WindowsPhone Facebook Integration:How to post message/image to FaceBook Fan Page(C#-XAML)

Introduction:


Now its time to a requirement is "How to post message/image to Facebook Fan Page from windows phone".Actually there is lot of resources is available for posting message on facebook profile wall page.But for posting message on facebook fan page,there is no resources available.However we will talk with this post.

Lets understand requirement 

1)What is a fan page on Facebook:
A fan page is the only way for entities like businesses, organizations, celebrities, and political figures to represent themselves on Facebook.
Unlike a personal Facebook profile, fan pages are visible to everybody on the Internet. Anyone on Facebook can connect to and receive updates from a page by becoming a fan (i.e. ‘Liking’ the page).
If you interesting on knowing more about fan page visit this link

Building the Sample:

Description:

After successfully Facebook Connect with access_token ,Once you got it, you could do anything with the API. For now, I will show you how to post to the FaceBook Fan Page with specific message/image. So lets start with few steps

1)Extended Permissions for Posting message on facebook Fan Page:

Yes we need to some following extra permissions to post message on Facebook page. 

C#
 private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream,manage_pages";

2)How to post message/image on facebook Fan Page:

It is very simple and similar to posting message on facebook profile page.But we need to have some changes .
To post message on facebook profile page:
C#
var fb = new FacebookClient(_accessToken); 
fb.PostAsync("me/feed", parameters);

To post message on facebook fan page ,we just need to replace "me/feed" to "FacebookFanPageName/feed".
 for example
C#
var fb = new FacebookClient(_accessToken); 
fb.PostAsync("SubramanyamRajuWindowsPhone/feed", parameters);

Here i tried to post message on my facebook fan page name is: https://www.facebook.com/SubramanyamRajuWindowsPhone

By the way the total code to post message/image on fan page is:
C#
 private void PostToFaceBookFanPage_Click(object sender, RoutedEventArgs d) 
        { 
            var fb = new FacebookClient(_accessToken); 
 
            fb.GetCompleted += (o, e) => 
            { 
                if (e.Error != null
                { 
                    Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message)); 
                    return
                } 
 
                var result = (IDictionary<stringobject>)e.GetResultData(); 
                var id = (string)result["id"]; 
                result["id"] = id; 
 
 
                fb.PostCompleted += (oo, args) => 
                { 
                    if (args.Error != null
                    { 
                        Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message)); 
 
                        return
                    } 
 
                    var result1 = (IDictionary<stringobject>)args.GetResultData(); 
                    _lastMessageId = (string)result["id"]; 
 
                    Dispatcher.BeginInvoke(() => 
                    { 
                        NavigationService.GoBack(); 
                        MessageBox.Show("Message Posted successfully"); 
 
 
                    }); 
                }; 
                var fbupload = new FacebookMediaObject 
                { 
                    FileName = "images.jpg"
                    ContentType = "image/jpeg" 
                }; 
                fbupload.SetValue(data); 
                var parameters = new Dictionary<stringobject>(); 
                parameters["message"] = "SubramanyamRaju WindowsPhone Tutorials \n www.bsubramanyamraju.blogspot.com"
                // parameters["name"] = "My FB Pic"; 
                parameters["picture"] = "http://azujenergia.hu/files/2013/04/blossoming-flower4.jpg";//to post image on facebook 
               // parameters["link"] = "http://www.logictreeit.com"; 
                fb.PostAsync("SubramanyamRajuWindowsPhone/feed", parameters);//to post message pn facebook fanpage profile 
               // fb.PostAsync("me/feed", parameters);//to post message on user profile 
 
            }; 
 
            fb.GetAsync("me?fields=id"); 
        }

 3)Fan Page ScreenShots:


Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)


Rabu, 21 Mei 2014

WindowsPhone 8.1 LightSensor :Now the great "LightSensor" class is available for phone (C#-XAML)

Introduction

Again the great start of windowphone 8.1 is now "LightSensor" class available for developers.LightSensor returns the ambient-light reading as a LUX value.An ambient light sensor is one of several types of environmental sensors that allow apps to respond to changes in the user's environment.So You can use the ambient light sensor to detect changes in lighting with an app written in C#.

Why LightSensor?

Lets come with some real time examles

1)This sensor can be used for many things and it is common that the light sensor is used to illuminate the backlight on keyboards.

2)Controlling display backlight level for Windowsphone based on LUX values retun by LightSensor.

3)You know those fancy car GPS navigators that automatically switch color mode to dark when it gets dark to make it easy on your eyes? The display even turns dark when you drive into a tunnel and lights back up when you’re out

4)Another simple useful requirement is making device theme dark/white based on user environment status.

Source file at :LightSensorSample8.1

Building the Sample

  • This sample is targeted on windowsphone 8.1(non-silverlight)
  • Make sure you’ve downloaded and installed the Windows Phone SDK. For more information, see Get the SDK.
  • I assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see  Register your Windows Phone device for development.
  • This post assumes you’re using Microsoft Visual Studio Express 2013 for Windows.

Description

In this post we are going to take a look at how to use the Light Sensor from within your C#/XAML Windowsphone 8.1 application.
Before we get started we should understand what the light sensor reading is providing you.  This sensor will give you the ‘Lux Values’ (which is lumens per square meter) from the ambient light in your area.  The Lux values can be described in the chart below and you can get more details by looking at the MSDN link here
Lighting conditionFrom (lux)To (lux)Mean value (lux)Lighting step
Pitch Black01051
Very Dark1150302
Dark Indoors512001253
Dim Indoors2014003004
Normal Indoors40110007005
Bright Indoors1001500030006
Dim Outdoors500110,00075007
Cloudy Outdoors10,00130,00020,0008
Direct Sunlight30,001100,00065,0009

1)How to use LightSensor in windowsphone?
Unfortunately There is no API in Windows Phone 8 to access brightness sensor readings like LightSensor.However now luckely both windows phone 8.1 and windows phone silverlight 8.1 are support "LightSensor" class By the way when your app starts, you should first query the device to see if it has a light sensor. The sensor's GetDefault() method will return null if the sensor isn't present on the device or the system was unable to get a reference to it. This might happen if the device is in a connected standby mode.

C#
private Windows.Devices.Sensors.LightSensor _lightSensor; 

private void SetupLightSensor()
{
_lightSensor = Sensor.LightSensor.GetDefault();

if (_lightSensor == null)
{
LuxLums = "Your current device does not support the light sensor.";
}
}
And there is two ways for reading ambient-light reading as a LUX value

  • the app begins streaming light-sensor readings in real time and it is always get updated values with help ofReadingChanged event.
  • the app will retrieve the sensor readings at a fixed interval with help of GetCurrentReading() Method.
1.1)Register to receive updates from the sensor as the values change:

Once you confirm access to the sensor, it's recommended that you set its reporting interval to the default value (0).

ReportInterval:
 In cases where you need to set it explicitly, you can do this by changing the sensor's ReportInterval property. Make sure you don't go below the MinimumReportInterval property. Conversely, when an application is finished with the sensor, it should explicitly return the sensor to its default report interval by setting it to zero. This is important for power conservation, especially when using a language that may keep the sensor object active for an indefinite period prior to garbage collection. 
C#
protected override void OnNavigatedTo(NavigationEventArgs e) 
{
lightSensorobj = LightSensor.GetDefault();
uint minReportInterval = lightSensorobj.MinimumReportInterval;
lightSensorobj.ReportInterval = minReportInterval > 1000 ? minReportInterval : 1000;
lightSensorobj.ReadingChanged += LightSensorOnReadingChanged;
}
Note: Don't forgot to set it back to the default value (0) when you're done. Beacuse Conversely , when an application is finished with the sensor, it should explicitly return the sensor to its default report interval by setting it to zero. This is important for power conservation, especially when using a language that may keep the sensor object active for an indefinite period prior to garbage collection.
So lets start light-sensor readings with ReadingChanged event.
C#
void LightSensorOnReadingChanged(Windows.Devices.Sensors.LightSensor sender, Windows.Devices.Sensors.LightSensorReadingChangedEventArgs args) 
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
LuxTxt.Text = args.Reading.IlluminanceInLux.ToString();
EnvironmentStatusTxt.Text = args.Reading.IlluminanceInLux < 1000 ? "Dark" : "Light";
RequestedTheme = args.Reading.IlluminanceInLux < 1000 ? ElementTheme.Dark : ElementTheme.Light;//Changing the theme of app.
}
);
}
In above code light sensor allows the user to have a theme that responds to light, e.g. have a light theme during the day and dark theme during the night. This might be used for reading apps

1.2)Getting the reading once or via Polling:

If you would like to simply get the Lux value one time you could just do the following

C#
var CurrentlightSensorReading = lightSensorobj.GetCurrentReading();  

Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  

Have a nice day by  :)

Selasa, 13 Mei 2014

WindowsPhone HttpWebRequest vs WebClient:Post JSON data to WebService Beginners Tutorial(C#-XAML)

Introduction:

What is webservice?

Web services allow different applications from different sources to communicate with each other without time-consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating system or programming language.

For example, Java can talk with Perl, Windows applications can talk with UNIX applications.and it is way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone


Why Json?

HTTP-based Web services frequently use JavaScript Object Notation (JSON) messages to return data back to the client. JSON objects can easily be instantiated in JavaScript, without parsing logic, which makes it a convenient format for messages in Web applications.


So what's this sample teach us?

Some times in our windowsphone application,we may need to request webservice in the form of Json format,then only webservice will be returns expected results.So this post is expalined about "How to post json data to webservice using HttpWebRequest or WebClient" 

So lets understand the this sample requirement :

1)I have a webservice like :

 http://test.postjson.com/Login?userid="2"&username="subbu"

here webservcie expected input parameters are userid& username with json format only ,but above service will not work,because of bad request with appending string parameters

Note: Above webservice url is taken for testing purpose only,kindly you can replace your webservice url to work with this sample.

2)Hence we need to json format request to get webservice responce
         string JsonString = "{
                                        'userid': '2',
                                        'username': 'subbu'
                                      }";
3)So we need to  request webservcie in the form of  above JsonString using HttpWebRequest/WebClient

Building the Sample:

This sample is targeted on WindowsPhone 7.1 OS.
Source file at: PostJsondataSample

Description:

1)Which one is best WebClient vs. HttpWebRequest?

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.Also WebClient doesn't have timeout property. And that's the problem, because default value is 100 seconds and that's too much to indicate if there's no Internet connection.

The main difference between the two is that WebClient is basically a wrapper around HtppWebRequest and exposes a simplified interface. 
Apart from that (at least in WP7, not sure about WP8), WebClient only works on the user thread, which is not a good thing. If you want to wait for the reply on a background thread, you need to use HttpWebRequest.

Note:Some times WebClient may not work properly if we need to handle more controls over the entire request,So in this case HttpWebRequest is good for us.


2)Which method we need to choose get vs post?


GET: 

1.All the name value pairs are submitted as a query string in URL. 
It's not secured as it is visible in plain text format in the Location bar of the web browser.
2.Length of the string is restricted. 
3.If get method is used and if the page is refreshed it would not prompt before the request is submitted again. 
4.One can store the name value pairs as bookmark and directly be used while sharing with others - example search results. 

POST: 

1. All the name value pairs are submitted in the Message Body of the request. 
2. Length of the string (amount of data submitted) is not restricted. 
3. Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser. 
4. If post method is used and if the page is refreshed it would prompt before the request is resubmitted. 
5. If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST. 
6. Data is submitted in the form as specified in enctype attribute of form tag and thus files can be used in FileUpload input box. 

  However in our sample we need to post json data to webservice,so that in our case we need to use post method of HttpWebRequest/WebClient.

Se lets start with two ways as following

2.1)How to post json data to webservice using HttpWebRequest post method in WindowsPhone:

Make sure HttpWebrequest object properties like
  • httpwebreqobj.ContentType = "application/json";
  • httpwebreqobj.Method="POST"

C#

private void PostJsonRequest() 
        { 
            //Please replace your webservice url here string AuthServiceUri = "http://test.postjson.com/Login?"
            HttpWebRequest spAuthReq = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest; 
            
spAuthReq.ContentType = "application/json"
            spAuthReq.Method = "POST"
            spAuthReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), spAuthReq); 
        } 
 
        void GetRequestStreamCallback(IAsyncResult callbackResult) 
        { 
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState; 
            Stream postStream = myRequest.EndGetRequestStream(callbackResult); 
            string postData = "{'userid': '2','username':'subbu'}"
            byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
            postStream.Write(byteArray, 0, byteArray.Length); 
            postStream.Close(); 
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest); 
        } 
 
        void GetResponsetStreamCallback(IAsyncResult callbackResult) 
        { 
 
            try 
            { 
                HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState; 
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult); 
                string responseString = ""
                Stream streamResponse = response.GetResponseStream(); 
                StreamReader reader = new StreamReader(streamResponse); 
                responseString = reader.ReadToEnd(); 
                streamResponse.Close(); 
                reader.Close(); 
                response.Close(); 
                string result = responseString; 
            } 
            catch (Exception e) 
            { 
 
            } 
        }

2.1)How to post json data to webservice using WebClient post method in WindowsPhone:

Make sure WebClient object properties like
  • webclientobj.Headers["ContentType"] = "application/json";

C#

void PostJsonRequestWebClient() 
        { 
            WebClient webclient = new WebClient(); 
            Uri uristring = null
           //Please replace your webservice url here  uristring = new Uri("http://test.postjson.com/Login?"); 
            webclient.Headers["ContentType"] = "application/json"; 
            string WebUrlRegistration = ""
            string JsonStringParams = "{'userid': '2','username':'subbu'}"
            webclient.UploadStringCompleted += wc_UploadStringCompleted; 
           //Post data like this  webclient.UploadStringAsync(uristring, "POST", JsonStringParams); 
        } 
        private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
        { 
            try 
            { 
                 
                if (e.Result != null
                { 
                    string responce = e.Result.ToString(); 
                    //To Do Your functionality 
                } 
            } 
            catch 
            { 
            } 
        }
Congratulations! now you can able to post json data to webservice.

Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

Kamis, 08 Mei 2014

Windows Phone Development vs Android Development Tutorial for Beginners

Introduction:

Smartphones are a recent phenomenon and weren't always this popular. Prior to the Android vs. iPhone vs. WindowsPhone debate,and as a developer we can't imagine which mobile platform will be hero in future ,and so mobile application developer it is best practices to know about other mobile platforms (android,iphone,windowsphone,blackberry..etc) 

However if you have been developing android apps and are interested in building apps for windows phone and also vice versa .this post is for you.And so lets start comparison between android vs windows phone development

1.Development Tools:

Android: Android app development is done mostly in Java (in a few cases with C or C++),Declarative screen design in Android is represented in an XML file which gets injected into the corresponding activity code at run time

Windows Phone: Windows phone apps support C++, C#, Microsoft Visual Basic .NET, and JavaScript.Declarative screen design in Windows Phone is represented in Extensible Application Markup Language (XAML).. XAML is a declarative language, with each XML node representing a Windows Runtime object.

The first question that concerns every developer during his first steps is “how easy is it to start developping on a platform”. Assuming that you already are a windows user, things are quite easy. You have to download the SDK and the Visual Studio Express (a striped down version of the standard Visual Studio) and you are ready to start. Of course the same stands for Android too, you download eclipse, the eclipse plugin and the Android SDK and again, you are set to go. Both platforms have rich documentation but Android has an advantage to online communities like StackOverflow and mailing lists. The problems begins when you are a linux or a mac user like myself. Eclipse and the Android SDK run on all operating systems and versions, while Visual Studio runs only on Windows Vista and later. The solution of using a virtual machine is rather disappointing.


Android
Windows Phone
Company/ Developer
Google
Microsoft
Programmed in
Mostly Java (in a few cases with C or C++)
C#, VB.NET,Java Script
(C++ is not supported officially)
RunTime OS 
Android
Windows Phone
Initial release
September 23, 2008
October 21, 2010
Supported platforms
ARM, MIPS, x86, I.MX
ARM,x86
IDE
Eclipse,IntelliJ,NetBeans
VisualStudio
Default user interface
Graphical (Multi-touch)
Graphical (Metro UI)
SDK
Android SDK
Windows Phone SDK
Source model
Open source software
Closed-source
Tools
Android Developers Tools(ADT) plugin for eclipse
Visual Studio Templates and Blend for Visual Studio.
Development OS
Windows,Mac, and Linux FlavorsBest to work with Windows 
Language support
Multiple language support
Multiple language support

2.Layout Controls:

Layout Controls
Windows Phone 7Android Equivalent
CanvasAbsoluteLayout
GridGridView
ScrollViewScrollView
StackPanelLinearLayout

3.Basic Controls:

Basic Controls
Windows Phone 7Android Equivalent
TextBlockTextView
TextBoxEditText
ButtonButton
CheckBoxCheckBox
RadioButtonRadioButton
ImageImageView
ProgressBarProgressBar
ListBoxListView
MapMapView
WebBrowserWebView

4.UI Development:

You have your tools set up, now you must start the development. Both platforms are using XML to construct the UI of an application. In fact the similarities are quite suspicious.

WindowsPhone: Windows Phone offers a great drag and drop tool and the UI creation is a straight-forward procedure.

Android: Things are a little bit more complicated on Android. There is a basic drag and drop tool, but it doesn’t do a lot of things (it can’t really), designing the UI for so many different types of Android screen sizes and shapes is -despite the tools and the good documentation- more complicated than having to support a limited and documented set of screens.

5.UI Guidelines:

Another important issue is the design guideline. 

WindowsPhone: Microsoft came with the Metro UI. I find it so attractive, and many of my friends who work on the design industry find it splendid, so I have to trust their taste.
For more info you may read UI Design Guidelines for Windows Phone 8

Android: What concerns me most is that the design guidelines for Android are constantly changing (can you find anything similar between Android 1 and the Holo theme? I can’t!), you have to redesign your app often (this can be a good thing too) but I believe the Metro UI has come to stay and we won’t see any dramatic changes to the UI or the UX of the Windows Phone applications in the near future.

6.Which programming language is best?

Google made the decision to use Java as the programming language of Android to attract many Java developers. Microsoft did exactly the same, only they used C#. Cloning the good elements and coming to fix Java’s weaknesses, offering extra functionality, C# is a more modern programming language and this is a point for Windows Phone. Do not forget the power of the jars though, as the majority of Java’s extra libraries are very likely to work on Android and this is a big issue if you just think of the Apache Commons’ set of libraries. (I do not want to go deeper into programming language performance war since, let’s face it, testing execution speed of these languages on a 600mhz mobile device has little value). Memory consumption on the other side is a big thing, but Garbage Collectors on both languages do a very good job and it’s up to you to use the phone’s memory conservatively.

7.Emulator:

WindowsPhone: Speaking of emulators, Windows Phones have a big advantage here. Strangely enough (!), the Android emulator’s speed hasn’t improved over the years and is still tremendously slow. (Yes, years have passed since version 1). Windows Phone emulator works like a charm and starts at the speed of light compared to the Android emulator.

Android: Strangely enough (again) eclipse’s Android plugin and toolset is very buggy and lacks of many features. Also, many developers state that Visual Studio is a much more stable and mature IDE than eclipse, but I’m afraid I’m not in a position to confirm that :)

8.Development Cost:

And here comes another thing: cost. Not counting the cost of the operating system, since you have already paid for it

WindowsPhone: Windows Phone development has extra costs. if you want to publish an application or deploy your app on your device ,You have to pay for the full version of Visual Studio and you have to pay an annual fee (99$) which is now reduce to (19$) only due to summer offer .Good news are that if you are a student, some of these costs are withdrawn. 

Android: Android on the other hand, is significantly cheaper. You only need to pay 25$ once, and that is if you want to publish your apps on the Play store. Oh, I forgot, Android headsets are also cheaper, if you want to buy a real device!

9.Tablets:

WindowsPhone: Windows tablet does not run Windows Phone OS but it runs under windowsRT. windowsRT is a "light" version of Windows 8 that is dedicated for tablets. It does not run .exe files but only Windows store applications. But there is the Surface Pro which runs Windows 8 and .exe files. I should mention that 80% of Windows phone APIs are from windows8 APIs. So you can easily share your code between Windows Phone and Windows 8.

Note: Now WindowsPhone store 8.1 Development environment support more in common—a much larger API set, a similar app model and life cycle, a shared toolset, a common UI framework—Windows Phone and Windows Store app developer platforms truly have become one, single development platform.

Android: Android runs on smartphones, also on tablets. From the 3.0 version, Google added a bunch of APIs for larger screens so that apps will be more funny on tablet the mains components added were ActionBar and Fragments.


10.App Store Submission Process:

WindowsPhone: In order to publish windowsphone applications,There are two kinds of accounts: a developer account which will cost you 49$ and an Enterprise account which will cost you 99$(Present 19$ only due to summer special and it may be forever).The validation process will be very strict and take you about maximum 5 days and if your app is rejected, you will get an error report about what you have to change in your app.it don't have malwares in the Windows Phone Marketplace. It's a trusted store!

Android: In order to publish Android applications, you need to have a Google Play account,that will cost you 25 USD,you have to pass through a validation process which takes only 15 to 30 minutes.Google play has a lot of malwares, that's because of the very fast validation process and the huge number of Android developers.

Note: This post is does not pointing to which platform is winner,but as a developer it is best practices to know about both platform's environment  before going to develop apps.You can still discuss with me in the "Comments " section below.

Follow me always at  

Have a nice day by  :)