Saturday 26 December 2015

Reading Image and Video from device in windows phone 8.1

1.  Create a button control in Xaml page.

MainPage.Xaml
 <Button x:Name="btnPhotos" HorizontalAlignment="Left" Margin="2,256,0,0" VerticalAlignment="Top" FontFamily="Arial" Width="388" Height="96" Click="btnPhotos_Click">
            <TextBlock x:Name="textBlock" Text="Photos" FontSize="28" Foreground="#FF7A7070"  Width="210" Height="42"/>
 </Button>
 <Button x:Name="btnVideo" HorizontalAlignment="Left" Height="99" Margin="3,366,0,0" VerticalAlignment="Top" FontFamily="Arial" Width="387" Click="btnVideo_Click">
            <TextBlock Name="textVideo" Text="Video" FontSize="28" Margin="10,0,23,0" Foreground="#FF7A7070" Width="210" Height="42"></TextBlock>
 </Button>

2. Write the following code on code behind.
MainPage.Xaml.cs
========================
 private async void btnPhotos_Click(object sender, RoutedEventArgs e)
        {
            photosProgressBar.Visibility = Visibility.Visible;
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.PickMultipleFilesAndContinue();
        }

 private async void btnVideo_Click(object sender, RoutedEventArgs e)
        {
            videoProgressBar.Visibility = Visibility.Visible;
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".mp4");
            //openPicker.FileTypeFilter.Add(".jpeg");
            //openPicker.FileTypeFilter.Add(".png");
            openPicker.PickMultipleFilesAndContinue();
        }

 public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            IReadOnlyList<StorageFile> files = args.Files;
            if (files.Count > 0)
            {

                foreach (var item in files)
                {
   //Do your work                  
                }
            }
        }

3. Write an event in App.Xaml.cs.
App.Xaml.cs
===========================
  protected override void OnActivated(IActivatedEventArgs args)
        {
           // Sync osync = new Sync();
            var root = Window.Current.Content as Frame;
            var sync = root.Content as Sync;
            if (sync != null && args is FileOpenPickerContinuationEventArgs)
            {
                sync.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
            }
        }
      

Voice Recording/Mic Testing and Playing Recorded Sound in Windows Phone Silverlight

<phone:PhoneApplicationPage x:Class="MicrophoneTest.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">  
  1.     <!--LayoutRoot is the root grid where all page content is placed-->  
  2.     <Grid x:Name="LayoutRoot" Background="LightBlue">  
  3.         <Image x:Name="ScanComp" HorizontalAlignment="Left" Height="170" Margin="156,235,0,0" VerticalAlignment="Top" Width="170" />  
  4.         <TextBlock Name="timerMsg" Margin="10,460,10,257" TextAlignment="Center" Foreground="White" FontSize="24"></TextBlock>  
  5.         <TextBlock Name="timedisplayBlock" Margin="206,508,221,209" Foreground="White" FontSize="40"></TextBlock>  
  6.         <Button Name="btnstart" Content="start" Click="recordButton_Click" Margin="0,636,0,58"></Button>  
  7.     </Grid>  
  8. </phone:PhoneApplicationPage> 
  1. public partial class MainPage: PhoneApplicationPage  

  2. {  
  3.     // Constructor  
  4.     int currentcount;  
  5.     Microphone microphone = Microphone.Default;  
  6.     byte[] buffer;  
  7.     MemoryStream stream = new MemoryStream();  
  8.     SoundEffect sound;  
  9.     DispatcherTimer recordingTimer;  
  10.     public MainPage()  
  11.     {  
  12.         InitializeComponent();  
  13.         recordingTimer = new DispatcherTimer();  
  14.         recordingTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);  
  15.         recordingTimer.Tick += new EventHandler(recordingTimer_Tick);  
  16.     }  
  17.     private void recordButton_Click(object sender, EventArgs e)  
  18.     {  
  19.         Startrecording();  
  20.     }  
  21.     protected async void Startrecording()  
  22.     {  
  23.         ScanComp.Source = new BitmapImage(new Uri(@ "Assets/scan_microphone.png", UriKind.Relative));  
  24.         timerMsg.Text = "Speak something to test recording.";  
  25.         currentcount = 10;  
  26.         recordingTimer.Start();  
  27.         DispatcherTimer dt = new DispatcherTimer();  
  28.         dt.Interval = TimeSpan.FromMilliseconds(33);  
  29.         dt.Tick += delegate  
  30.         {  
  31.             try  
  32.             {  
  33.                 FrameworkDispatcher.Update();  
  34.             }  
  35.             catch  
  36.             {}  
  37.         };  
  38.         dt.Start();  
  39.         microphone.BufferReady += new EventHandler < EventArgs > (microphone_BufferReady);  
  40.         microphone.BufferDuration = TimeSpan.FromMilliseconds(1000);  
  41.         buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];  
  42.         microphone.Start();  
  43.         await Task.Delay(TimeSpan.FromSeconds(10));  
  44.         if (microphone.State == MicrophoneState.Started)  
  45.         {  
  46.             microphone.Stop();  
  47.         }  
  48.         timerMsg.Text = "playing sound...";  
  49.         sound = new SoundEffect(stream.ToArray(), microphone.SampleRate, AudioChannels.Mono);  
  50.         sound.Play();  
  51.     }  
  52.     void microphone_BufferReady(object sender, EventArgs e)  
  53.     {  
  54.         microphone.GetData(buffer);  
  55.         stream.Write(buffer, 0, buffer.Length);  
  56.     }  
  57.     private void recordingTimer_Tick(object sender, EventArgs e)  
  58.     {  
  59.         timedisplayBlock.Text = currentcount--.ToString();  
  60.         if (currentcount == 0)  
  61.         {  
  62.             recordingTimer.Stop();  
  63.             timedisplayBlock.Text = "";  
  64.             timerMsg.Text = "playing sound...";  
  65.         }  
  66.     }  
  67. }  

Windows Phone Device Mode and Version in windows phone Silverlight 8.1.

  1. public MainPage()  
  2. {  
  3.     InitializeComponent();  
  4.     var phone = PhoneNameResolver.Resolve(DeviceStatus.DeviceManufacturer, DeviceStatus.DeviceName);  
  5.     txtModel.Text = Convert.ToString(phone.FullCanonicalName);  
  6.     txtVrsn.Text = Convert.ToString(System.Environment.OSVersion);  
  7.   
  8.      
  9. }  http://www.c-sharpcorner.com/code/2075/windows-phone-device-model-and-version-in-windows-phone-silv.aspx

Add Edit Delete in XML file using MVC

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcXML.Models;  
  7. using System.Data;  
  8. using System.Xml.Linq;  
  9. using System.Xml;  
  10. namespace MvcXML.Controllers   
  11. {  
  12.     public class AdminController: Controller   
  13.     {  
  14.         //  
  15.         // GET: /Admin/  
  16.         public ActionResult Index()   
  17.         {  
  18.             List < ProjectModels > lstProject = new List < ProjectModels > ();  
  19.             DataSet ds = new DataSet();  
  20.             ds.ReadXml(Server.MapPath("~/XML/ProjectList.xml"));  
  21.             DataView dvPrograms;  
  22.             dvPrograms = ds.Tables[0].DefaultView;  
  23.             dvPrograms.Sort = "Id";  
  24.             foreach(DataRowView dr in dvPrograms)   
  25.             {  
  26.                 ProjectModels model = new ProjectModels();  
  27.                 model.Id = Convert.ToInt32(dr[0]);  
  28.   
  29.                 model.ProjectName = Convert.ToString(dr[1]);  
  30.   
  31.                 model.Location = Convert.ToString(dr[2]);  
  32.                 lstProject.Add(model);  
  33.             }  
  34.             if (lstProject.Count > 0)   
  35.             {  
  36.                 return View(lstProject);  
  37.             }  
  38.             return View();  
  39.             return View();  
  40.         }  
  41.         ProjectModels model = new ProjectModels();  
  42.         public ActionResult AddEditProject(int ? id)   
  43.                 {  
  44.                 int Id = Convert.ToInt32(id);  
  45.                 if (Id > 0)   
  46.                 {  
  47.                     GetDetailsById(Id);  
  48.                     model.IsEdit = true;  
  49.                     return View(model);  
  50.                 } else   
  51.                 {  
  52.                     model.IsEdit = false;  
  53.                     return View(model);  
  54.                 }  
  55.             }  
  56.             [HttpPost]  
  57.         public ActionResult AddEditProject(ProjectModels mdl)  
  58.             {  
  59.   
  60.             if (mdl.Id > 0) {  
  61.                 XDocument xmlDoc = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));  
  62.                 var items = (from item in xmlDoc.Descendants("Project") select item).ToList();  
  63.                 XElement selected = items.Where(p => p.Element("Id").Value == mdl.Id.ToString()).FirstOrDefault();  
  64.   
  65.                 selected.Remove();  
  66.                 xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));  
  67.                 xmlDoc.Element("Projects").Add(new XElement("Project",  
  68.                     new XElement("Id", mdl.Id),  
  69.   
  70.                     new XElement("ProjectName", mdl.ProjectName),  
  71.   
  72.                     new XElement("Location", mdl.Location)  
  73.                 ));  
  74.                 xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));  
  75.   
  76.                 return RedirectToAction("Index""Admin");  
  77.             } else {  
  78.                 XmlDocument oXmlDocument = new XmlDocument();  
  79.                 oXmlDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));  
  80.                 XmlNodeList nodelist = oXmlDocument.GetElementsByTagName("Project");  
  81.                 var x = oXmlDocument.GetElementsByTagName("Id");  
  82.                 int Max = 0;  
  83.                 foreach(XmlElement item in x) {  
  84.                     int EId = Convert.ToInt32(item.InnerText.ToString());  
  85.                     if (EId > Max) {  
  86.                         Max = EId;  
  87.                     }  
  88.                 }  
  89.                 Max = Max + 1;  
  90.                 XDocument xmlDoc = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));  
  91.                 xmlDoc.Element("Projects").Add(new XElement("Project",  
  92.                     new XElement("Id", Max),  
  93.   
  94.                     new XElement("ProjectName", mdl.ProjectName),  
  95.   
  96.                     new XElement("Location", mdl.Location)  
  97.                 ));  
  98.                 xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));  
  99.                 return RedirectToAction("Index""Admin");  
  100.             }  
  101.   
  102.         }  
  103.   
  104.         public ActionResult Delete(int Id) {  
  105.             if (Id > 0) {  
  106.                 XDocument xmlDoc = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));  
  107.                 var items = (from item in xmlDoc.Descendants("Project") select item).ToList();  
  108.                 XElement selected = items.Where(p => p.Element("Id").Value == Id.ToString()).FirstOrDefault();  
  109.                 selected.Remove();  
  110.                 xmlDoc.Save(Server.MapPath("~/XML/ProjectList.xml"));  
  111.             }  
  112.             return RedirectToAction("Index""Admin");  
  113.   
  114.         }  
  115.   
  116.   
  117.         public void GetDetailsById(int Id) {  
  118.             XDocument oXmlDocument = XDocument.Load(Server.MapPath("~/XML/ProjectList.xml"));  
  119.             var items = (from item in oXmlDocument.Descendants("Project") where Convert.ToInt32(item.Element("Id").Value) == Id select new projectItems {  
  120.                 Id = Convert.ToInt32(item.Element("Id").Value),  
  121.   
  122.                     ProjectName = item.Element("ProjectName").Value,  
  123.   
  124.                     Location = item.Element("Location").Value,  
  125.             }).SingleOrDefault();  
  126.             if (items != null) {  
  127.                 model.Id = items.Id;  
  128.   
  129.                 model.ProjectName = items.ProjectName;  
  130.   
  131.                 model.Location = items.Location;  
  132.             }  
  133.         }  
  134.         public class projectItems {  
  135.             public int Id {  
  136.                 get;  
  137.                 set;  
  138.             }  
  139.   
  140.             public string ProjectName {  
  141.                 get;  
  142.                 set;  
  143.             }  
  144.   
  145.             public string Location {  
  146.                 get;  
  147.                 set;  
  148.             }  
  149.             public projectItems() {}  
  150.         }  
  151.     }  

.Net Framework at a glance.


To work on ASP. NET and to understand the ASP. Net World, first we have to understand .NET Framework. . It is a common question which is asked in interviews that "What is .NET Framework? and what is the need of .NET Framework?"

As I know about my friends and caliuge who is working as a web developer also faces a problems on .NET Framework's questions. So, today I decided to write about .NET framework.

.NET Framework

1. .NET framework is a complete development and execution environment. That allows the developer to develop , run and deploy the following application.

a. Console application. b. Windows application c. Web application

d. Service oriented application (WCF) e. Web service f. Windows service

g. WPF, WWF etc.

2. .Net framework support the object oriented programming model for multiple language such as, C#, VB, vC++, J# etc.

3. It support the language interoperability .Interoperability implies that each language can use the code written in some other language.

4. It provides a common set of tools enables easy integration of module developed with one another.

5. It also enables the developers to create sharable component to be used in distributed computing architecture.



Need of .NET Framework

.NET Framework was designed to fulfill the following goals.

a. Interoperability b. Cross platform Support c. Language Independence

d. Base class library. e. Easy development f. Security

Interoperability: .NET Framework supports interoperability between new application and existing application. It implies that the code written in one language can be used in some other language.





Cross Platform support: Each .NET compatible language, such as C#, VB, VC++ provides its own compiler to compile code to MSIL . After that , the common runtime engine compile MSIL code to native code with the help of Just In Time (JIT) compiler and then run the application.



Language Independence: .NET framework provides the multiple language support by using the feature known as common type system. That is built into common language runtime.

Base Class Library: The base class library provides the fundamental building block for any application you develop. These application could be windows , web, console, or service oriented. The BCL mostly serves as the main point of interaction with the CLR.

Easy Deployment: .NET Framework makes the task of employment easier. In most cases , to install an application along with component on the target computer.

Security: .NET Framework provides security model that allows you to authorize and authenticate the user.



Component of .NET Framework

Following are the main component of the .NET Framework.

1. .Net Framework library 2. CLR 3. DLR (Dynamic Language Runtime

4. Application Domain 5. Runtime host 6. CTS ( Common Type System)

7. Metadata 8. Cross Language Interoperability

9. Security 10. Side by side execution 11. Profiling etc.

Above all components discussed separately in next topic.



MSIL (Microsoft Intermediate Language) OR Intermediate Language( IL)

IL stands for Intermediate Language. It is also known as MSIL(Microsoft Intermediate Language) or CIL (Common Intermediate Language ). All the .NET language such as C#, J#,VB uses there own compiler. the compiler compile the code into IL and after than common runtime engine convert the IL code into native code with the help of JIT compiler. OR …

MSIL : .Net is shipped with compiler of all programming language to develop program. There are separate compiler for the VB, C#, VC++ etc. All compilers produce an intermediate code after compiling source code. The intermediate code is common for all language and it is understandable into .NET environment. This intermediate code is known as IL or MSIL.

Assembly Manifest

Assembly manifest stores the assembly metadata. It contains all the metadata needed to do the following things :-

1. Version of assembly

2. Security Identity

3. Scope of assembly

4. Resolve reference to resource of class

Assembly manifest contains PE file either .exe or .dll

Common Type System

CTS is a component of CLR (Common Language Runtime) through which .NET framework provide support for multiple language. Because it contains a type system, that is common across all the language. Two common type system language do not require type conversion when calling the code written in another language. CTS provide a base set of data type for all language supported by .NET framework. This means that the size of integer and long variable is same across all language.

Managed and Unmanaged code

Managed Code : Managed code is the code that executed directly by CLR instead of operating system. The language compiler compile the managed code to IL or MSIL. This code does not depend on the machine configuration and can be executed on different machine. Manage code process are as follows :-

Choose Language Compiler --> Compile to MSIL --> MSIL to Native Code -->Execute the code

Unmanaged Code : Unmanaged code is the code that is executed directly by the operating system outside the CLR environment. It is directly compiled to native machine code which depends on the machine configuration. In unmanaged code, The allocation of memory , Type safety and security is required to be taken care of by the developer. If unmanaged code is not properly handled. It may result in memory leak.



Assembly in .NET framework

Every software has an executable file (.exe) apart from the .exe file, there are some dynamic link library (.dll) and Library file (.lib) that contains the compiled code of some commonly used function. These file are shipped along with the software. Any software package includes an executed file along with some DLL and LIB file that are necessary to run the application. In term of .NET runtime, the process of packing is called assembly. An assembly contains MSIL, Metadata file are required to execute a .NET program successfully. There are two types of assembly. They are :

1. Private Assembly 2. Public assembly



Global Assembly Catch (GAC )

While using shared assembly, To avoid assembly being overwritten by the different or same assembly . Shared assembly are placed in a special directory in the file system are known as global assembly catch.

Or

GAC is a central repository (cache) in a system in which assemblies are registered to share among various applications that execute on local or remote machines. .NET Framework provides the GAC tool (gacutil.exe utility), which is used to view and change the content of GAC of a system. Adding new assemblies to GAC and removing assemblies from GAC are some of the tasks that can be performed by using the gacutil.exe utility. GAC can contain multiple versions of the same .NET assembly. CLR checks GAC for a requested assembly before using information of configuration files.



Component and services of CLR

There are several component of CLR, Which are as follows :

1. CTS 2. MSIL 3. Execution Support Function 4. Security

5. Garbage collection 6. Class loader 7. Memory layout

Services of CLR :

1. Loading and execution of program 2. Memory Isolation for application

3. Verification of type safety. 4. Compilation of MSIL to native code

5. Providing Metadata 6. Interoperability with other system

7. Managing exception and error 8. Debugging and profiling.



Garbage collection

Garbage collection prevent memory leaks during execution of programs. It is a low priority process that manages the allocation and deallocation of memory in your application. It checks for unreferenced variable and objects. If GC find any object that is no longer uses by application, it frees up the memory that object.

GC has changed a bit in .Net framework 4.0. It contains following overload method.

1. GC.collect () 2. GC.collect (int, GC collection method)

Generation of garbage collection :

1. Generation 0 : when an object is initialized.

2. Generation 1 : The object under the GC process.

3. Generation 2 : whenever new object are created and added to memory. It adds generation 0 and generation 1.



Namespace in .Net framework

Namespace has two basic functionality :-

1. It is a logically group type.

2. In object oriented world many times it is possible that , programmer will use the same class name by qualifying namespace with class name, this collision is able to remove.

Difference between Assembly and Namespace

1. An assembly is a physical grouping of logical unit. While namespace is logically group of class.

2. A namespace can span multiple assembly.

3. It is a collection of name wherein each name is unique. While assembly is an output unit. It contains a unit of development and deployment.

Difference between private and shared assembly

Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.