How do you rate this blog

Saturday, August 2, 2014

How to create a WCF Data Service using .NET

This post is w.r.t the post where in I had consumed WCF Data service in an android application. I have used SQL Server 2012 database, visual studio 2012 using ADO.Net

entity framework for creation of dataservices. We will create a sample WCF data service over an adventureworks database, this database can be downloaded from the

following link - Download.

Step1 - In visual studio 2012 click on New Projects on the start page and click on ASP.NET web forms as shown in the image below.

Step2 - Rightclick on the project and create a new folder and name it as AdventureDWData




Step3 - Once this is done, right click on the folder and click on new item. In the selection search for ADO.Net Entity Framework and name it as adventureModel.edmx


Step4 - It will give you an option to generate the entity model based on existing database or you can create your own tables in this which will inturn be made into a
database by the layer. Here we choose generate from database and click on next


   Step5 - Click on New Connections and provide the servername and credentials as shown in the image below Save the webconfig as AdventureWorksDW2012Entities1 and click
on next.

     Step6 - Then you will be taken to a screen where in you can select the list of table / views / stored procedures which you would like to expose in the data service. I
will go ahead and select all the tables as shown in the image below and click on Finish.



Step7 - Once done you can see the tables which have been pulled into the entity model which is shown in the image below.



Now that we have created the entity model with the list of objects to be exposed in the service let us go ahead and create the data service

Step8 - Right click on the solution and click on add > new item. In the selection click on WCF Data Service and name it AdventureDS1.

Step9 - Once done you will be taken to a AdventureDS.svc.cs, this where you bind the dataservice with the entity model. We need to do the following modifications
    a) Tell the dataservice where your entity model is stored by -
        "using AdventureworksDataService.AdventureDWData;"
    b) You need to tell the dataservice is over the following entitymodel this is done using the code below
        public class AdventureDS : DataService< AdventureWorksDW2012Entities >
    c) In the Initialize service function you can find the line "//config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);". Uncomment this line
       and modify it as "config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);"
       This is where you go ahead and mention the accessrights you want to set on each table / sp / views in your entitymodel. Here I have mentioned it as * which

means that all the entities in the entity model are readonly.

    The final code will like below:

using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;
using AdventureworksDataService.AdventureDWData;

namespace AdventureworksDataService
{
    public class AdventureDS : DataService< AdventureWorksDW2012Entities1 >
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        }
    }
}

    Step 10 - Right click on the service and select set as startpage.
Now right click on the solution and run it and you can see the following image as shown below with the url http://localhost:26636/AdventureDS1.svc/



If you add http://localhost:26636/AdventureDS1.svc/$metadata you can see the list of all the table and columns exposed in the data service as shown in the image below.



Saturday, July 26, 2014

Unable to detect Nexus 7 in developer mode in windows 8.1

I was doing some developement for Android tablet the developement environment was as given below:
OS: Windows 8.1, 64 bit
IDE: Android Studio
and wanted to test it on a physical tablet rather than a emulator so I connected my nexus 7 2012 model to my laptop then decided to turn on the debugging mode and the challenges came up

1) Developer Options was not to be seen in the settings menu:
   It seems you need to go to settings > About Tablet > Build and click on the build 7 times to enable the developer options. Wow its very developer friendly, how would anyone go ahead and figure that out, HTC inturn has a clear menu for developer option without having to do any of this circus.

2) ADB not detecting the device:
   Step1:   
    I enabled all the debugging options that I required and looked for the pop up which will enable my system to be used for debugging, it did not come up. Went to command prompt and using the adb (command : "adb devices") decided to list all the devices available for the test and it showed none.

   Step2:
    I went to the device manager to check the list of all devices and the image below shows my Nexus 7 and there was a warning sign next to it (as shown in the image below) which meant that either my driver was not updated or my driver was not present.





So went to the link -> Driver and downloaded the usb driver and extracted it, then I clicked on Nexus 7 and did a right click to update the driver, then clicked on browse my computer and went to the folder in which I had recently extracted the google usb driver for windows. Once it is done you will get a pop up on your nexus 7 which will ask for your permission to allow the computer to connect to your tablet, check the checkbox to always allow from the computer and click on OK. Once it is done you can execute the adb devices in the command prompt and you will see the device listed as shown in the image below.




Saturday, July 12, 2014

YouTube player in Android application

In the previous post I have described about a normal video player and streaming videos through it. In this post we will see how to stream youtube videos.

To obtain API key for accessing for youtube data api v3:


Step1: Logon to google developer console: Console
Step2: Once you login create a new project
Step3: On creation of new project go to API's and turn on You Tube API V3
Step4: Once this is done, click on credentials to generate a key for the API which we selected in the step above for android. Click on Create new key under Public API

access for android once it is done it asks you to create SHA1 fingerprint to do this execute the below command in command prompt

keytool.exe -V -list -alias androiddebugkey -keystore "<the directory in which debug.keystore is stored>" -storepass android -keypass android

example
keytool.exe -V -list -alias androiddebugkey -keystore "C:\Users\Bharath\.android\debug.keystore" -storepass android -keypass android

Once done copy the SHA1 and append the package name in which you will embed the api as show below
<SHA1 Key>;<package name of your solution>

To create the application:


Step1: Download the youtube api jar file from : Download
Step2: Add the jar file into the application
    a) Right click on the project and click on properties
    b) Click on java build path
    c) Click on libraries
    d) Add external jar
    e) Add YouTubeAndroidPlayerAPI.jar
    f) click on the text box next to the jar file in order and export tab

Step3: To allow internet access-
Add the code below into Android Manifest file
<uses-permission android:name="android.permission.INTERNET" />

Step4: Add the youtube player to the application:

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Step5: Code for youtube player in your application


import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.Toast;

public class Youtubevids extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {

    private YouTubePlayer myPlayer;
    private static final String myAPIKey ="<You Developer Key>";
    private static final int RECOVERY_DIALOG_REQUEST = 1;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_youtubevids);
        //Youtube player
        YouTubePlayerView myPlayer=(YouTubePlayerView) findViewById(R.id.youtube_view);
        myPlayer.initialize(myAPIKey, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.youtubevids, menu);
        return true;
    }

    @Override
    public void onInitializationFailure(Provider prov,
            YouTubeInitializationResult res) {
        // if there is an error
        if(res.isUserRecoverableError()){
            res.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
        }else {
            Toast.makeText(this, "Error: "+res.toString(), Toast.LENGTH_LONG).show();
        }
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_DIALOG_REQUEST) {
            // Retry initialization if user performed a recovery action
            getPlayerProvider().initialize(myAPIKey, this);
        }
    }

    protected Provider getPlayerProvider() {
        return (YouTubePlayerView) findViewById(R.id.youtube_view);
    }
   
   
    @Override
    public void onInitializationSuccess(Provider prob, YouTubePlayer player,
            boolean restore) {
    if(!restore){
        myPlayer=player;
        //The video which you want to play, you can use a list but for this post I am using a video.
        myPlayer.cueVideo("QQr7gM8MA3s");
    }
       
    }

}

Run the application:

Once this is done you are ready to run the app, you can run it on the emulator, but it requires youtube app to be installed in the emulator if you want to test it. I

have run this directly on mobile and the output is as shown in the snapshot given below.


Video Streaming in Android

In this post we will see how to stream videos in the applications in android.

To implement this the logic is

1) Allow internet access to the application
2) Add video control on the view
3) Add the media control to playback control to pause, play, move forward or backward.

We need a link from which we can stream videos. We will use the link below and stream video from this link
https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4

We are not using a youtube link in this post since those videos need to be accessed through the YouTube API.

So Lets get started, create a new project in eclipse using Android Jelly Bean and create a blank activity. Now we will implement logic which was described above-

1) Allow internet access to the application


  Since the application will stream video it needs internet access, so add the below code in the androidmanifest file allow the application to access the internet

<uses-permission android:name="android.permission.INTERNET" />

2) Add video control on the view


 Now we need to add the video control on the application

a) Go to the layout file and the below code

    <VideoView
        android:id="@+id/myVideoView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

b) Go to the java file in src file and add bind the layout control with the Uri as shown below

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videostreamer);

        //binding the view
        VideoView myvid=(VideoView) findViewById(R.id.myVideoView);
        //to set the uri that should be streamed in the video
        String videolink="https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4";
        Uri videoUri=Uri.parse(videolink);

        //add the control on the view
        myvid.setMediaController(mycontroler);

        //to play the video
        myvid.setVideoURI(videoUri);
        myvid.start();
       
    }

3) Add the media control


   Now we have added the player in the application, but we need to add the playback controls in the video control which will allow you to perform basic operations like play, pause, move forward or back.

        //play back controllers
        MediaController mycontroler=new MediaController(this);
        mycontroler.setAnchorView(myvid);
Add this code in the onCreate function described above, the final code will be

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videostreamer);
        //binding the view
        VideoView myvid=(VideoView) findViewById(R.id.myVideoView);
        //to set the uri that should be streamed in the video
        String videolink="https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4";
        Uri videoUri=Uri.parse(videolink);
        //play back controllers
        MediaController mycontroler=new MediaController(this);
        mycontroler.setAnchorView(myvid);
        //add the control on the view
        myvid.setMediaController(mycontroler);
        //to play the video
        myvid.setVideoURI(videoUri);
        myvid.start();
       
    }


Now lets run the application, the output will as shown in the snapshot below

Saturday, July 5, 2014

Consume WCF data service in Android


The basic need for any application is to send or receive data. So how do we make application read or write data in a mobile, the answer is Web services / WCF  / WCF REST Services / Web API.

In this post I am going use WCF data services. 

What is WCF Data Service?


    WCF data service is a component of .NET framework which helps you to expose the specific database object(s) as services over OData (Open data protocol). The

data exchange in this happens through Atom and JSON(Java Script Object Notification)

Setting up Environment:

1) Java should be installed in your machine. If you want to download Java go to the following Link
2) Eclipse should be present in the machine. This can be downloaded in the following Link
If there is any issue like
    a) Java not installed in your machine, please add the path where java is installed on your machine to the environment variable- PATH
    b) If you have an error saying jvm.dll not found, then please check the version of eclipse that you have and then the version of java that you have installed on the system. Given below are the combinations in which eclipse will work
    32 bit OS can have 32 bit eclipse and 32 bit java (pretty straight forward)
    64 bit OS can have 32 bit eclipse and 32 bit java only
    64 bit OS can have 64 bit eclipse and 64 bit java only
3) There are 2 ways to consume WCF data services
    a) OData4j
    b) restlet
   In this post I am going to use Odata4j. This can be downloaded through the Link
Now that we have the environment set up, lets get on with the app.

What should the app do?

1) The app should be able to connect to the WCF data service
2) Ability to access a table / entity which has been exposed over the service
3) Display it in the list view.


Now lets start off with the app by creating a new android app project in eclipse. Once created import the Odata4j jar file "odata4j-0.7.0-clientbundle.jar" which will

be present in the bundles folder of Odata4j download. To import you need to right click on the project > properties > libraries > Add external jar and select the file

mentioned above. Once done go to Order and Export tab and check the library file.

Step 1 - Android Manifest File: 
This application needs access to internet so go ahead and the following code to the android manifest file
    <uses-permission android:name="android.permission.INTERNET" />

Step 2 - Creation of Layout:

This application needs the following elements in the layout:
1) Button to call the service
2) List view to display the elements we want to display on the app

The layout will look like the code below:

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <Button
 android:id="@+id/callbtn"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Connect to WCF" />

 <ListView
 android:id="@+id/wcflistview"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>

</LinearLayout>


Step 3 - Accessing the web service:

We need a wcf data service from which we will access an entity, we have a service called as http://services.odata.org/Northwind/Northwind.svc/. To check what are the

entities exposed in the service use the following link http://services.odata.org/Northwind/Northwind.svc/$metadata. In this post I will use Categories. To see what

data is present in this entity use the uri http://services.odata.org/Northwind/Northwind.svc/Categories

The code for connecting is given below along with the comment as to why is it used

package com.service.wcfexample;

import java.util.ArrayList;
import java.util.List;

import org.odata4j.consumer.ODataConsumer;
import org.odata4j.core.OEntity;
import org.odata4j.jersey.consumer.ODataJerseyConsumer;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Wcfserv extends Activity {
Button callbtn;
ListView wcflist;
ArrayList cat;
ArrayAdapter cat_adpt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wcfserv);
        callbtn=(Button) findViewById(R.id.callbtn);
        wcflist=(ListView) findViewById(R.id.wcflistview);
        cat=new ArrayList();
       
        callbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            // TODO Auto- generated method stub
            new wcfService().execute();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.wcfserv, menu);
        return true;
    }

    public class wcfService extends AsyncTask<Void, Void, ArrayList<String>>{

        @Override
        protected ArrayList<String> doInBackground(Void... arg0) {
            //To call the service
            ODataConsumer con = ODataJerseyConsumer.create("http://services.odata.org/Northwind/Northwind.svc");
            //List which will hold a particular entity from the consumer
            List<OEntity> myEntity = con.getEntities("Categories").execute().toList();
            //To add the elements of myEntity into a arraylist
            if (myEntity.size() > 0) {
                for (OEntity entity : myEntity) {
                    cat.add(entity.getProperty("CategoryID").getValue().toString()
                    + " - "
                    + entity.getProperty("CategoryName").getValue()
                    .toString());
                    }
                }
            return cat;
            }

            @Override
            protected void onPostExecute(ArrayList<String> result) {
            super.onPostExecute(result);
            //displaying the result
            cat_adpt = new ArrayAdapter<String>(Wcfserv.this,
            android.R.layout.simple_list_item_1, result);
            wcflist.setAdapter(cat_adpt);
           
        }
       
       
       
    }
   
   
}

Step 4- Run the application:
Now run the application and the screen will be as shown in the snapshot below:




Now Click on connect to WCF the output will as shown below:







Saturday, May 3, 2014

Changing the color of an app based on Light Sensor

Recently I got a strange requirement that the theme of the app should change based on the light conditions. So my initial approach was to inflate a new theme as and when the conditions change but that was a bad idea since it would be a very bad user experience since there would be a period where in the app would reinitialize, so I  stopped over engineering about the problem and used a simple approach of recoloring the layouts. In this post I will just go ahead and create a simple app which shows the current reading of brightness in terms of lux, if the brightness is below 10 lux the background becomes black and the text becomes white and if the brightness the logic is simple given below are steps :

1. Register the Light sensor if it is present.
2. Read the sensor value.
3. if the value is above 10 LUX then change the theme having black background and white text else have white background and black text.

Now that we know the logic lets go ahead and code this.

Step 1: Create a new project using andoroid 4.3 in my case I have called it as LightSensor
Step 2: Go to the LightSensor.java file within src folder of the project and lets implement the logic that we have discussed above.
   
    Step a: We need to see if the Light sensor is present or not and if present we need to register the light sensor to obtain readings. This can be done using the code below:
        if(curSensor!=null){
            SM.registerListener(this, curSensor, SM.SENSOR_DELAY_FASTEST);
           
        }
        else{
            Values=(TextView) findViewById(R.id.textView1);
            Values.setText("Unable to register sensor");
        }
    If you want to know in detail how to use light sensor then go my post given in this link LightSensor
   
    Step b: Now that we have registered we need to obtain the value, this is done using the code below on the onSensorChanged function which you have to override if you implement SensorEventListener.
       

        if(event.sensor.getType()==Sensor.TYPE_LIGHT){
            // to obtain the light sensor value
            Values.setText("Value= "+event.values[0]+" lux");
            LSVal=event.values[0];
            //to call the theme changer based on the light condition
            if(event.values[0] > 100){
                changeTheme(1);
                displays.setText("Good Light Conditions");
            }
            else{
                changeTheme(0);
                displays.setText("bad Light Conditions");       
            }
        }
       
Step 3: You have now completed the code for reading the light sensor value, now we need to write a simple code to change the layout based on the condition. I have used a parameter which helps me to find out which layout I should shift to when there is a change light condition, you can do it in a much better way, this is just for an example.

     public void changeTheme(int theme){
        if(theme==1){
            //Layout Background
            LL.setBackgroundColor(Color.WHITE);
            //Text Background
            Values.setBackgroundColor(Color.WHITE);
            Values.setTextColor(Color.BLACK);
            displays.setBackgroundColor(Color.WHITE);
            displays.setTextColor(Color.BLACK);
            sensorSetting.setBackgroundColor(Color.WHITE);
            sensorSetting.setTextColor(Color.BLACK);
            //Edit Text
            sensortresh.setBackgroundColor(Color.WHITE);
            sensortresh.setTextColor(Color.BLACK);           
        }
        else{
            //Layout Background
            LL.setBackgroundColor(Color.BLACK);
            //Text Background
            Values.setBackgroundColor(Color.BLACK);
            Values.setTextColor(Color.WHITE);
            displays.setBackgroundColor(Color.BLACK);
            displays.setTextColor(Color.WHITE);
            sensorSetting.setBackgroundColor(Color.BLACK);
            sensorSetting.setTextColor(Color.WHITE);
            //Edit Text
            sensortresh.setBackgroundColor(Color.BLACK);
            sensortresh.setTextColor(Color.WHITE);
        }
    }

    The above code changes the background and the text colors, you can modify the colors based on your need. You can do various things like if the light conditions are bad you can auto adjust the brightness of the screen (although this is already done by the phone). Given below is are screen shots of the app in different light conditions.

Good light Condition

Bad Light Condition

If you have a better way of doing the same please do let me know.