September, 2013

  • Wriju's BLOG

    Build Windows Phone Apps using Windows Azure Mobile Services from Ground Up

    • 2 Comments

    Windows Phone 8 works really well with Window Azure Mobile Services. Windows Azure portal gives us the startup apps, however you can also build from ground up. Here it is,

    Let’s say you have created a Windows Azure Mobile Service

    image

    image

    Once it is ready

    image

    Grab the URL and Key. After that create a blank Windows Phone 8 Apps.

    image

    Then add the Windows Azure Mobile Services from http://nuget.org. Run the below command in Library Package Manager Console 

    image

    This will install these below assemblies

    image

    After that in App.xaml.cs add this line

     

    public static MobileServiceClient MobileService = 
    
        new MobileServiceClient("https://wpmobile.azure-mobile.net/", "jjj.....");

    Create a blank table in Windows Azure Mobile Services called “Employee

    image

    image

    Then add the entity called “Employee”

    //The Model Class
    
    public class Employee
    
    {
    
        public int Id { get; set; }
    
        public string FullName { get; set; }
    
    }

    To add a new Employee

    private void SaveData(Employee emp)
    
    {
    
        App.MobileService.GetTable<Employee>().InsertAsync(emp);
    
    }

    This will add a new column called FullName because the dynamic schema is ON by default.

    Similarly we can read the data

    var emps = await App.MobileService.GetTable<Employee>().ReadAsync();

    This clearly a simple approach. Adding the XAML and complete C# to run the code

    XAML

    <!--ContentPanel - place additional content here-->
    
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    
        <Grid.RowDefinitions>
    
            <RowDefinition Height="*"></RowDefinition>
    
            <RowDefinition Height="Auto"></RowDefinition>
    
        </Grid.RowDefinitions>
    
        <StackPanel Grid.Row="0">
    
            <TextBox x:Name="txtName"></TextBox>
    
            <Button x:Name="btnSave" Content="Save" Click="btnSave_Click"></Button>
    
            <Button x:Name="btnLoad" Content="Load Data" Click="btnLoad_Click"></Button>
    
        </StackPanel>
    
                
    
        <ListBox x:Name="lstData" Grid.Row="1" VerticalAlignment="Top">
    
            <ListBox.ItemTemplate>
    
                <DataTemplate>
    
                    <TextBlock FontSize="30" Text="{Binding Path=FullName}"></TextBlock>
    
                </DataTemplate>
    
            </ListBox.ItemTemplate>
    
        </ListBox>
    
    </Grid>

    Complete C#

    //The Model Class
    
    public class Employee
    
    {
    
        public int Id { get; set; }
    
        public string FullName { get; set; }
    
    }
    
    public partial class MainPage : PhoneApplicationPage
    
    {
    
        public MainPage()
    
        {
    
            InitializeComponent();
    
        }
    
        private void btnSave_Click(object sender, RoutedEventArgs e)
    
        {
    
            Employee emp = new Employee() { FullName = txtName.Text };
    
            SaveData(emp);
    
            ShowData();
    
        }
    
        //Add data
    
        private void SaveData(Employee emp)
    
        {
    
            App.MobileService.GetTable<Employee>().InsertAsync(emp);
    
        }
    
        private void btnLoad_Click(object sender, RoutedEventArgs e)
    
        {
    
            ShowData();
    
        }
    
        //Read the data
    
        private async void ShowData()
    
        {
    
            var emps = await App.MobileService.GetTable<Employee>().ReadAsync();
    
            lstData.ItemsSource = emps;
    
        }        
    
    }

    Namoskar!!!

  • Wriju's BLOG

    Repository Pattern with ADO.NET Entity Framework Hack

    • 4 Comments

    Let’s build ADO.NET Entity Framework library using Repository Pattern. There are a many ways but this is probably the easiest hack. 

    First build a blank solution

    image

    Then add a class library called “DAL” and add a class called “Employee”

    namespace DAL
    
    {
    
        public class Employee
    
        {
    
            public int Id { get; set; }
    
            public string FullName { get; set; }
    
        }
    
    }
    Then in the DAL add “EntityFramework” from http://nuget.org in Package Manager Console

    image

    At Package manager Console it would show

    image

    Then add T4Scaffolding from http://nuget.org in Package Manager Console

    image
    The Package Manager Console would look like

    image

    Project structure will be as below

    image

    Notice that in the reference section the Entity Framework is showing but the “T4Scaffolding” is missing. However the packages.config shows the list.

    This is as template so you will find them at the source folder

    image

    Run the following command from the DAL project’s Package Manager Console

    PM> scaffold repository DAL.Employee -DbContextType:HRContext

    Output would show

    image

    This would create two files under DAL > Models as “EmployeeReopository.cs” and “HRContext.cs

    image

    The content would look like

    HRContext.cs

    namespace DAL.Models
    
    {
    
        public class HRContext : DbContext
    
        {
    
            // You can add custom code to this file. Changes will not be overwritten.
    
            // 
    
            // If you want Entity Framework to drop and regenerate your database
    
            // automatically whenever you change your model schema, add the following
    
            // code to the Application_Start method in your Global.asax file.
    
            // Note: this will destroy and re-create your database with every model change.
    
            // 
    
            // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<DAL.Models.HRContext>());
    
            public DbSet<DAL.Employee> Employees { get; set; }
    
        }
    
    }

    EmployeeRepository.cs

    using System;
    
    using System.Collections.Generic;
    
    using System.Data;
    
    using System.Data.Entity;
    
    using System.Linq;
    
    using System.Linq.Expressions;
    
    using System.Web;
    
    using DAL;
    
    namespace DAL.Models
    
    { 
    
        public class EmployeeRepository : IEmployeeRepository
    
        {
    
            HRContext context = new HRContext();
    
            public IQueryable<Employee> All
    
            {
    
                get { return context.Employees; }
    
            }
    
            public IQueryable<Employee> AllIncluding(params Expression<Func<Employee, object>>[] includeProperties)
    
            {
    
                IQueryable<Employee> query = context.Employees;
    
                foreach (var includeProperty in includeProperties) {
    
                    query = query.Include(includeProperty);
    
                }
    
                return query;
    
            }
    
            public Employee Find(int id)
    
            {
    
                return context.Employees.Find(id);
    
            }
    
            public void InsertOrUpdate(Employee employee)
    
            {
    
                if (employee.Id == default(int)) {
    
                    // New entity
    
                    context.Employees.Add(employee);
    
                } else {
    
                    // Existing entity
    
                    context.Entry(employee).State = EntityState.Modified;
    
                }
    
            }
    
            public void Delete(int id)
    
            {
    
                var employee = context.Employees.Find(id);
    
                context.Employees.Remove(employee);
    
            }
    
            public void Save()
    
            {
    
                context.SaveChanges();
    
            }
    
            public void Dispose() 
    
            {
    
                context.Dispose();
    
            }
    
        }
    
        public interface IEmployeeRepository : IDisposable
    
        {
    
            IQueryable<Employee> All { get; }
    
            IQueryable<Employee> AllIncluding(params Expression<Func<Employee, object>>[] includeProperties);
    
            Employee Find(int id);
    
            void InsertOrUpdate(Employee employee);
    
            void Delete(int id);
    
            void Save();
    
        }
    
    }

    You are simply done. You need a project and add DAL as reference then …

    namespace ConsoleApplication1
    
    {
    
        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                InsertEmployee();
    
            }
    
            private static void InsertEmployee()
    
            {
    
                using (var repo = new EmployeeRepository())
    
                {
    
                    Employee em = new Employee() { FullName = "Wriju" };
    
                    repo.InsertOrUpdate(em);
    
                    repo.Save();
    
                }
    
            }
    
        }
    
    }

    No EntityFramework reference or so.

    image

    Isn’t it easy? Enjoy!!!

    Special thanks to Julie Lerman, if you don’t know who she is then you are not an Entity Framework developer.

     

    Namoskar!!!

  • Wriju's BLOG

    The beautiful MVVM

    • 0 Comments

    Getting Started with MVVM in 10 minutes

     

    Building a Reusable ICommand implementation for Windows Phone MVVM apps

     

    Laurent Bugnion, leads the MVVM Light Toolkit project, has a 4-article MSDN series on MVVM

    IOC Containers and MVVM

    Messenger and View Services in MVVM

    Maximizing the Visual Designer's Usage with Design-Time Data

    Commands, RelayCommands and EventToCommand

     

    And finally, more videos:

    Designing Awesome XAML apps for Windows 8 and Windows Phone 8 (Build 2012)

    Create Cross-Platform Apps using Portable Class Libraries (Build 2012)

    Understanding the Model-View-ViewModel pattern (MIX10)

    Deep Dive MVVM (MIX 11)

    Namoskar!!!

     

  • Wriju's BLOG

    Reinstall Windows Phone Application

    • 1 Comments

    When your phone gets reset or you have a new Windows Phone you might want to get back the old apps you had downloaded in past. Here it is as easy as candy.

    1. Go to http://www.windowsphone.com/

    2. Login using the same Microsoft Account which you are using in the Windows Phone

    3. You need to enable “Find my Phone” from Settings.

    4. Then go to “Purchase Historyhttps://www.windowsphone.com/en-us/my/purchase-history

    This would show you the list of Applications you had installed earlier. You can simply click on reinstall and it will push them to your phone

    image

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework : Executing TSQL and DbContext under same Transaction

    • 0 Comments

    There might be a requirement that we need to run a RAW SQL statement and DbContext update under same connection and would like to have the Transaction in place. Let’s see how we can achieve this easily

    SQL Table

    CREATE TABLE [dbo].[Emp](
    
    	[Id] [int] IDENTITY(1,1) NOT NULL,
    
    	[FirstName] [varchar](50) NOT NULL,
    
    	[LastName] [varchar](50) NULL,
    
     CONSTRAINT [PK_Emp] PRIMARY KEY CLUSTERED 
    
    (
    
    	[Id] ASC
    
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    
    ) ON [PRIMARY]
    

    C# Code

    private static void TransactionSample()
    
    {
    
        int id = 2299;
    
        var trOptions = new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted };
    
        using (var tran = new TransactionScope(TransactionScopeOption.Required, trOptions))
    
        {
    
            using (var ctx = new TestDBEntities())
    
            {
    
                try
    
                {
    
                    ctx.Database.Connection.Open();
    
                    var sqlCommand = ctx.Database.Connection.CreateCommand();
    
                    //TODO: You may add some just char to produce bad query
    
                    sqlCommand.CommandText = "UPDATE Emp SET FirstName ='FirstName1' WHERE Id=" + id.ToString();
    
                    sqlCommand.ExecuteNonQuery();
    
                    //TODO: you may add some wrong id so that it will fail
    
                    var empUpdate = ctx.Emps.Where(p => p.Id == id).First();
    
                    empUpdate.LastName = "LastName1";
    
                    ctx.SaveChanges();
    
                            
    
                    tran.Complete();
    
                }
    
                catch
    
                {
    
                    Console.WriteLine("Some error occured");
    
                    //Fail the Transaction
    
                }
    
            }
    
        }
    

    }

  • Wriju's BLOG

    Windows Azure Mobile Services : Adding and Filtering Authenticated User in Table

    • 0 Comments

    When you authenticate you Mobile apps using Windows Azure Mobile Services you may want to add the user id in your table row. This way you can later filter them while reading. This sandbox filing would give a portal experience to the end user. Now this can be done at the client level but the “Server Script” is the most elegant way to do it because it can hide the code from user to do injection.

    During insert you may write

    image

     

    While reading you also need to filter out.

    image

    So your table level data security is implemented.

    Namoskar!!!

  • Wriju's BLOG

    Office 365 is free for NGO

    • 0 Comments

    It’s a channel and to know more about it visit http://www.microsoft.com/en-us/news/Press/2013/Sep13/09-10Office365NonprofitsPR.aspx

    Microsoft Corp. on Wednesday announced the global availability of Office 365 for Nonprofits for qualifying nonprofits and nongovernmental organizations (NGOs) through its software donation program. The donation is available immediately in 41 countries around the world and for up to 90 countries by July 2014…..

    Namoskar!!!

Page 1 of 1 (7 items)