Free eBooks – From Microsoft Press

Hi Folks,

Microsoft has released three eBooks free of cost. Below is the information about the eBooks.

  1. Windows 10 IT Pro Essentials Support Secrets
    https://blogs.msdn.microsoft.com/microsoft_press/2016/07/14/free-ebook-windows-10-it-pro-essentials-support-secrets/
  2. Configuring Microsoft SharePoint Hybrid Capabilities
    https://blogs.msdn.microsoft.com/microsoft_press/2016/07/06/free-ebook-configuring-microsoft-sharepoint-hybrid-capabilities/
  3. Microsoft Platform and Tools for Mobile App Development
    https://blogs.msdn.microsoft.com/microsoft_press/2016/06/22/free-ebook-microsoft-platform-and-tools-for-mobile-app-development/

Tuple, a new data structure in C#

Tuple is an interesting data structure in C#. It contains number and sequence. You can create tuple of 1 to 7 elements. Additionally you can create tuple of eight element using the TRest element. TRest element allows you to add nested tuple.

Let see example of basic tuple. We have student entity having marks fro seven subject. We can define this data structure by using tuple.

var tupleStudent = Tuple.Create("Mandar Badve", 87, 45, 76, 78, 64, 71, 80);
Console.WriteLine(""+ tupleStudent.Item1 + " got " + tupleStudent.Item2 + " marks in first subject.");
//// OUTPUT: Mandar Badve got 87 marks in first subject.
Console.WriteLine(""+ tupleStudent.Item1 + " got " + tupleStudent.Rest.Item1 + " marks in seventh subject.");
//// OUTPUT: Mandar Badve got 80 marks in seventh subject.

In above example first console will print the name of student accessed using Item1 of tuple and marks got in first subject accessed using Item2 of tuple. In second console we have access nested tuple using Rest property of tuple.

You can create tuple by using two ways.

  • Using constructor
var tupleUsingConstructor = new Tuple<string, int, int, int, int, int, int>("Mandar Badve", 87, 45, 76, 78, 64, 71);
  • Using helper method Create()
var tupleByHelperMethod = Tuple.Create("Mandar Badve", 87, 45, 76, 78, 64, 71, 80);

Create method have different overloads as follows:

Name
Description
Create<T1>(T1) Creates a 1-tuple, or singleton
Create<T1, T2>(T1, T2) Creates a 2-tuple, or pair.
Create<T1, T2, T3>(T1, T2, T3) Creates a 3-tuple, or triple.
Create<T1, T2, T3, T4>(T1, T2, T3, T4) Creates a 4-tuple, or quadruple.
Create<T1, T2, T3, T4, T5>(T1, T2, T3, T4, T5) Creates a 5-tuple, or quintuple.
Create<T1, T2, T3, T4, T5, T6>(T1, T2, T3, T4, T5, T6) Creates a 6-tuple, or sextuple.
Create<T1, T2, T3, T4, T5, T6, T7>(T1, T2, T3, T4, T5, T6, T7) Creates a 7-tuple, or septuple.
Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1, T2, T3, T4, T5, T6, T7, T8) Creates a 8-tuple, or octuple.

Get location coordinates with windows phone application

shimla-13

Location API

You can use Windows Phone’s location API if your windows phone application needs location of user. In this post we will see how to use location API.

Let’s code

Getting started by creating new windows phone application.

CreateProject

Double click on ‘WMAppManifest.xml’ file.(You can read here for more details.) You will find this file inside projects Properties.

Capabilities

Go to Capabilities tab and then select ‘ID_CAP_LOCATION’ capability. This will tell to Windows Phone Store that this application need access to users location. While installing application user will see prompt message about the need of location service. This is the first step of get permission to access location from the user.

LocationServiceCapabilities

We need some user interface to show location status. Copy the following code block inside the default grid created by visual studio template.

XAML Code

 <StackPanel> 
    <Button x:Name="btnGetLocation" Click="btnGetLocation_Click">Get Location</Button> 
    <TextBlock x:Name="txtLatitude"></TextBlock> 
    <TextBlock x:Name="txtLongitude"></TextBlock> 
    <TextBlock x:Name="txtStatus"></TextBlock> 
</StackPanel>

Finally your XAML code and designer will looks like this.

XAMLCode

Code behind

Go to MainPage.xaml.cs and add following method

protected override void OnNavigatedTo(NavigationEventArgs e) 
 { 
 if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationPermission")) 
 { 
 //// User already allowed app to access location 
 return; 
 }
 
 //// User not allowed app to access location 
 //// Ask user to allow

 MessageBoxResult result = 
 MessageBox.Show("Application needs your location. Please allow.",  "Location", MessageBoxButton.OKCancel);
 
 if (result == MessageBoxResult.OK) 
 { 
   //// If user allows to access location 
   IsolatedStorageSettings.ApplicationSettings["LocationPermission"] = true; 
 } 
 else 
 { 
    //// If user not allows to access location 
    IsolatedStorageSettings.ApplicationSettings["LocationPermission"] =    false; 
 } 
 IsolatedStorageSettings.ApplicationSettings.Save(); 
}

User will navigate to the MainPage.xaml page when he open application. At this time OnNaviatedTo method get called. This method first check user already set permission to access location.(No check here if he accepted or rejected location access request. We will check it later).

If user has not given permission to access location, we will show Ok Cancel message box of asking the permission to access location. If he responds with Ok, we will store the value of ‘LocationPermission’ key as true else false if user select Cancel option.

OnNevigaetedTo

Get Location

Below is the button click event handler. Copy code and paste it below to above method.

private async void btnGetLocation_Click(object sender, RoutedEventArgs e) 
 { 
 if (!(bool)IsolatedStorageSettings.ApplicationSettings["LocationPermission"]) 
  { 
    return; 
  }
 Geolocator geolocator = new Geolocator(); 
 geolocator.DesiredAccuracyInMeters = 50;

 try 
  { 
   Geoposition geoposition = await geolocator.GetGeopositionAsync( 
   maximumAge: TimeSpan.FromMinutes(10), 
   timeout: TimeSpan.FromSeconds(10) 
   );

   txtLatitude.Text = "Latitude: " +       geoposition.Coordinate.Latitude.ToString(); 

   txtLongitude.Text = "Longitude: " + geoposition.Coordinate.Longitude.ToString(); 

  } 
  catch (Exception) 
  { 
    txtStatus.Text = "Your phone may not have geolocation API support."; 
  } 
 }

This method first check weather user allowed to access location or not by accessing the value of key ‘LocationPermission’ from Application Settings. If user not allowed then we will simply return.(You can show message to user here. E.g. You have rejected permission to access location.)

If user allows, we will create object of Geolocator. Set property ‘DesiredAccuracyInMeters’ to 50 meters. This option defines the accuracy of the location. You can get object of Geopostion by using the GetGeopositionAsync method of Geolocator object. Geoposition object contain Coordinate property which have Latitude and Longitude values. Set this values to the label as text.

Here is the final screen where you will see the Latitude and Longitude values on screen.

Result

Conclusion

In this post we have seen the following things

  • How to add location API capability in the manifest file.
  • Ask user to allow to access location.
  • Save user response in application settings.

In the next post we will see how can we use this coordinates to show location on maps.

AngularJS directives and custom directives

Angular JS directives and custom directives

Angular is very popular JavaScript framework and custom directives are the heart of the angular. We will take look at the directives.

Angular directive

Directives are the command, tells angular what operations can angular do on the DOM element, attribute or the children of the element. These angular directives extend the HTML attributes. Angular directives are prefixes by ng-. Following are the some popular directives by angular.

ng-app: It initializes the angular application.

ng-init: It initializes the data of application.

ng-model: It provides the access to the model data for binding to the HTML controls.

For example

<div ng-app="firstApp" ng-init="firstName='John'">
<p>This is angular js application</p>
Change the name: <input type="text" ng-model="firstName" />
<p>My name is {{firstName}}
</div>

In above example firstApp is the name of the angular application. The name is not mandatory. You can keep blank as well. Next attribute is ng-init which initializes the data used by the application. By using the ng-model textbox can change the value of the firstName variable defined in the model. And finally we have used {{firstName}} to display the actual value of the variable.

Angular custom directives

In the above section we have seen the directives provided by the angular framework. Angular can also give you power to extend the directives. You can create and define your own directives.

Take a basic example below.

angular.directive('myStudent', function(){
    return{
        template: 'Name: {{firstName}} {{lastName}} <br />Roll No: {{rollNumber}} <br />Address: {{address}}'
    };
});

In above script we have created directive of name ‘student’. Every directive should return the object. Here we are returning the object with the template field. The value of template contains the html content. When we use the student directive, it is replaced with the html content provided as template.

You can use directive like

<div my-student></div>

Here we have used attribute ‘my-student’. Directives in angular are named as camelCase. We can use the directive in DOM by delaminating words with dash.

You can see something like this.

John Cart
1002
Sweden

Extending template property

If your template contains lots of the html content then it will not feasible to provide like above method. You can also provide the template URL which contains the URL of the html page you want to use for the template.

angular.directive('student', function(){
    return{
        template: 'studentTemplate.html'
    };
});

Restrict property

Restrict is another option you can use in the directive definition. Following are the possible values for the restrict option.

  • A – defines the attribute directive
  • E – defines the element directive
  • C – defines the CSS class directive

You can combine the above values for you need. By default if you don’t provide any values just like above examples, directive take ‘AE’ value. In this case you can define directive on the attribute level and also element level.

angular.directive('student', function(){
    return{
        template: 'studentTemplate.html'
        restrict: 'E'
    };
});

Form input type range element (Slider control)

HTML5 gives us very useful slider control. Lets look at the syntax and how to use the slider control.

<input type="range" name="price" min="1" max="10" value="1" />

Here are the different attributes you can use with range input.

  • min: specify the minimum value allowed.
  • max: specify the maximum value allowed.
  • step: specify the value of the interval.
  • value: specify the default value of the slider.

You can use event onchange to track selected value.

<input type="range" max="10" min="1" name="quantity" value="1" onchange="alert('Selected value: '+ this.value);" />

Demo

Select the quantity of the product:

Check the browser compatibility for the input type color

http://caniuse.com/#feat=input-range

CSS :before and :after Pseudo-element

The before and after insert content before and after of the element .

Let’s see an example below.

Here is HTML:

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc adipiscing tristique dictum. Nunc odio sapien, sagittis a viverra non, consequat sed urna. Nunc blandit mi nisl, ut condimentum mi iaculis ut. Morbi eget ante luctus, venenatis augue sed, condimentum tortor. Aliquam pretium commodo enim, vel consequat lacus dignissim quis. Vivamus tristique luctus egestas. Mauris aliquam enim et velit rhoncus, a tempus neque faucibus. Pellentesque nec erat ut nunc ultrices suscipit eget ac metus. Suspendisse eget auctor eros, ut dignissim ante. Nunc non justo facilisis odio blandit euismod non nec metus. Quisque eu felis nisl. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam tempus consectetur lorem vitae facilisis.
</p>

And here is CSS

p:before
{
    content:"'";
    font-weight:bold;
}
 p:after
{
    content:"'";
    font-weight:bold;
}

In the above css we have applied: before and :after on the p element. We have set content to single quote and weight of the font is set to bold.

Here how the p element will render to browser.

beforeandafter

You will see the single quote appears before and after the content of the p element.

You can see live example here http://jsfiddle.net/mandarBadve/3ye7E/

HTML5 web storage – offline storage solution for the web

Test3

Using HTML5 you can store data into user’s browser. Before HTML5, there was only one way to store data using cookies. This web storage stores data in key/value pair. You can use this technique to store data offline.

How to check that browser supports web storage?

if(typeof(Storage) !== “undefined”)
{
// Browser supports web storage. So you can use local and session storage
}
Else
{
// Browser does not support web storage.
}

There are two types of the web storage

  1. Local Storage
  2. Session Storage

Local Storage

You can store data into local storage like

localStorage.key = “value”;

And you can retrieve it as

var localStorageValue = localStorage.key;

This storage is persisted even you closes and reopen the browser.

Session Storage

This storage is same as the local storage. One thing differs from local storage is that, the data will be lost if user closes the browser. So if you want to store data per session, go with this storage.

You can store data as follows

sessionStorage.key = “value”;

After you can retrieve as

var sessionStorageValue = sessionStorage.key;
 

How to check/debug web storage is working or not?

Developer tools of the browser will show data stored into the web storage. Following image taken from w3schools.com describes the where you can find the web storage.

HTML5 web storage

 

You can check your browser supports how many HTML5 features just opening http://html5test.com/ into your browser.

Enrich user interface of your web application with Bootstrap UI framework

Bootstrap is very reach UI framework, flexible and responsive. It is made by Twitter and hosted on github.

You can find the more details at http://getbootstrap.com/

Let’s start to integrate this framework into your web application.

Very first you need to download framework files from bootstrap website mentioned above. Download will contain ZIP file (bootstrap-x.x.x-dist.ZIP)

After extracting the downloaded ZIP file, you will get three folders:

  • css: This folder contains style sheets files for the bootstrap framework and theme
  • fonts: This folder contains necessary files for the fonts
  • js: This folder contains JavaScript files for bootstrap framework.

For the further process I have used Visual Studio to create and manage web application. You can use any editor instead of the Visual Studio.

In the Visual Studio go to the menu:  File -> New -> Project. It opens New Project dialog. Select ASP.NET Web Application and give the name for the solution.

Enrich user interface of your web application with Bootstrap UI frameworkClick on OK then Select Empty project type.

select empty project template

Click OK to create project.

You will see solution created as below.

Solution1

Right click on ‘WebAppWithBootstrap’ the solution select Add then select HTML Page.

Solution2Give the name as index.html

Solution3

Index.html file is created opened in editor.

Now add folder ‘Bootstrap’ by right-click on solution and choose Add and then New Folder.

Solution4

Then create two folder called ‘css’ and ‘js’ inside the folder ‘Bootstrap’

Solution5

Now copy the ‘bootstrap.min.css’ file from css file folder of the extracted Bootstrap zip file to the css folder of the solution. Also copy the ‘bootstrap.min.js’ JavaScript file from js folder of the extracted Bootstrap zip file to the js folder of the solution.

Solution6

Now we need to give references of the added css and js file into index.html file as follows.

Solution7

Here we have added meta tag with viewport and set content width=device-width. This made your page responsive.

We have done with the integration of Bootstrap framework with web application.

Now open the page into browser.

Solution8