Working with Local Storage in Windows Phone App

Gallery

Ray Yagubyan

Ray Yagubyan

In almost all the apps that are developed, some sort of data needs to be stored on the device either temporarily or permanently. There are lots of options of storing data when working on Windows Phone platform. In my earlier tutorials, we looked at how to create a simple Windows Phone app and performing page navigation. In this post, lets take a look at how to Read and Write files to the Local Folder in Windows Phone.

Open Visual Studio 2013/2012 and Create a New Windows Phone App project and name it “LocalStorageWpApp”. We will be creating a small application where we will read and write contents in a local file on Windows Phone.

Once the default solution is create, open MainPage.xaml and rename the page title to say “Local Storage”. Add the below XAML code to the ContentPanel Grid.

 

<StackPanel >
             <TextBlock Text="FileName" />
             <TextBox Name="txtFileName" />
             <TextBlock Text="Content" />
             <TextBox Name="txtFileContent" Height="200" TextWrapping="Wrap"  />
             <Button Content="Create File" Name="btnCreate" Tap="btnCreate_Tap" />
             <Button Content="View Files" Name="btnView" Tap="btnView_Tap" />
</StackPanel>

We have added the Textboxes where the user can enter the filename as well as the file content which is to be stored in the file. Once the user hits the “Create File” button, a new file will be created in the local folder with the filename specified. We call the “SaveFile” function which is implemented as shown below

private async void SaveFile()
        {
            try
            {
                StorageFolder folder = ApplicationData.Current.LocalFolder;

                if(folder != null)
                {

                    StorageFile file = await folder.CreateFileAsync(txtFileName.Text, CreationCollisionOption.ReplaceExisting);

                    byte[] fileContent = Encoding.UTF8.GetBytes(txtFileContent.Text.ToCharArray());

                    Stream fileStream = await file.OpenStreamForWriteAsync();
                    fileStream.Write(fileContent, 0, fileContent.Length);
                    fileStream.Flush();
                    fileStream.Close();

                    MessageBox.Show("File Has Been Created");
                    txtFileContent.Text = "";
                    txtFileName.Text = "";
                }

            }
            catch (Exception ex)
            {

                // Some Exception handling code
            }

        }

 

The “Windows.Phone.Storage” namespace contains the “StorageFolder” and “StorgaeFile” classes which provides method for working with Files and Folders in Windows Phone Application. In the code above, we are storing some string content in a file in local application data folder. The StorageFolder class gives access to the root container and allows operations like creating and reading files. It also contains different functions for creating as well as deleting files/folders.

Once we get a handle to the Local Folder using the ApplicationData instance, we call the “CreateFileAsync” function and pass the name of the file. We also specify an additional Collision Option through the CreateCollisionOption enumeration. In this case, we are specifying the file should be replaced if a file with the same name already exists. Since the “CreateFileAsync” function is asynchronous it is necessary to execute these using the “await” and “async” keywords.

Once the file is created, we use the “OpenStreamForWriteAsync” function to get a stream which can then be used to write content to the file. This is similar to what we normally used while working with files in C#. If the file is successfully created, we display a message.

As the files are now getting created, lets display the list of files to the user which are present in the Local Folder. Right Click on Project –> Add –>New Item –> Windows Phone Portrait Page and name it ViewFiles.xaml. In this page, we will display the List of files which we are creating in the Local Folder. In the “View Files” button tap event add the below code which navigates the user to our newly added page.

 

private void btnView_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ViewFiles.xaml", UriKind.Relative));
        }

 

 Open ViewFiles.xaml and add the following XAML to the ContentPanel grid.

 

<phone:LongListSelector Margin="0,-10,-22,2" SelectionChanged="LongListSelectorFiles_SelectionChanged" Name="llsFiles" >

                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                           <StackPanel >
                                <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Margin="10,35"  Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="{StaticResource PhoneFontSizeLarge}" />
                           </StackPanel>
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>

 

We are going to display the List of File Names using the LongListSelector control. In the code behind file, we handle the “OnNavigatedTo” event and call the “GetFilesList” function which has below code

 

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    GetFilesList();
}

public async void GetFilesList()
{
    StorageFolder folder = ApplicationData.Current.LocalFolder;

    IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();

    FilesList = new List<StorageFile>(files);
    llsFiles.ItemsSource = FilesList;

}

 

 In the “GetFilesList” function, we again obtain a handle to the local folder and get a list of files in the current folder using the “GetFilesAsync” method. It returns an IReadOnly List of ‘StorageFile’ types which we then save to the FilesList variable. We then set the ItemSource property of our LongListSelector to “FilesList”. This displays the list of file names.

Lets run the app in our emulator. Once the application starts, enter the file name and some text in the Content Text box and click on “Create File”. The File will be created. Clicking the “View Files” button takes us to separate page which list down the name of the files which we have created.

  

Lets add the functionality display the contents of the file which the user selects from the list. Add a new ‘Windows Phone Portrait Page’ to the project and name it “SinglePage.xaml”. We will handle the “SelectionChanged” event of the LongListSelector.

 

private void LongListSelectorFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (llsFiles.SelectedItem != null)
            {
                var file = llsFiles.SelectedItem as StorageFile;
                NavigationService.Navigate(new Uri("/SingleFile.xaml?filename=" + file.Name, UriKind.Relative));
                llsFiles.SelectedItem = null;
            }
        }

 

 In the above code, we use the ‘SelectedItem’ property which contains the object which the user selected and typecast it to ‘StorageFile’ type as our LongListSelector is bound to List<StorageFile”> object. Once we get the selected object, we use the ‘Name’ property to get the file name and we pass it as a query string to the “SinglePage.xaml”.

Open “SinglePage.xaml” and add the below XAML to the ContentPanel Grid.

 

<StackPanel>
                <TextBlock Text="File Name" />
                <TextBox Name="txtFileName" IsReadOnly="True" />
                <TextBlock Text="Content" />
                <TextBox Height="200" Name="txtFileContent" />
                <Button Content="Update" Name="btnUpdate" Tap="btnUpdate_Tap" />
                <Button Content="Cancel" Name="btnCancel" Tap="btnCancel_Tap" />
</StackPanel>

 

 This is similar to our main page. We are displaying the name of the file as well as its content to the user. The user can change the content and update the same and the file will be updated. Add the below code to the “SinglePage.xaml.cs” files to read the content of the file which the user has selected.

 

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    string filename;

    if(NavigationContext.QueryString.TryGetValue("filename",out filename))
    {
        DisplayFile(filename);
    }
}

private async void DisplayFile(string filename)
{
    StorageFolder local = ApplicationData.Current.LocalFolder;

    if(local != null)
    {

        try
        {
            Stream file = await local.OpenStreamForReadAsync(filename);

            StreamReader sr = new StreamReader(file);
            string content = sr.ReadToEnd();
            txtFileContent.Text = content;
            txtFileName.Text = filename;
            sr.Close();
            file.Close();

        }
        catch(Exception ex)
        {
            // SOme Exception Handling
        }

    }
}

 

In the ‘OnNavigatedTo’ event, we read the file name from the query string and pass it to the function. In the “DisplayFile” function, we use the “OpenStreamForReadAsync” function to get a reference to the stream. We then create an instance of the StreamReader class to read the content of the file and we are displaying the same in the Textbox.

To Update the file, we can use the similar function which we will be almost same as the “SaveFile” function we saw earlier. You can run the app in the emulator. On clicking on a file name, you will be redirected to different page which will list the content of the file.

In the next post, we will take a look at storing data in Memory card and local databases.

Download Solution

After 50 Years,BASIC still Misunderstood!

Gallery

Ray Yagubyan

Ray Yagubyan

It appears that the BASIC programming language has been around a lot longer than most of us have realized. It had its beginnings back in 1964 at Dartmouth College. BASIC has a long and rich history as a programming language, but often today it is viewed as a beginners language or childs language. What few may appreciate is how great an impact BASIC has had on programming and how it has grown over time. When programmers hear the name BASIC today, they often think about a slow interpreted language with little use for real world programming. This is the furthest thing from the truth though.

Why BASIC ?

Having experienced writing a FORTRAN program using punch cards back in the 1970′s, I can attest to how amazing it was to use BASIC on a video terminal in real time. You could get immediate results when writing code. Write a few lines of code and then RUN it and you had immediate results. Coding became something the average person could do. But what made BASIC so well received ?

Aside from the immediate results one got from using an interpreted language, the real key to BASIC was its more natural syntax. If one had any experience with basic algebra in school, picking up the BASIC language was not very difficult. The idea of variables to store numbers, basic mathematical expressions along with a simple, easy to use command language for adding logic made BASIC just make sense. It was coding using language we are used to. Some have referred to it as a more “natural”programming language. Compared to languages of today, like C++, it is obvious why a language like BASIC would be appealing.

But could you get real work done with BASIC ?

Absolutely !  As quickly as people started learning BASIC, they also started finding ways to get some real work done with it.  The reason for programming languages is to be able to get real work done with a computer. As long as this is accomplished, then a programming language is valuable. So, did a lot of programmers get some real work done with BASIC ? More than many may imagine. Actually BASIC created a different breed of programmer. Rather than simply leaving programming in the hands of a select few highly trained professionals, BASIC brought programming to the average person. A engineer could write programs to solve daily problems on his job. An accountant could write programs to make the daily drudgery of working with lots of numbers faster and more accurate. The first tasks these budding programmers solved likely were simple, but as one task was solved, they often would tackle something even more complex next. Before long, people were learning on their own how to write some very complex software, even turning what started as a hobby into a real business.  They took their knowledge of their specific trade and used programming as a way to create new ways to solve all sorts of problems. They got real work done and did it well.

BASIC, the language, grew in ways few would have expected.

The interesting thing about BASIC is that the creators of the different BASIC flavors (brands) often did not expect the results they got. What may have been viewed as a training or hobby programming language, was often used to accomplish real work in the business world and was quite successfully. One of the best examples of this was Visual Basic. Visual Basic, for all practical purpose, was not intended to replace so called higher level languages like C. But something amazing happened with Visual Basic. People who were not professional programmers or even trained in college in computer science, were creating commercial software to solve all sorts of problems in business. The number of commercial applications written in Visual Basic by so called “hobby” programmers is likely astounding if one were to actually calculate the actual numbers. Some very good software was written by such “hobby” programmers too.

What some may not appreciate is that those who learned how to program in BASIC were (and are today) just as interested in finding ways to push the boundaries of software development as any college trained C (or C++) programmer is. This has been going on for a long time, whether the mainstream programming world has noticed. Let’s go back a few years and see.

BASIC on every computer !

Back in the 1980′s, BASIC found its way onto nearly every desktop and home computer. GWBasic came with early MSDOS and later another version called QBasic shipped with Microsoft DOS. I was using BASIC back before DOS on CPM computers to write business applications. When the hobby home computer became popular, with the TI-99/4A computer by Texas Instruments, the Atari computers and the famous Commodore 64, they all came with a version of BASIC burned into ROM. While slow in execution speed, the languages made up for that in ease of use and accessability. BASIC was everywhere !

BASIC programmers are more than hobby programmers !

But BASIC programmers quickly learned to want more. Did they all switch to C ? No, they loved BASIC, so instead they found ways to expand the language, to improve it. Programmers using ROM based Basics learned machine language so they could extend the language. I once wrote such an extension to Commodore ROM basic which added sprite and graphic commands to the language. Now despite the misconception that all BASIC’s were (or are) interpretors, I started using a real BASIC language compiler on my Commodore 64 back in the 1980′s.  Abacus had a very nice compiler which produced programs nearly as fast as those hand coded in assembler and it was BASIC. I used the Abacus compiler to write my own subset BASIC compiler specifically for producing programs which were even closer to those written in assembler, in speed.

BASIC programmers have long appreciated the value of an optimized compiler. They stopped using line numbers and interpreted languages a long time ago. BASIC over the years picked up some of the best features from other languages, like Pascal and C. But BASIC though was about ease of coding. New features were not added to BASIC simply to make it the same as other languages, but simply to gain the best feature sets possible while maintaining the naturalness of BASIC. They wanted the best of both worlds, power and ease of use. What BASIC programmers didn’t want was added complexity to programming. Many different flavors of BASIC over the years came along and tried to maintain that goal of ease of programming. In the DOS days, BASIC programmers would use tools like screen layout designers, code generators and the like. In the Windows years, different versions of BASIC came along which provided drag and drop visual designers. If the BASIC language some used didn’t have a visual designer, its community of users often built their own. In the early Windows years there were a number of commercial BASIC’s created, some by some very big companies. Aside from Visual Basic 1.0, there was GFA Basic, CA Realizer and a number of independent BASIC’s (indie developers who created shareware Basic languages or freeware). Early versions of Visual Basic were PCode compilers and in time users demanded more power and speed and Visual Basic 5.0 introduced a real compiler backend which was nearly as good as many a C compiler. In the DOS days some very powerful BASIC compilers were commercially sold, QuickBasic (and PDS 7.1) from Microsoft and TurboBasic from Borland (which still exists today as Powerbasic). Those BASIC compilers produced very high quality applications. Back when I was using Microsoft’s PDS 7.1 Basic compiler, I was writing some extension libraries in assembler to add even more power to the language. The way I compiled the applications was so complex, I couldn’t do it from the IDE and had to write batch files which would compile my applications just the right way so I could get the most out of the compiler.

Yes, BASIC programmers were (and still are) a unique breed. They want to be able to produce the best and the fastest software possible and were willing to push the limits of the compilers they used. As a long time BASIC programmer myself, I often found myself looking for something better. I wanted to program faster. I wanted to produce smaller and faster applications. I wanted more powerful features. But like many other BASIC programmers, it was not a matter of switching to a different language, like C++, but in finding ways to make BASIC better. There is something about BASIC which just makes it feel right for many programmers. Personally, I think it has a lot to do with the more natural syntax of the language. While many modern BASICs support object oriented syntax when wanted, many long time BASIC programmers find a more procedural style of coding preferable, since it can make coding simpler while producing smaller and faster applications. But what ever the reasons for sticking with BASIC and even the style of coding each BASIC programmer uses, BASIC is a language that just won’t go away.

USB Reset Attribute

Gallery

 

Ray Yagubyan

Ray Yagubyan

Introduction

What do you do when your Removal Device or USB gets affected by a virus and files are hidden? Most of the Antivirus scan the device and delete the virus only. So we can’t see the files in our USB device which is hidden by the virus. So here, the “Ultimate USB Reset Attribute” comes with a powerful option.

Idea Behind the Code

I just embed my code with the existing one which is already available in here (CodeProject). So my first sincere thanks to CodeProject, without this I could not do it.

Using the Code

Using this code, the number of USB or removal devices is listed in a dropdown which is currently connected to a computer.

if(!Directory .Exists (currDir ))
            return;
            //set the progress bar max value
            pbar.Maximum += Directory.GetFileSystemEntries(currDir).Count();
            //iterate over the files
            foreach (string ff in Directory.GetFiles(currDir))
            {   //super cast to the parent class FileSystemInfo
                ResetAttribute((new FileInfo(ff)) as FileSystemInfo );
             }
          
            foreach (string dr in Directory.GetDirectories(currDir))
            {
                if (!Directory.Exists(dr))
                    return;
                //reset the directory attribute
               ResetAttribute((new DirectoryInfo(dr)) as FileSystemInfo);
                      ScanFiles(dr); //scan the directory  
//Changing the file attributes by using this code.
try
            { //bitwise operator on the file attribute
                fsi.Attributes &= ~FileAttributes.Hidden;
                fsi.Attributes &= ~FileAttributes.System;

                fsi.Attributes &= ~FileAttributes.ReadOnly;
            pbar.Value += 1;
            }
            catch (Exception ex)
            {
                return;
            } 
//Whenever the main form is loaded, it checks and gets drive details by using this code.
 var drv = from dr in DriveInfo.GetDrives()
                     where dr.IsReady == true && dr.DriveType == DriveType.Removable
                     select dr;
            foreach (DriveInfo dinfo in drv)
            {
                cmbUSB.Items.Add(dinfo.Name);
                cmbUSB.SelectedIndex = 0;
              } 
 
  DriveInfo dr = new DriveInfo(cmbUSB.SelectedItem.ToString());
    lblusb.Text = dr.VolumeLabel + " (" + dr.Name + ")";

Command Line Reseter

Just enter the Drive Letter what you want to reset. Using this code.

set /p letter=
attrib -s -h -a /s /d %letter%:\*.*

Points of Interest

Hope this version helps you. This is the general idea, which I got in my dreams!!!

Screenshots

Developer? Five Reasons to Make A Mobile App

Gallery

Ray Yagubyan

Ray Yagubyan

 

#1 – You Already know programming
Of course you know programming – you are a developer! You have already made several applications – maybe they are web apps, some server apps or desktop applications – it doesn’t really matter. The only thing that matters is that code doesn’t intimidate you and you know how to plan an application from visualising the final product to constructing the perfect code that actually works!

#2 – You have a smartphone
Unless you are unlike almost every software-person in the world you already own a smartphone. This is good – because that means you already have the hardware needed to execute the mobile app you will be writing! It doesn’t really matter what kind of smartphone you have – because chances are you have a computer that will be the perfect development platform for it. Having a smartphone you already use a ton of different apps and you already have the experience needed to judge if apps are good or bad – which leads to the next point.

#3 – You have problems
Well – not you – but you have several apps that doesn’t work. Maybe they have bugs. Maybe they are missing features. Or maybe they are just stupidly made and annoy you a lot when you are forced to use them. If this is not the case you must have some need or desire that isn’t fulfilled at the moment – now you have an excellent idea for an app! Scratch your own itch! Do your own dogfooding! And when you are done you’ll have a new useful app you made yourself!

#4 – You will gain knowledge
When you are done you will know what it takes! You will know why so many mobile apps fail to deliver and why they suddenly crash eg. – it is not that easy. A lot of engineering efforts are put into making the smartphones the easiest computers to use – ever – but the act of creating apps and the perfect user experience on such a young platform is not trivial. Random bugs, doubtful internet connectivity and different hardware features will ensure that you walk away from the experience with a newfound respect and understanding about the device in your pocket and the efforts that are put into making it and its apps working.

#5 – I could be a new career
Writing a mobile app will scratch your own itch. You will be a better developer when you are done. And maybe others can use your app too! After all – if you find it that useful why shouldn’t others?! Maybe you’ll have a new (or a few new) side projects on your hand. Maybe you will even kickstart a new career – you don’t know. Just get on with it – I bet you’ll like it!

Bonus reason #6: It beats sitting around watching yet another reality show on TV.

How to Publish your Windows Phone 8 Application on the Store

Gallery

Ray Yagubyan

Ray Yagubyan

Introduction

Almost of my friends asked me how to publish my Windows Phone 8 application on the store and this process can take time because your application must meet all the store requirements. So, in this tip, we will see together how to publish a Windows Phone 8 application step by step.

Background

Our application lets us see the latest movies with a full description. It is ready. We have to test it before starting the Publishing steps. We run the application and we see the outputs. Inside the emulator, you will see the latest movies as we see in the picture shown below:

Now, we need to start the process, let’s start with Build in “Release” Mode which is necessary to submit the application store for download. To change the build mode from “Debug” to “Release”, we should click on build menu >configuration Manager, then change the configuration like the picture shown below:

In fact, it is important to create the application Icons. If you aren’t good on using graphical editing tool, don’t worry, I advice you to use Windows Phone Icon Maker, which is freely available at http://wpiconmaker.codeplex.com.

This tool will generate automatically all required different size icons.

Once these icons are created, you have to open Project>Properties>WMAppManifest.xml where you will associate the icons and complete the application description.

After that, we have to disable the functionality of frame-rate counter, so open App.Xaml.cs and disable this line of code:

//Display the current frame rate counters
//Application.Current.Host.Settings.EnableFrameRateCounter = true; 

Added to this, we want to take at least 3 screenshots.

Now open the project menu and click on Open Store Test Kit. Associate all images and the Windows should look like:

That is great.

Now you need to enter the website which has this link: https://dev.windowsphone.com, click on Publish then submit app. The Window should look like this one:

Compete the app information. Then, you need to Upload the project package found at C:\Users\Hadrich\Documents\Visual Studio 2013\Projects\MoviesShow\MoviesShow\Bin\Release.

Finally, you need to associate all screenshots and click on submit. Well done.