Wednesday, 20 August 2014

Kiddy example in C#

class Program
    {
        static void Main(string[] args)
        {
            //we provide the value manually
            string s = Console.ReadLine();
            int x = Convert.ToInt16(s);
            for (int i = 1; i <= x; i++)
            {
                for (int j = 1; j <= x - i; j++)
                    Console.Write(" ");

                for (int j = 1; j <= i; j++)
                    Console.Write("*");

                for (int k = 1; k < i; k++)
                    Console.Write("*");

                Console.WriteLine(" ");
            }
           // Console.ReadLine();

            string Name = Console.ReadLine();
            char[] characters = Name.ToCharArray();
            string reverse = string.Empty;
            foreach (char ch in Name)
            {

                reverse = ch + reverse;

            }
            Console.WriteLine(reverse);
            StringBuilder sb = new StringBuilder();
            for (int i = Name.Length - 1; i >= 0; --i)
            {
                sb.Append(characters[i]);
            }
            Console.Write(sb.ToString());
            Console.Read();
        }
    }







Rest in WCF service

Rest Service in WCF Service here

Thursday, 7 August 2014

Http JSON web request

Http Web request example here


Here need to send the Json by HttpWebrequest just for reference  :
public static class EventSender
{
    static JToken current_item;

    public static void Run(JToken json)
    {

        SendEvent(json);
    }
    static void SendEvent(JToken item)
    {
        var orgId = item.Children<JProperty>().FirstOrDefault(x => x.Name == "orgId").Value;
        var sessionId = item.Children<JProperty>().FirstOrDefault(x => x.Name == "sessionId").Value;
        var drcId = item.Children<JProperty>().FirstOrDefault(x => x.Name == "drcId").Value;
        var wkt = item.Children<JProperty>().FirstOrDefault(x => x.Name == "wkt").Value;
        string baseURL = "URL HERE?";
        StringBuilder urlBuilder = new StringBuilder().Append(baseURL);
        urlBuilder.Append("orgId=" + orgId);
        urlBuilder.Append("&sessionId=" + sessionId);
        urlBuilder.Append("&drcId=" + drcId);
        urlBuilder.Append("&wkt=" + wkt);

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
        req.Method = "POST";
        req.ContentType = "application/json;charset=utf-8"; 
        req.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), req);
    }
    static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        var json = current_item.Children<JProperty>().FirstOrDefault(x => x.Name == "json").Value;
        try
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            //string postData = JsonConvert.SerializeObject(json).ToString();
            //byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            //byte[] byteArray = Encoding.UTF8.GetBytes(json.ToString());
            //postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
            //Start the web request
            request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);
        }
        catch (Exception err)
        {
            Debug.WriteLine(err.Message);
        }
    }
    static void GetResponceStreamCallback(IAsyncResult callbackResult)
    {

        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            string result = httpWebStreamReader.ReadToEnd();

        }

    }
}


here download another example 
another source sample here

Tuesday, 22 July 2014

Making Stylish ListPicker in Wp8

Making Stylish ListPicker

Here I am Explaining With List of Object assign to ListPicker.

Here Xaml Code :-

add the namespace to the Xaml Page like below :-

 xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"


this is List Picker :-

<toolkit:ListPicker x:Name="lpkCategory" Margin="120,-20,10,-24"
  ItemsSource="{Binding Category}"                              Grid.Row="5"      Canvas.ZIndex="220" Width="200" SelectionChanged="lpkCategory_SelectionChanged" Foreground="Teal"  ExpansionMode="FullScreenOnly" >
                    <toolkit:ListPicker.ItemTemplate>
                        <DataTemplate>
                            <Border Width="200" Background="BlueViolet" Margin="10,10,10,10" >
                                <TextBlock Text="{Binding categoryName}" Margin="10,10,10,10"/>
                            </Border>
                        </DataTemplate>
                    </toolkit:ListPicker.ItemTemplate>
                    <toolkit:ListPicker.FullModeItemTemplate>
                        <DataTemplate>
                            <Border Width="200" Background="BlueViolet" Margin="10,10,10,10" >
                                <TextBlock Text="{Binding categoryName}" Margin="10,10,10,10"/>
                            </Border>
                        </DataTemplate>
                    </toolkit:ListPicker.FullModeItemTemplate>
                </toolkit:ListPicker>


Expecting Problems :-

ZIndex :- Some times Listpicker items not appear when it expands so  make sure ur ZIndex Sets High .

like Below Canvas.ZIndex ="220"

Display Item Name : While Displaying Item name in Listpicker It shows Listpicker Property  .
for this we need to check the  ListPicker.ItemTemplate and ListPicker.FullModeItemTemplate

class :-

 public  class Category
    {
         
       
        public int categoryId { get; set; }
     
        public string categoryName { get; set; }
       
    }

 Category = objdbhelper.GetCategory();
  // Make sure here Category  is same mentioned in Xaml like  ItemsSource="{Binding Category}"

lpkCategory.ItemsSource = Category;
lpkCategory.SelectedIndex = 0;


//Display different Design Styles Item i have used Border tags in DataTemplate like below in above Xaml  page .

<DataTemplate>
       <Border Width="200" Background="BlueViolet" Margin="10,10,10,10" >
       <TextBlock Text="{Binding categoryName}" Margin="10,10,10,10"/>
       </Border>
 </DataTemplate>

Output like below :-


Monday, 21 July 2014

Read the XML Embedded Resource file in C#


Just add one XML file to your solution .






in above solution i  have added master.xml file and i set the properties BuildAction : Embedded Resource   and Copy to OutPut : Copy if Newer .

add these two name Spaces     using System.Xml.Linq;  
                                             using System.Xml;


define one class :-

class schemas
    {
     
     
        public int schemaId { get; set; }
     
        public string schemaName { get; set; }
    }

 class Category
    {
         
       
        public int categoryId { get; set; }
     
        public string categoryName { get; set; }
       
    }

class userInfo
    {
       
        public int userId { get; set; }
       
        public string firstName { get; set; }
       
        public string lastName { get; set; }
    }

 using System.Xml.Linq;  
 using System.Xml;
namespace PatrolInfromationSystem
{
 public class DBHelper
    {

         List<Model.Category> catlst = null;
        List<Model.userInfo> usrlst = null;
        List<Model.schemas> schemelst = null;

DBHelper()
{
 XDocument doc;

                var asm = Assembly.GetExecutingAssembly();

                using (var stream =Assembly.GetExecutingAssembly().GetManifestResourceStream("PatrolInfromationSystem.master.xml"))
                  // Mandatory to specified with Namespace .
                {
                    doc = LoadFromStream(stream);
                }

                catlst = null;
                usrlst = null;
                schemelst = null;
                catlst = doc.Descendants("category").Select(d => new Model.Category { categoryId = Convert.ToInt16(d.Element("categoryId").Value), categoryName = d.Element("categoryName").Value }).ToList();
                usrlst = doc.Descendants("userInfo").Select(d => new Model.userInfo { userId = Convert.ToInt16(d.Element("userId").Value), firstName = d.Element("firstName").Value, lastName = d.Element("lastName").Value }).ToList();
                schemelst = doc.Descendants("schemas").Select(d => new Model.schemas { schemaId = Convert.ToInt16(d.Element("schemaId").Value), schemaName = d.Element("schemaName").Value }).ToList();
}

 static XDocument LoadFromStream(Stream stream)
        {
            using (XmlReader reader = XmlReader.Create(stream))
            {
                return XDocument.Load(reader);
            }
        }

}
}

Monday, 14 July 2014

Windows Phone 8 Push notification


This is a Sample push notification .

Here I am trying to give an  Idea What activities going behind in Push Notification .

1)Windows phone :-
Here we need to writing the code for to generate  Uri .
This Uri generate by MPNS with the help Push Client (it is part of  Windows Phone OS activity)

What and Why Uri ?

 What/ Why ans is for unique Communication  establish Device(windows phone) to Server( Cloud Service provider)

This  Uri Unique one for Every application in windows phone . it was generating the  combination of application name and OS .

==================================================================
 private const string ChannelName = "TestNotification";

private void SetupNotificationChannel()
        {
            _channel = HttpNotificationChannel.Find(ChannelName);

            if (_channel == null)
            {
                _channel = new HttpNotificationChannel(ChannelName);
                _channel.ChannelUriUpdated += ChannelUriUpdated;
                _channel.ErrorOccurred += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => ErrorOccurred(e));
                _channel.Open();
            }
            else
            {
                RegisterForNotifications();
            }
        }
========================================================================

the above method checking the channelname if it is not existed the  channelname  we need create channel for this application  and Updates Uri with the help of MPNS .

Step 1:- Creating a web/WCF  Service  to Send the message to Register clients.

Now i am going to create a WCF service :-

interface  IService1 is like below:-

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace TestWCFNotification
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        void Subscribe(Guid uniqID, string uri);

        [OperationContract]
        void SendToastNotification(string title,string message);

        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
 
}

and Implementation is :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Net;
namespace TestWCFNotification
{
    //Notification Types
    public enum NotificationType
    {
        Tile = 1,
        Toast = 2,
        Raw = 3
    }

    //Time interval required to send messages.
    public enum BatchingInterval
    {
        TileImmediately = 1,
        ToastImmediately = 2,
        RawImmediately = 3,
        //TileWait450 = 11,
        //ToastWait450 = 12,
        //RawWait450 = 13,
        //TileWait900 = 21,
        //ToastWait900 = 22,
        //RawWait900 = 23
    }
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        private static Dictionary<Guid, Uri> _clientUris = new Dictionary<Guid, Uri>();
        public void Subscribe(Guid uniqID, string uri)
        {
            if (_clientUris.ContainsKey(uniqID))
            {
                _clientUris[uniqID] = new Uri(uri);
            }
            else
            {
                _clientUris.Add(uniqID, new Uri(uri));
            }
        }

        public void SendToastNotification(string title ,string message)
        {
            var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                 "<wp:Notification xmlns:wp=\"WPNotification\">" +
                    "<wp:Toast>" +
                       "<wp:Text1>" + title + "</wp:Text1>" +
                       "<wp:Text2>" + message + "</wp:Text2>" +
                      "</wp:Toast>" +
                 "</wp:Notification>";
            toastMessage = string.Format(toastMessage, message);

            var messageBytes = System.Text.Encoding.UTF8.GetBytes(toastMessage);

            foreach (var uri in _clientUris.Values)
            {
                SendMessage(uri, messageBytes, NotificationType.Toast);
            }
        }
        public void SendRawNotification(string message)
        {
            var messageBytes = Encoding.UTF8.GetBytes(message);

            foreach (var uri in _clientUris.Values)
            {
                SendMessage(uri, messageBytes, NotificationType.Raw);
            }
        }

        private void SendMessage(Uri uri, byte[] messageBytes, NotificationType notificationType)
        {
            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "text/xml";
            request.ContentLength = messageBytes.Length;

            request.Headers.Add("X-MessageID", Guid.NewGuid().ToString());

            if (notificationType == NotificationType.Toast)
            {
                request.Headers["X-WindowsPhone-Target"] = "toast";
                request.Headers.Add("X-NotificationClass", ((int)BatchingInterval.ToastImmediately).ToString());
            }
            else
            {

                request.Headers.Add("X-NotificationClass", ((int)BatchingInterval.RawImmediately).ToString());
            }

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(messageBytes, 0, messageBytes.Length);
            }

        }
    }
}

Webconfig file ( You may get some time out exception so make sure ur web config file has this type of configuration :-

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicBinding" closeTimeout="10:01:00" openTimeout="10:01:00" receiveTimeout="10:20:00" sendTimeout="10:01:00"
                 maxBufferSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647"
                       maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"  />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />

          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="TestWCFNotification.Service1"
          name="TestWCFNotification.Service1">
        <endpoint address=""
          binding="basicHttpBinding" bindingConfiguration="BasicBinding"
          contract="TestWCFNotification.IService1">
         </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://19x.16x.x.xx//TestNotification/Service1.svc" />
          </baseAddresses>
        </host>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
      </services>
      <behaviors>
      <serviceBehaviors>
        <!--<behavior>-->
           <!--To avoid disclosing metadata information, set the values below to false before deployment--> 
          
          <behavior name="TestWCFNotification.Service1">
            <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
            <serviceThrottling maxConcurrentCalls="20" maxConcurrentSessions="20"
         maxConcurrentInstances="2147483647" />

          <!--</behavior>-->
        </behavior>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <!--To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information-->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!--<protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>-->    
    <!--<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />-->
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>


the above Web Config file i have changed baseAddresses URL .

Note :- Change Localhost to ur IP address  for this u need to host in  the IIS .Otherwise Windows Phone it won't accept ur service .



Step 2:-

Here i am Writing code for simple and sample  Windows Phone application.


What ever getting result is added to this listbox .if application is not open just show the notification alert to end user .

MainPage.Xaml :-

========================================================================

<phone:PhoneApplicationPage
    x:Class="TestNotificationWP8.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="Push Notification" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0" FontSize="30"/>
         
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="200"/>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>
            <ListBox  Grid.Row="1" x:Name="lstOffers" BorderBrush="Azure" BorderThickness="5" Margin="10,10,10,10" Height="200">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" FontFamily="Segoe WP Light"  FontSize="20"/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>

       
    </Grid>

</phone:PhoneApplicationPage>
========================================================================
Here MainPage.xaml.cs :-

using System;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Notification;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Diagnostics;
using System.IO;

namespace TestNotificationWP8
{
    public partial class MainPage : PhoneApplicationPage
    {
        private HttpNotificationChannel _channel;
        private const string ChannelName = "TestNotification";
        private Guid _deviceId;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            if (DesignerProperties.IsInDesignTool)
                return;

            if (IsolatedStorageSettings.ApplicationSettings.Contains("DeviceId"))
            {
                _deviceId = (Guid)IsolatedStorageSettings.ApplicationSettings["DeviceId"];
            }
            else
            {
                _deviceId = Guid.NewGuid();
                IsolatedStorageSettings.ApplicationSettings["DeviceId"] = _deviceId;
            }

            SetupNotificationChannel();
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }
        private void SetupNotificationChannel()
        {
            _channel = HttpNotificationChannel.Find(ChannelName);

            if (_channel == null)
            {
                _channel = new HttpNotificationChannel(ChannelName);
                _channel.ChannelUriUpdated += ChannelUriUpdated;
                _channel.ErrorOccurred += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => ErrorOccurred(e));
                _channel.Open();
            }
            else
            {
                RegisterForNotifications();
            }
        }
        private void RegisterForNotifications()
        {
            RegisterWithNotificationService();
            _channel.ShellToastNotificationReceived += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => ToastReceived(e));
            _channel.HttpNotificationReceived += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => HttpNotificationReceived(e));
            _channel.ErrorOccurred += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => ErrorOccurred(e));
        }
        private void RegisterWithNotificationService()
        {

            var svc = new ServiceReference1.Service1Client();

            svc.SubscribeCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    Debug.WriteLine("Error registering with notification service");
                }
            };

            svc.SubscribeAsync(_deviceId, _channel.ChannelUri.ToString());
        }

          private void HttpNotificationReceived(HttpNotificationEventArgs e)
       {
           var reader = new StreamReader(e.Notification.Body);
           var message = reader.ReadToEnd();
           lstOffers.Items.Add("Raw notification : " + message);
           reader.Close();
       }
          private void ToastReceived(NotificationEventArgs e)
          {
             // lstOffers.Items.Add("Toast Recevied : " + e.Collection["wp:Text1"]);
             lstOffers.Items.Add( "Toast Recevied : "+ String.Format("Title:" + e.Collection["wp:Text1"] + "\nMessage:" + e.Collection["wp:Text2"]));
          }

          private void ErrorOccurred(NotificationChannelErrorEventArgs e)
          {

              lstOffers.Items.Add(e.Message);
              Debug.WriteLine("ERROR:" + e.Message);
          }

          private void ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
          {
              _channel = HttpNotificationChannel.Find(ChannelName);

              if (!_channel.IsShellToastBound)
              {
                  _channel.BindToShellToast();
              }

              RegisterForNotifications();
          }
     

       
    }
}


===========================================================

and Ur WCF  Service Reference to Windows phone 8 , i have given name with ServiceReference1

and i have created client line below

   var svc = new ServiceReference1.Service1Client();



Step 3 Server application It needs to send the message to register Clients :-




Above window.xaml page :-
==================================================================
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" closeTimeout="10:10:00"
                    openTimeout="10:10:00" receiveTimeout="10:10:00" sendTimeout="10:10:00"
                    maxReceivedMessageSize="2147483647" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://19x.16x.x.xx/TestNotification/Service1.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
                contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>
========================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfPushNotification
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            ServiceReference1.Service1Client SvcClient = new ServiceReference1.Service1Client();

            if (txtMessage.Text != string.Empty)
            {
                SvcClient.SendToastNotification("Tester", txtMessage.Text);
            }
            else
            {
                MessageBox.Show("Pls Provide Message to Send");
            }
            //{
            //    MessageBox.Show("Sent successful");
            //}
            //else
            //{
            //    MessageBox.Show(" not Sent");
            //}
        }
    }
}

======================================================================

For this we need to add service Reference  and i given named as ServiceReference1 .


Step 4 :-

Need to host WCf in IIS .

Step 5 :- Need to check Service Reference in Windows or WPF  and Windows phone application .

Step 6:- Need to Run the Windows application then come to home page

step 7 :- Run the Windows/WpF application provide some message in Text box like below:-





Step 8 u r message will be display like below in windows phone :-






Here We get broadcasting message to Windows phone.

Thursday, 10 July 2014

Create a Globalization application in Windows phone 8.

Globalization application

Vipul given good example  Here

Now we need to modified little bit code because of next time onwards application  will be open last time selected language.

Just we need to store selected language in  Isolated storage file like below :-
Make sure your Page has these name spaces
using System.Globalization;
using System.Threading;
using System.IO.IsolatedStorage;

private IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
        // Constructor
        public MainPage()
        {
            if (appSettings != null && appSettings.Count >0)
            { 
                ApplyCulture(new CultureInfo((string)appSettings["lan"])); 
            }
            
            InitializeComponent();


           
        }
// this above condition is  next time onwards just check the isolated storage memory  if it has any language then it will open last time selected language.


private void radioButtonenUS_Checked(object sender, RoutedEventArgs e)
        {
            ApplyCulture(new CultureInfo("en-US"));
            appSettings["lan"] = "en-US";
        }
here we save the Selected language in Isolated storage memory .
 
private void radiobuttonfrFR_Checked(object sender, RoutedEventArgs e)
        {
            ApplyCulture(new CultureInfo("fr-FR"));
          appSettings["lan"] = "fr-FR";
            
        }

 private void ApplyCulture(CultureInfo cul)
        {
            Thread.CurrentThread.CurrentCulture = cul;
            Thread.CurrentThread.CurrentUICulture = cul;
            DateTime current = DateTime.Now;
            textBoxLongDate.Text = current.ToString("D");
            textBoxShortDate.Text = current.ToString("d");
            textBoxTime.Text = current.ToString("T");
            textBoxCurrency.Text = 100.ToString("C");
            textBlockLongDate.Text = AppResources.TextLabelLongDate;
            textBlockShortDate.Text = AppResources.TextLabelShortDate;
            textBlockTime.Text = AppResources.TextLabelTime;
            textBlockCurrency.Text = AppResources.TextLabelCurrency;
            textBlockUser.Text = AppResources.UserName;
            textBlockHello.Text = AppResources.Salutation;
        }

 //if we don't write the above method your current page doesn't convert to selected language this is for immediate effect for current page.
 

Dormant and Tombstone in Windows phone Life Cycle ?

Dormant --> Tombstoned


Let’s understand the cycle thoroughly.
1. The phone starts with a clean slate. No app is in memory or in dormant state. The user taps a tile and starts Application A .The Application A while going from the Not running state to the Launched state invokes the “launching “event.
2. Now the App is running .Let’s say a call comes .The dialer will come into focus and our app will be shifted to the background. This is called the dormant state. The app is in memory but it’s not working. Suppose, if we have a note taking app, and the user was taking notes and the call comes. After the call, when the user gets back to the app, the unsaved notes will be visible without any special action by the developer.
3. Whenever the app gets deactivated the deactivating event is invoked.
4So when does it get tombstone? Well Windows Phone currently can have maximum of 6 apps in dormant state. So the moment a seventh app goes to dormant, our app A which was the first to go into dormant state goes into Tombstone state.
5Tombstones state basically means that your app is no longer taking any system resources .All unsaved data is lost. For example suppose our user was typing a note in the textbox and presses the home key and then goes onto open 6 other applications. First the app will be shifted to dormant and then finally to tombstone.
6. So we don’t need any special code for keeping state during dormancy. But the important part is that we would never know when the app goes from the dormant to the tombstone state. Hence, whenever our app goes to the dormant state, we should think of it as tomb stoning and put data into isolated storage for keeping state.
7. So when the user navigates back to the app by pressing the back key multiple times or long pressing the back key (task manager) .Our app will come to running state from either tombstone state or deactivated state. Both these cases will result in same function to be invoked “Activating”
8. So how do we know whether our app has been brought to life from tombstone or dormancy?  That can be done by testing e.IsApplicationInstancePreserved . If it’s coming to life from dormancy, then we do not need to do anything special.
9. There is a third case, the case when our app is dormant, but the user launches your app by tapping on tile. Technically tapping on the tile creates a new instance of your app and that is what is done. The unfortunate case is your existing instance of the app which was in dormant state is silently destroyed. Which means the user loses the unsaved data. The “launching” event is invoked
10. The solution is code redundancy! Well sort of, since in both activating and launching event needs to have some sort of parallel code ,as both would involve getting saved data from local storage .
The recommended practice is to save state data as the data changes. For example, the results of a web request can be saved to disk or the application state dictionary (or both) at the moment it arrives from the network. You should not wait until the Deactivated event occurs to store this data. All application lifecycle events enforce a limit of 10 seconds for an application to complete any tasks

Checking is it from Dormant or Tombstone

private void Application_Activated(object sender, ActivatedEventArgs e)
{
     // Determine whether it is returning from being dormant or tombstoned.
     // If it is false, return from tombstoned.
     if (e.IsApplicationInstancePreserved == false)
         //TODO
     else
         //TODO
 }
Resource from

http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff817008(v=vs.105).aspx


http://iamabhik.wordpress.com/2012/12/01/windows-phone-8-application-lifecycle/