• Wriju's BLOG

    Windows Phone 7 : Open URL in IE9 from Application

    • 0 Comments

    Launching browser from your Phone application is often required. The common term could be “Shell” for those who came to classic VB age like me. Later in .NET it was wrapped under System.Diagnostic.Process. In Windows Phone 7 we might need such functionality while working with RSS kind of application where user can click on the link and open it in browser.

    WebBrowserTask wbTask = new WebBrowserTask();
    //URL = http://create.msdn.com
    wbTask.Uri = new Uri(textBox1.Text, UriKind.RelativeOrAbsolute);
    wbTask.Show();
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : Using Local Database for Application

    • 4 Comments

    Windows Phone uses concept of Local Database and by implementing LINQ to SQL you can create 100% relational database driven application.

    Windows Phone DataContext and Local Database

    To understand more on this refer http://msdn.microsoft.com/en-us/library/hh202860(VS.92).aspx

    So what you need is the good old tie up between Silverlight and LINQ to SQL. Here we go.

    You need to refer System.Data.Linq assembly and use the below two namespaces to define the model.

    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    

    After that you need to define the model by hand.

    //Model Class
    [Table]
    public class EmailClass
    {
        [Column(IsDbGenerated = true, IsPrimaryKey = true)]
        public int Id { get; set; }
        [Column()]
        public string EmailAddress { get; set; }
    }
    

    Once the model is defined you then need the DataContext

    public class EmailContext : DataContext
    {
        public EmailContext(string sConnectionString)
            : base(sConnectionString)
        { }
    
        public Table<EmailClass> Emails
        {
            get
            {
                return this.GetTable<EmailClass>();
            }
        }
    }
    

    Connection string would look like,

    string ConnectionString = "Data Source=isostore:/EmailDB.sdf";
    

    Some reusable methods to Add and Display

    public IList<EmailClass> GetEmails()
    {
        List<EmailClass> emails = new List<EmailClass>();
        using (var db = new EmailContext(ConnectionString))
        {
            var query = from e in db.Emails
                        select e;
            emails = query.ToList();
        }
    
        return emails;
    }
    
    public void AddEmail(EmailClass _email)
    {
        using (var db = new EmailContext(ConnectionString))
        {
            db.Emails.InsertOnSubmit(_email);
            db.SubmitChanges();
        }
    }
    

    Then comes UI which would help you to save and display data,

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <TextBox Width="300" x:Name="txtEmail"></TextBox>
            <Button HorizontalAlignment="Right" x:Name="btnSave" Content="Save" Width="120" Click="btnSave_Click"></Button>
        </StackPanel>
        <ListBox x:Name="lstEmails" Grid.Row="1" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=EmailAddress}"></TextBlock>
                        <TextBlock Text="-----"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>            
    </Grid>
    

    The complete code is as below,

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Microsoft.Phone.Controls;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    
    namespace WP7_Samples
    {    
        public partial class LocalDB_WP7 : PhoneApplicationPage
        {
            const string ConnectionString = "Data Source=isostore:/EmailDB.sdf";
            public LocalDB_WP7()
            {
                InitializeComponent();
    
                InputScope _scope = new InputScope();
                InputScopeName _scopeName = new InputScopeName();
                _scopeName.NameValue = InputScopeNameValue.EmailNameOrAddress;
                _scope.Names.Add(_scopeName);
    
                txtEmail.InputScope = _scope;
    
                using (var db = new EmailContext(ConnectionString))
                {
                    if (!db.DatabaseExists())
                        db.CreateDatabase();
    
                    LoadData();
                }
            }
    
            public void LoadData()
            {
                lstEmails.ItemsSource = GetEmails();
            }
    
            public IList<EmailClass> GetEmails()
            {
                List<EmailClass> emails = new List<EmailClass>();
                using (var db = new EmailContext(ConnectionString))
                {
                    var query = from e in db.Emails
                                select e;
                    emails = query.ToList();
                }
    
                return emails;
            }
    
            public void AddEmail(EmailClass _email)
            {
                using (var db = new EmailContext(ConnectionString))
                {
                    db.Emails.InsertOnSubmit(_email);
                    db.SubmitChanges();
                }
            }
    
            private void btnSave_Click(object sender, RoutedEventArgs e)
            {
                if (txtEmail.Text.Trim() != "")
                {
                    var emailObj = new EmailClass() { EmailAddress = txtEmail.Text.Trim() };
                    AddEmail(emailObj);
                }
                LoadData();
                txtEmail.Text = "";
            }
        }
    
        //Model Class
        [Table]
        public class EmailClass
        {
            [Column(IsDbGenerated = true, IsPrimaryKey = true)]
            public int Id { get; set; }
            [Column()]
            public string EmailAddress { get; set; }
        }
    
        public class EmailContext : DataContext
        {
            public EmailContext(string sConnectionString)
                : base(sConnectionString)
            { }
    
            public Table<EmailClass> Emails
            {
                get
                {
                    return this.GetTable<EmailClass>();
                }
            }
        }
    }
    

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : How to change Startup Page

    • 1 Comments

    Windows Phone 7 Silverlight project generally starts by opening MainPage.xaml. How to change this?

    Under solution explorer, expand Properties and open WMAppManifest.xml and there we can change it

    <Tasks>
      <DefaultTask Name="_default" NavigationPage="LocalDB_WP7.xaml" />
    </Tasks>
    

    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 : 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!!!

  • 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 : 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

    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 : 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 - Binding Data to ListBox through Code

    • 10 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 : 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 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 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 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 : 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 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

    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

    Cost of My Windows Azure Application : Pricing Calculator

    • 0 Comments

    Often question comes to our mind “how to determine the cost of Azure application”. Now the pricing calculator is more interactive and easy to use. Sliders would help you determine the required numbers,

    image

    http://www.microsoft.com/windowsazure/pricing-calculator/

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Table per Hierarchy

    • 0 Comments

    Concept of Table Per Hierarchy (TPH) is to implement polymorphism and to de-normalize the relational database via inheritance. The entire hierarchy is mapped to a single database table holding all the properties of all the classes. The database then would create a column called “[Discriminator]” to hold the specific type. In Code First this is default behavior and we do not have to do anything extra.

    TPH is the simplest and possibly the fastest approach. Code First just amazingly supports it.

    If we consider the below diagram of Animal, Mammal and Reptile. Here Animal is the abstract base class holding common properties.

    image

     This finally would get converted into a table as below (notice the additional [Discrminator] column which is NOT NULL)

    image

    To have this we need the below code

    public abstract class Animal
    {
        public int AnimalId { get; set; }
        public string Name { get; set; }
    }
    
    public class Reptile : Animal
    {
        public double Length { get; set; }
    }
    
    public class Mammal : Animal
    {
        public double Weight { get; set; }
        public bool IsMarried { get; set; }
    }
    
    public class AnimalContext : DbContext
    {
        public DbSet<Animal> Animals { get; set; }
    }
    

    To add data

    To add data to Reptile

    using (var ctx = new AnimalContext())
    {
        var Rep = new Reptile() { Name = "Snake", Length = 10.0 };
        ctx.Animals.Add(Rep);
        ctx.SaveChanges();

    To add data to Mammal

    using (var ctx = new AnimalContext())
    {
        var Mam = new Mammal() { IsMarried = true, Name = "Adam", Weight = 100.0 };
        ctx.Animals.Add(Mam);
        ctx.SaveChanges();
    

    After adding data would be saved as below

    image

    Querying data

    We can query data in various ways,

    var q = from a in ctx.Animals.OfType<Mammal>()
            select a;
    foreach (var k in q)
    {
        Console.WriteLine(k.Name);
    }
    

    We can also use Entity SQL with “OFTYPE”.

    Now the the column [Discriminator] can be altered through FluentAPI

    image

    This would create a column in the database as “AnimalType” and for each entry of Mammal add “M” and Reptile add “R”.

    image

    TPH anyways violets the third normal form and has serious data integrity issue and for a long term perspective this is not manageable. But still the simplest approach.

    Namoskar!!!

  • Wriju's BLOG

    Using ADO.NET EF 4.1 Code First with existing Database

    • 0 Comments

    Most of the time questions comes to our mind about EF 4.1 Code First whether or not can we use it with already available database? Simple answer is YES.

    I have very few personal view on it. I have seen in most of my application development scenario, database gets designed and created before and then evolves as application and requirements. So I expect to use Code First with already created database.

    This is how we can,

    image

    Step 1: We will go for the database-first approach and create our EDMX.

    image

    Step 2: Right click on the edmx and then choose “Add Code Generation Item…

    image

    Step 3: Select “ADO.NET DbContext Generator”. Then delete the .edmx file from your project.

    After that you need few small but important changes,

    Change 1 : Add the connection string (if using SQL Server)

    image

    Change 2 : The tables you are using in your code (check all the DbSet<T> in your context) and add their corresponding onModelCreating code

    image

    Then your code should run without any trouble,

    image

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Querying Many to Many Relationship

    • 0 Comments

    In continuation to my previous post on how to create one to many, let’s see how can we query it.

    We will use the same code base and query it

    Option 1

    When we want to query it normally like below

    var emps = ctx.Emps
                .Where(e => e.EmpId == 1)
                .SelectMany(e => e.Projects, 
                        (em, proj) => new 
                        {
                            em.EmpName, 
                            proj.ProjectName
                        });
    

    The generated object graph would look like

    image

    Option 2

    Whereas if we want to write our query as below

    var em = from e in ctx.Emps.Include(p => p.Projects)
                where e.EmpId == 1
                select e;
                

    This case object graph is more complicated

    image

    Generated SQL

    Interestingly both the cases the generated SQL is same

    SELECT 
    [Project1].[EmpId] AS [EmpId], 
    [Project1].[EmpName] AS [EmpName], 
    [Project1].[C1] AS [C1], 
    [Project1].[ProjectId] AS [ProjectId], 
    [Project1].[ProjectName] AS [ProjectName]
    FROM ( SELECT 
    	[Extent1].[EmpId] AS [EmpId], 
    	[Extent1].[EmpName] AS [EmpName], 
    	[Join1].[ProjectId] AS [ProjectId], 
    	[Join1].[ProjectName] AS [ProjectName], 
    	CASE WHEN ([Join1].[Project_ProjectId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    	FROM  [dbo].[Emps] AS [Extent1]
    	LEFT OUTER JOIN  (SELECT [Extent2].[Project_ProjectId] AS [Project_ProjectId], [Extent2].[Emp_EmpId] AS [Emp_EmpId], [Extent3].[ProjectId] AS [ProjectId], [Extent3].[ProjectName] AS [ProjectName]
    		FROM  [dbo].[ProjectEmps] AS [Extent2]
    		INNER JOIN [dbo].[Projects] AS [Extent3] ON [Extent3].[ProjectId] = [Extent2].[Project_ProjectId] ) AS [Join1] ON [Extent1].[EmpId] = [Join1].[Emp_EmpId]
    	WHERE 1 = [Extent1].[EmpId]
    )  AS [Project1]
    ORDER BY [Project1].[EmpId] ASC, [Project1].[C1] ASC

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Building Many to Many Relationship

    • 8 Comments

    Since we do not have any designer question might arise how can we create Many to Many relationship in Code First 4.1. Here it is

    public class Emp
    {
        public Emp()
        {
            Projects = new HashSet<Project>();
        }
    
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public ICollection<Project> Projects { get; set; }
    }
    
    public class Project
    {
        public Project()
        {
            Emps = new HashSet<Emp>();
        }
    
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
        public ICollection<Emp> Emps { get; set; }
    }
    
    public class EmpContext : DbContext
    {
        public DbSet<Emp> Emps { get; set; }
        public DbSet<Project> Projects { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Project() { ProjectName = "Fun Boat" };
            var p2 = new Project() { ProjectName = "Jumbo Jet" };
            var p3 = new Project() { ProjectName = "Free Zoo" };
    
            var e1 = new Emp() { EmpName = "Wriju" };
            var e2 = new Emp() { EmpName = "Wrishika" };
            var e3 = new Emp() { EmpName = "Saswati" };
    
            p1.Emps.Add(e1);
            p1.Emps.Add(e2);
    
            p2.Emps.Add(e2);
            p2.Emps.Add(e3);
    
            p3.Emps.Add(e3);
            p3.Emps.Add(e1);
    
            using (var ctx = new EmpContext())
            {
                ctx.Projects.Add(p1);
                ctx.Projects.Add(p2);
                ctx.Projects.Add(p3);
                    
                ctx.SaveChanges();
            }
        }
    }

    Generated database would look like

    image

    Namoskar!!!

  • Wriju's BLOG

    CodeFirst EF 4.1 : Changing Database Table and Column name

    • 2 Comments

    At times we need to control the Table and Column name of our generated database or have different Entity/Property name of code than actual database in EF 4.1 Code First. There are two ways we can do it.

    Using Annotations

    using System.ComponentModel.DataAnnotations;
    
        //Changing database Table name to Employee
        [Table("Employee")]
        public class Emp
        {
            //Changing database column name to EmpId
            [Column("EmpId")]
            public int Id { get; set; }
            public string Name { get; set; }
        }

    Using FluentAPI

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Changing Database Column name to EmployeeId
        modelBuilder.Entity<Emp>()
            .Property(p => p.Id)
            .HasColumnName("EmployeeId");
    
        //Changing Database table name to EmployeeData
        modelBuilder.Entity<Emp>()
            .ToTable("EmployeeData");
    }
    Note: If you have both Annotation and FluentAPI available, the FluentAPI will win.

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Missing “ADO.NET DbContext Generator” VS Template

    • 6 Comments

    I have seen people coming back to me asking questions about the template visible in Visual Studio 2010 as “ADO.NET DbContext Generator”. This template allows you to create the POCO classes and the context for CodeFirst from already existing edmx file.

    The template in Visual Studio looks like

    image

    But missing. But why?

    At times if you have used NuGet package manager to install the EF 4.1 then the ADO.NET DbContext Generator would not come.

    This template gets installed only when you install the complete EF 4.1 from MSDN here

    Namoskar!!!

  • Wriju's BLOG

    Code First 4.1 : Using Stored Procedure to Insert Data

    • 4 Comments

    Code First in Entity Framework does not support Stored Procedure by default. As there is no designer we cannot even map our stored procs to the entity. There are a many scenario we have seen where we are bound to use stored procedure for any database modifications (insert/update/delete). Here is how we can use stored procedure.

    image

    This would finally call the Stored Procedure.

    The stored proc used here is very simple

    ALTER PROCEDURE [dbo].[stp_InsertEmp]
    (
    	@Name as VARCHAR(50)
    ) AS
     
    	INSERT INTO Emps(Name) VALUES(@Name)

    Namoskar!!!

Page 8 of 25 (620 items) «678910»