Sunday, June 7, 2015

Alternative way for enable developer mode in windows 10 device

Hi ,

Have you ever seen bug when going to enabling developer mode in windows 10 preview (IP)? The application crashes.

Now how we enable developer mode for application development ?

There is option available. When we are deploying apps with side loading in windows 8/8.1 we are doing the policy editing to allow app installation in client machine. the same is helpfull here too

Open your group policy editor  -> Computer Configurations-> Administrative templates -> Windows Components -> App Package development 

In there enable
Allow development of windows store apps and installing them from integrated development environment ...
and
allow all trusted apps to install 





You are done and enjoy  

Saturday, April 4, 2015

Server Socket (TCP) With Microsoft Azure

When we working on the real time applications Microsoft azure provides the facilities to run our all kind of applications from oldest to latest technologies. With my earlier post i explained how to create SignalR applications for real time operations

Today I'm gonna introduce create Server socket with the Azure .


1. Create new Azure Cloud project
















2. Create new Azure Worker Role  with the solution. I named it as Socket Worker 














3. Then you need to add endpoint to Worker role. If you are working on TCP Just add TCP endpoint in the worker role  as follows


















External clients use public port to send traffic to service using public port

actually they send traffic through this port .  Here is how people send traffic http://mysitedomain:2020/

Azure load balancer send the traffic (re route the traffic to Worker Role) through the private port to the Virtual Machine that run the worker role

(More)

4. Then Create your regular TCP Listener (It  may be UDP/TCP/Http/Https, Azure support all  ) Code inside the run

Replace the Run() as following with auto reset event

private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
public override void Run()
       {
           TcpListener listener = null;
           try
           {
               //Create TCp Listener to Listen endpoint define in the Worker Role
               listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TcpEndpoint"].IPEndpoint);
               listener.ExclusiveAddressUse = false;
               listener.Start();
           }
           catch (SocketException)
           {
               Trace.Write("Echo server could not start.""Error");
               return;
           }
 
           //Listen to the all requests 
           while (true)
           {
               //Handle requests Asynchronously 
               IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
               connectionWaitHandle.WaitOne();
           }
       }

5. Then create Async request handle with following. **All important areas are commented


      /// <summary>
/// Handle Async requests 
/// </summary>
/// <param name="result"></param>
private void HandleAsyncConnection(IAsyncResult result)
{
    // Accept connection 
    TcpListener listener = (TcpListener)result.AsyncState;
    TcpClient client = listener.EndAcceptTcpClient(result);
    connectionWaitHandle.Set();
 
    // Setup reader/writer 
    NetworkStream netStream = client.GetStream();
    StreamReader reader = new StreamReader(netStream);
    // Show application 
    string input = string.Empty;
    while (true)
    {               
 
        //Get the input line 
        input = reader.ReadLine();
 
        Trace.TraceInformation(input);
    }
    // Done! 
    client.Close();
}

Run and enjoy  :)







Full Code In Media Fire 
http://bit.ly/SocketAzure













Sunday, March 8, 2015

MongoDb With C Sharp

This post is related with the post that I put few months ago, If you don't have already configured Mongodb on the machine Here is the post that I put

Big question ?? How we use Mongo With C#? Is it hard?

Its really easy to use Mongo in .NET ,

Here im going to create Asp.NET Web API project for demonstration. (You can use any type of project )

Then Install official MongoDb Driver for .NET it name as MongoCsharpDriver Nuget package














Here is screenshot of my Mongo Database and document that I'm going to use


Here is the class I created for mongo operations


using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace MongoDb.Models.MongoModels
{
    public class MongoConnection
    {
        private MongoServer _ServerConnection { getset; }
        public MongoDatabase _Database { getset; }
        public string _ConnectionString { get { return "Server=localhost:27017"; } }
        public MongoConnection()
        {
            MongoClient client = new MongoClient(_ConnectionString);
            this._ServerConnection = client.GetServer();
            ////////////////////Old way of create server////////////////////
            //this._ServerConnection=MongoServer.Create(_ConnectionString);
 
            //Set the database 
            this._Database = _ServerConnection.GetDatabase("DocumentOrDb");
        }
 
        /// <summary>
        /// Get all data in the document
        /// </summary>
        /// <returns></returns>
        public MongoCursor<BsonDocument> GetAllUserdata()
        {
            return _Database.GetCollection<BsonDocument>("UserDetails").FindAll();
        }
 
        /// <summary>
        /// Insert Item
        /// </summary>
        /// <param name="name"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        public BsonDocument Insert(string name, string address)
        {
            MongoCollection<BsonDocument> UserDetails = _Database.GetCollection<BsonDocument>("UserDetails");
 
            BsonDocument NewRecord = new BsonDocument()
            {
               { "Name",name},
               {"Address",address}
            };
 
            UserDetails.Insert(NewRecord);
            //return last inserted element 
            return UserDetails.FindAll().Last();
        }
    }
 
}

**This code is use latest standards of official mongo driver up to today 
Then use this class with the code. That's It

Enjoy :)









Full Code 
http://bit.ly/MongoCSharp

Thursday, March 5, 2015

First SignalR Codes

Lets start SignalR with hands on ,

Not like usual chat demos in SignalR , We are going to make counter application which displays number of connected nodes to the web

1. Create New empty ASP.Net web project with visual studio
2. The install following Nuget on the Application
   Microsoft.AspNet.SignalR
 After Installing SignalR Your solution automatically get the Scripts for signal R














3. Add Hub Class to the solution by Add -> New Item -> SignalR Hub Class(v2)
Name it as CountHub 








4. Then Modify the CountHub with following code
[HubName("hithub")]
   public class CountHub : Hub
   {
       public static int count = 0;
 
       /// <summary>
       /// Once user open window with this URL hitter called 
       /// </summary>
       public void Hitter()
       {
           count++;
           Clients.All.OnHit(count);
       }
 
       /// <summary>
       /// User disconnected OnDisconnected automatically fired 
       /// </summary>
       /// <param name="stopCalled"></param>
       /// <returns></returns>
       public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
       {
           count--;
           Clients.All.OnHit(count);
            return base.OnDisconnected(stopCalled);
       }
   }

in here HubName attribute should be start with simple letter. Otherwise it will not working

In here Client.All broadcast with all connected clients .

5. Then add Owin Start up class to build the start up with the web application Named it as StartUp



6. add Configuration for SingnalR in Startup
public void Configuration(IAppBuilder app)
       {
           app.MapSignalR();
       }

8. Now we are done with SignaR server side coding. Lets build HTML client for SignalR
Create html page in solution (default.html) and refer signalR and Jquery to the web page

<script src="Scripts/jquery-1.6.4.js"></script>
   <script src="Scripts/jquery.signalR-2.2.0.js"></script>
  
9. Then add following script after it . Comments discribes the code

<script type="text/javascript">
    $(function () {
        //Create hub connection 
        var conection = $.hubConnection();
 
        //create hub proxy 
        var hub = conection.createHubProxy("hithub");
 
        //get message with the hub proxy to latest update in count 
        hub.on("OnHit"function (count) {
            $('#count').text(count);
        });
 
        //Call hitter 
        conection.start(function()
        {
            hub.invoke('hitter')
        });
    })
</script> 
 
 
10. Modify the body of html as follows

<body>
    <h2 id="count">0</h2>
</body>
 
 

Run and enjoy,


Happy coding







Full Code 
http://bit.ly/1G1YOze

Thursday, February 26, 2015

MethMvvm Visual Studio extention for C Sharp developers


  • meth - public method
  • methp - private method
  • propmvvm - mvvm property
 Features & Benefits
This will enable you to create methods in C# easily with double tap. And also enabled to crate MVVM properties easily. to do thet you have to create PropertyChange event . as follows,

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
public event PropertyChangedEventHandler PropertyChanged;
 
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(thisnew PropertyChangedEventArgs(name));
            }
        }

CodePlex Project and Download Link

Friday, February 6, 2015

Prism MVVM pattern with Applcaition development

Prism is one of the design patterns which defined by Microsoft Patterns and Practices team for building composite Applications in C# , XAML (WPF,Store Applications etc ) .

Why MVVM is not enough ?

When we creating application with MVVM there is few questions and practices we need to figure out. 
  • Should I use Prism to provide support for MVVM?
  • Should I use a dependency injection container?
    • Which dependency injection container should I use?
    • When is it appropriate to register and resolve components with a dependency injection container?
    • Should a component's lifetime be managed by the container?
  • Should the app construct views or view models first?
  • How should I connect view models to views?
    • Should I use XAML or code-behind to set the view's DataContext property?
    • Should I use a view model locator object?
    • Should I use an attached property to automatically connect view models to views?
    • Should I use a convention-based approach?
  • Should I expose commands from my view models?
  • Should I use behaviors in my views?
  • Should I include design time data support in my views?
  • Do I need to support a view model hierarchy?
 (reference https://msdn.microsoft.com/en-us/library/windows/apps/xx130657.aspx )

Why Prism?

Prism contains wire frame which can help to accelerate application development in  MVVM and It already contains commonly required core features in application development.


Let's Start Coding 


Here we are going to create windows store application using Prism

1. Create new windows store application project (Blank application)
2. Go to package manager console or manage nuget packages and install prism nuget to the application

 3. Now starts coding . Here we are using MVVM and I create few folders to isolate resources in the project such as
  • ViewModel - for ViewModel
  • Model - for Model
  • Controles - for BaseControls
  • View - for XAML pages 
  • Enum - for enumerations
  • Interfaces - for Interfaces 
and then put MainPage.xaml  in to teh View Folder (drag and drop)

Now my project like this


















 Code for prism
 Now we have to convert our application to prism
1. App.XAML and App.XAML.cs

<prism:MvvmAppBase
    x:Class="SamplePrism.App"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SamplePrism">
 
</prism:MvvmAppBase> 
 
 
sealed partial class App : MvvmAppBase
   {
       public App()
       {
           this.InitializeComponent();
       }
 
       protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
       {
          //Main is the name of view i need to navigate 
           this.NavigationService.Navigate("Main"null);
 
           return Task.FromResult<object>(null);
       }
   } 


2. Then create PageBase in controls  from Prism MVVM

public abstract partial class PageBasePage,IView
   {
   } 
3. Then Use this page base in our Views, xaml

 Change MainPage.xaml and MainPage.xaml.cs as  follows
<controls:PageBase
    x:Class="SamplePrism.Views.MainPage"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns:controls="using:SamplePrism.Controls"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SamplePrism.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    prism:ViewModelLocator.AutoWireViewModel="True"
    xmlns:designtime="using:SamplePrism.DesignTimeViewModel"
    mc:Ignorable="d">

public sealed partial class MainPage : PageBase
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
    }

4. In here I'm craeting Interface to keep the properties of MainPage But this is optional. You can jsut implement the ViewModel without this interface


Here is My interface


public interface IMainPageViewModel
   {
       string Title { getset; }
   }


5. Lets Starts MainPageViewModel

public class MainPageViewModel : ViewModelIMainPageViewModel
   {
       string _Title = default(string);
       public string Title { get { return _Title; } set { SetProperty(ref _Title, value); } }
 
       public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<stringobject> viewModelState)
       {
           this.Title = "Hello prism";
       }
   }

With prism MVVM it conains basic funtions in store app such like OnNavigatedTo , OnNavigatedFrom etc. You can directly use them inside the ViewModel 

Run and Enjoy the Prism.

It is really easy to build in complex applications in enterprise level. even if you  not like Prism code in specific scenario you can switch with your old MVVM too inside the same project










Full Code 
http://bit.ly/1DL68OI







Tuesday, February 3, 2015

Tips to build Real time Applications (SignalR)

What is real time ? People who use the applications they need to see the actions one it happens . No delays or refreshing even it is desktop application, App , web or some other application.

How its possible ?

There is few options that developer can looking at.
1. Running background thread
2. Use SignalR

1st option that I describe here is not the best option in most of the times. Running background thread all times is resource consuming and it always use pulling (grab the data from the remote). And there is security concerns as well. But believe me there is some applications which we need to use this and thread is worth than other .


Most pf the time best option is SignalR

What is SignalR ?
 SignalR is series of abstractions around various methods of providing persistent Http Connections. Simply it makes real time communication without effort 

 Where ?
SignalR can be in
  1. Web application
  2. Desktop Applicaton 
  3. App (windows /iOs/Android/berry ) 

 It is cross platform tool  (totally open source) which capable of running with any platform.


SignalR is Client Server

To use SignalR you need to have Server (basically you can create serever with asp.net i'll add posts future)

And client application, (if you use javascript no need to have client nuget to consume SignalR) you can make any application by just adding SignalR nugets to your project.

Microsoft Asp.Net SignalR 









Modern servers from Windows Server 2012 is support SignalR (Real time Communication perfectly )

There is life beyond  Web Sockets


Lets meet with handons later :) enjoy

SignalR Coading 

Friday, January 23, 2015

Microsoft Windows 10 Event.




Sunday, January 18, 2015

Working in designtime with Data in MVVM

If we develop applications ( XAML based) we have a problem with see the data in design view. Every application become successful when its interface is attractive. If our application is based on internet or any other computational task there is difficulty on make Interfaces without running the application real time. Here is solution for it

Use design time data binding which already with the xaml based application 

Today we going to develop the windows 8.1 store application. ( This is same with any XAML based Application )

1. Create Windows 8.1 store application form the Visual studio. (I named it as DesignTimedata )
2. Create ViewModel to bind the run time data , In following here is My MainViewModel.cs

With this example we are not going to the use internet or other tasks .therefore just hard corded the values in constructor 

namespace DesignTimeData.Runtime
{
    public class MainViewModel:INotifyPropertyChanged
    {
 
        private string _Title { getset; }
        public string Title
        {
            get { return _Title; }
            set
            {
                _Title = value;
                OnPropertyChanged("Title");
            }
        }
 
        private string _Description { getset; }
        public string Description
        {
            get { return _Description; }
            set
            {
                _Description = value;
                OnPropertyChanged("Description");
            }
        }
 
 
 
        public MainViewModel()
        {
        // Hard coded runtime data
            this._Title = "Title in Run time";
            this._Description = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.";
        }
 
        // Create the OnPropertyChanged method to raise the event 
        // Use in MVVM
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(thisnew PropertyChangedEventArgs(name));
            }
        }
    }
}


2. Then bind the ViewModel to the View with relevant tags.
You can use Singleton or Page Resource binding . In here Im using Bind the ViewModel to the Page in XAML . It gives me intellisense in XAML .

Here is my MainPage.xaml

<Page
    x:Class="DesignTimeData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignTimeData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:runtime="using:DesignTimeData.Runtime"
    mc:Ignorable="d">
    
    <Page.DataContext>
        <runtime:MainViewModel/>
    </Page.DataContext>
 
3 .Then Create New Class which have exact name of your view model. Better to use different namespace / folder . In this case It is MainViewModel 
Here is my design time ViewModel. It will contains all test data which displayed in design view in visual studio


namespace DesignTimeData.DesignTimedata
{
    public class MainViewModel
    {
        public string Title { get { return "DesignTime Title"; } }
 
        public string Description { get { return "Design time description"; } }
    }
} 

4. Then lets bind the design time data into the design (xaml) . In here there is always tag like this
      mc:Ignorable="d" 
with every page. something defines under this tag will not be displayed in the runtime. then this is the one that we need to use.

With this d we can define all the properties which page have and change them. but none of them are effecting the real application .

Lets bind the ViewModel to the page and use it with design time . Here is my full page

<Page
    x:Class="DesignTimeData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignTimeData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:desgn="using:DesignTimeData.DesignTimedata"
    xmlns:runtime="using:DesignTimeData.Runtime"
    mc:Ignorable="d">
    
    <Page.DataContext>
        <runtime:MainViewModel/>
    </Page.DataContext>
    
    <d:Page.DataContext>
        <desgn:MainViewModel />
    </d:Page.DataContext>
    
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Margin="100,150,0,0">
            <TextBlock Style="{StaticResource HeaderTextBlockStyle}" Text="{Binding Title}"/>
            <TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{Binding Description}"/>
        </StackPanel>
    </Grid>
</Page>

Now we can see the vaues that we put to test the Application UI and make any changes to it.














Here is runtime result of the app















Enjoy







Full Code 
http://bit.ly/1xiJ3yZ