July, 2011

  • Wriju's BLOG

    Windows Phone 7 - Binding Data to ListBox through Code

    • 9 Comments

    In Windows Phone 7 we need to display data programmatically. Below one demonstrates the simply way of binding data through code.

    Suppose you have Emp class as below.

    public class Emp
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Let’s create List<Emp>

    List<Emp> myData = new List<Emp>()
    {
        new Emp(){Id = 1, Name = "Wriju"},
        new Emp(){Id = 2, Name = "Writam"},
        new Emp(){Id = 3, Name = "Saswati"},
        new Emp(){Id = 4, Name = "Wrishika"},
        new Emp(){Id = 5, Name = "Baba"},
        new Emp(){Id = 6, Name = "Ma"}
    };
    

    After that format the ListBox to display it properly.

    <Grid>
        <ListBox Name="listBoxEmployee">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Id}"></TextBlock>
                        <TextBlock Text=" - "></TextBlock>
                        <TextBlock Text="{Binding Path=Name}"></TextBlock>
                    </StackPanel>
                </DataTemplate>               
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    

    Now, you need to simply code to bind the data

    lstData.ItemsSource = myData;
    

    This is a very simple example but useful in many scenario and applied to most of the data-bound application.

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : Building Simple RSS Reader

    • 5 Comments

    Here we will build simple RSS reader in Windows Phone. Reading RSS is reading XML file online. So you need some engineering between XML and XAML. Here you go.

    Your phone UI

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ListBox Name="lstRSS">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Title}"></TextBlock>
                        <TextBlock Text="{Binding Path=PubDate}"></TextBlock>
                        <TextBlock Text=" "></TextBlock>
                    </StackPanel>                    
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>            
    </Grid>
    

    Then the class to define the structure

    public class RSSClass
    {
        public string Title { get; set; }
        public string PubDate { get; set; }
    }
    

    After that we need few lines to read it online.

    public Page1()
    {
        InitializeComponent();
    
        WebClient myRSS = new WebClient();
        myRSS.DownloadStringCompleted += new DownloadStringCompletedEventHandler(myRSS_DownloadStringCompleted);
    
        //Read Async
        myRSS.DownloadStringAsync(new Uri(@"http://blogs.msdn.com/b/wriju/rss.aspx"));
    }
    
    void myRSS_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        //Check if the Network is available
        if (!Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable)
        {
            var rssData = from rss in XElement.Parse(e.Result).Descendants("item")
                            select new RSSClass
                            {
                                Title = rss.Element("title").Value,
                                PubDate = rss.Element("pubDate").Value
                            };
            lstRSS.ItemsSource = rssData;
        }
        else
        {
            MessageBox.Show("No network is available..");
        }
    }
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : IsolatedStorage Save and Read Data to a File

    • 4 Comments

    Windows Phone 7 apps runs in an isolated environment and often application needs store and retrieve data from files. Application can use its IsolatedStorage to store and retrieve data.

    The example shows how to read from a  file and display it in ListBox and save data to the file located in its isolated storage.

    We need the class to create a structure for UI data binding.

    //Creating the structure to display
    public class MyDataClass
    {
        public string MSG { get; set; }
    }
    

    After that define the UI look,

    <ListBox Background="White" x:Name="lstDisplay" Grid.Row="1" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock FontSize="20" Foreground="Black" Text="{Binding Path=MSG}"></TextBlock>
                    <TextBlock Foreground="Black" Text="---"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>                
    </ListBox>
    

    We now need to initialize the IsolatedStorage for our application.

    IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
    string sFile = "DataTest.txt";
    

    Once done we will start reading lines form the inline text file.

    public void LoadData()
    {
        //myFile.DeleteFile(sFile);
        if (!myFile.FileExists(sFile))
        {
            IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
            dataFile.Close();
        }
    
        //Reading and loading data
        StreamReader reader = new StreamReader(new IsolatedStorageFileStream(sFile, FileMode.Open, myFile));
        string rawData = reader.ReadToEnd();
        reader.Close();
    
        string[] sep = new string[] { "\r\n" }; //Splittng it with new line
        string[] arrData = rawData.Split(sep,StringSplitOptions.RemoveEmptyEntries);
                            
        List<MyDataClass> dataList = new List<MyDataClass>();
        foreach (var d in arrData)
        {
            dataList.Add(new MyDataClass() { MSG = d });
        }
        //Binding data to the UI for display
        lstDisplay.ItemsSource = dataList;
    }
    

    Below is how we can save the data in the file.

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        if (txtMSG.Text.Trim() !="")
        {
            string sMSG = txtMSG.Text;
            StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(sFile, FileMode.Append, myFile));
            sw.WriteLine(sMSG); //Wrting to the file
            sw.Close();
    
            //Refresh the display
            LoadData();
            txtMSG.Text = "";
        }
    }
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : Reading Twitter Timeline

    • 2 Comments

    This one is similar to my previous post on Reading RSS. But useful in Phone App.

    So you need the structure as below

    public class TWClass
    {
        public string TextMSG { get; set; }
        public string CreatedDt { get; set; }
    }
    

    After that you need the below code to get your Twitter timeline. My Twitter handle is wriju_ghosh. I have hardcoded it. You can make it dynamic as well.

    public Page1()
    {
        InitializeComponent();
            
        WebClient myTweet = new WebClient();
        myTweet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(myTweet_DownloadStringCompleted);
    
        myTweet.DownloadStringAsync(new Uri(@"http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=wriju_ghosh"));
    }
    
    void myTweet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        //Need to check Network/WiFi etc before proceeding further..
        var TWData = from tw in XElement.Parse(e.Result).Descendants("status")
                        select new TWClass
                        {
                            TextMSG = tw.Element("text").Value,
                            CreatedDt = tw.Element("created_at").Value
                        };
        lstTW.ItemsSource = TWData;    
    }
    

    Now UI would look like (this can be better).

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ListBox Name="lstTW" Margin="0,0,6,0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Width="400">
                        <TextBlock Text="{Binding Path=TextMSG}"></TextBlock>
                        <TextBlock Text="{Binding Path=CreatedDt}"></TextBlock>
                        <TextBlock Text="----"></TextBlock>
                    </StackPanel>                    
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>            
    </Grid>
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : Handling Hardware Back Button

    • 1 Comments

    Often user presses hardware back button while inside an application. This would send the existing application to the background and let other be on top. Most of the times this is acceptable but sometimes application requires user to choose whether to go back or notify about it. Handling back button through code,

    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        e.Cancel = true; //Cancelling the default back option
        MessageBox.Show("You have pressed hardware back button");            
    }
    

    Namosakr!!!

  • Wriju's BLOG

    Windows Phone 7 : Checking Network Connections before Downloading

    • 0 Comments

    Not every user will use unlimited data connections. So as a good application developer you should check and notify user whether they would like to proceed further or not.

    Some of the quick things you may want to do

    //Check if network is available
    var _isNetworkAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable;
    
    //Check if Cell Data connection is available
    var _isCellDataAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsCellularDataEnabled;
    
    //Check if the cell data connection is in ROaming
    var _isCellDataRoaming = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsCellularDataRoamingEnabled;
    
    //Check if WiFi Network is available
    var _isWiFiEnabled = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsWiFiEnabled;
    
    

    You can also check who is the mobile provider, a quick one to let user know if they are in Roaming and not using their parent connection

    Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.CellularMobileOperator;
    

    Namoskar!!!

  • Wriju's BLOG

    Channel 9 Video on Entity Framework 4.1

    • 0 Comments

    Published the video on ADO.NET Entity Framework 4.1 Code First Development video. This covers quickly the basic features if this amazing product.

    image

    Check it out at http://channel9.msdn.com/posts/EF41CodeFirst

    The code used for the demo is

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;
    
    namespace EF41CodeFirst_BDotnet
    {
        //Dept Class
        public class Dept
        {
            public Dept()
            {
                EmpDepts = new List<EmpDept>();
            }
            [Key] //Primary Key column
            public int MyId { get; set; }
            public string DeptName { get; set; }
            public string Location { get; set; }
    
            //For 1 to Many with EmpDept
            public virtual ICollection<EmpDept> EmpDepts { get; set; }
        }
    
        public class EmpDept
        {
            public int EmpDeptId { get; set; }
            public string EmpName { get; set; }
    
            //For foreign key
            public virtual Dept Dept { get; set; }
        }
    
        //Context to initialize connection using DbContext as base class
        public class HRContext : DbContext
        {
            public DbSet<Dept> Depts { get; set; }
            public DbSet<EmpDept> EmpDepts { get; set; }
        }
        
        class Program
        {
            static void Main(string[] args)
            {
                //Drop the database if model changes
                Database.SetInitializer<HRContext>(new DropCreateDatabaseIfModelChanges<HRContext>());
    
                //Adding values to the database
                using (var ctx = new HRContext())
                {
                    var d1 = new Dept() { DeptName = "Programming" };
                    var d2 = new Dept() { DeptName = "IT" };
    
                    new List<EmpDept>
                    {
                        new EmpDept(){EmpName = "Wriju", Dept = d1},
                        new EmpDept(){EmpName = "Saswati", Dept = d1},
                        new EmpDept(){EmpName = "Writam", Dept = d2},
                        new EmpDept(){EmpName = "Wrishika", Dept = d2},
                        new EmpDept(){EmpName = "Sreemoyee", Dept = d1},
                        new EmpDept(){EmpName = "Bingo", Dept = d1}
                    }.ForEach(e => ctx.EmpDepts.Add(e));
    
                    ctx.SaveChanges();
    
                    //Selecting data using Lazy Loading
                    var q = from d in ctx.Depts
                            select d;
    
                    foreach (var dep in q)
                    {
                        Console.WriteLine(dep.DeptName);
                        Console.WriteLine("+++++++++++++++++++++++++");
                        foreach (var e1 in dep.EmpDepts)
                        {
                            Console.WriteLine(e1.EmpName);
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
    }
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure Accelerator for Web Roles Released

    • 0 Comments

    WAAWebRoles.Logo

    Windows Azure Accelerator for Web Role released recently. Please check http://waawebroles.codeplex.com/. This would allow you to deploy multiple websites to a web role.

    There is a Channel 9 video available Getting Started with the Windows Azure Accelerator for Web Roles

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : Check the power status

    • 0 Comments

    You might need to check if your phone is connected to power or running in battery.

    //Check Power Status
    var power = Microsoft.Phone.Info.DeviceStatus.PowerSource;
    textBlock1.Text = power.ToString();
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : How to get the device name

    • 0 Comments

    Below is how you can retrieve the phone name.

    //Phone Name
    var PhoneName = Microsoft.Phone.Info.DeviceStatus.DeviceName;
    textBlock1.Text += Environment.NewLine + PhoneName.ToString();
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : How to get the manufacturer name

    • 0 Comments

    Below is how you can get the device manufacturer name.

    //Device Manufacturer
    var manufacturer = Microsoft.Phone.Info.DeviceStatus.DeviceManufacturer;
    textBlock1.Text += Environment.NewLine + manufacturer.ToString();
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : How to get Phone and Application memory information

    • 0 Comments

    If you want to get the memory information of your phone and application

    //Total Phone Memory (in bytes)
    var totalMemory = Microsoft.Phone.Info.DeviceStatus.DeviceTotalMemory;
    textBlock1.Text += Environment.NewLine + (totalMemory/(1024 * 1024)).ToString();
    
    //Application Current Memory Usage (bytes)
    var appCurrentMemoryUsage = Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage;
    textBlock1.Text += Environment.NewLine + appCurrentMemoryUsage.ToString();
    
     

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : How to Vibrate Phone

    • 0 Comments

    Below is how you can vibrate the phone programmatically. Duration should be positive or less than 5.

    image

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : How to play media

    • 0 Comments

    Windows Phone 7 can flawlessly play media files. There are list of supported codec which Windows Phone 7 can play. However below is the simple XAML which can enable the media loading.

    <MediaElement x:Name="myVideo" AutoPlay="True" Source="Kalimba.mp3" />

    You can also control various behaviors through your code. 

    Note.

    1. Now while using the Windows Phone 7 Emulator you will not be able to play video file. But the audio file is easy to play as mentioned above.

    2. Also you need to ensure if you are using local media file the Build Type of that media should be Content

    Namoskar!!!

Page 1 of 1 (14 items)