Tag Archives: Windows 8.1

How to run code daily at specific time in C# Part 2


dailyruncode

Few months ago I wrote blog post about how to run code daily at specific time. I dint know that the post will be the most viewed post on my blog. Also there were several questions how to implement complete example. So today I have decided to write another post, and extend my previous post in order to answer thise question as well as to generalize this subject in to cool demo called Scheduler DEMO.

The post is presenting simple Windows Forms application which calls a method for every minute, day, week, month or year. Also demo shows how to cancel the scheduler at any time.

The picture above shows simple Windows Forms application with two  numeric control which you can set starting hour and minute for the scheduler. Next there is a button Start to activate timer for running code, as well as Cancel button to cancel the scheduler. When the time is come application writes the message on the Scheduler Log.

Implementation of the scheduler

Scheduler is started by clicking the Start button which is implemented with the following code:

/// <summary>
/// Setting up time for running the code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void startBtn_Click(object sender, EventArgs e)
{

    //retrieve hour and minute from the form
    int hour = (int)numHours.Value;
    int minutes = (int)numMins.Value;

    //create next date which we need in order to run the code
    var dateNow = DateTime.Now;
    var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, 0);

    listBox1.Items.Add("**********Scheduler has been started!*****");

    //get nex date the code need to run
    var nextDateValue=getNextDate(date,getScheduler());

    runCodeAt(nextDateValue, getScheduler());

}

When the time is defined then the runCodeAt method is called which implementation can be like the following;

/// <summary>
/// Determine the timeSpan Dalay must wait before run the code
/// </summary>
/// <param name="date"></param>
/// <param name="scheduler"></param>
private void runCodeAt(DateTime date,Scheduler scheduler )
{
    m_ctSource = new CancellationTokenSource();

    var dateNow = DateTime.Now;
    TimeSpan ts;
    if (date > dateNow)
        ts = date - dateNow;
    else
    {
        date = getNextDate(date, scheduler);
        ts = date - dateNow;
    }

    //enable the progressbar
    prepareControlForStart();

    //waits certan time and run the code, in meantime you can cancel the task at anty time
    Task.Delay(ts).ContinueWith((x) =>
        {
            //run the code at the time
                methodToCall(date);

                //setup call next day
                runCodeAt(getNextDate(date, scheduler), scheduler);

        },m_ctSource.Token);
}

The method above creates the cancelationToken needed for cancel the scheduler, calculate timeSpan – total waiting time, then when the time is come call the method methodToCall and calculate the next time for running the scheduler.

This demo also shows how to wait certain amount of time without blocking the UI thread.

The full demo code can be found on OneDrive.

Advertisements

Using TaskCompletionSource in wraping event handler


Using TaskCompletionSource you can wrap any operation in to task, so that you can do anything you can with the task object. The TaskCompletionSource class is very important and today’s post will be explain how to wrap button click event in to TaskCompletionSource. With this wrap we will see how complicated operation behind click button handler can be simplified.

The for this blog post is simple Windows Store app shown on the picture below.

screen_sample2

When the Play Slides is clicked, Image slide is started which start animation of images. XAML code behind this app is listed here:

<Page.Resources>
    <Storyboard x:Name="animImageSlideIn">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)"
                                        Storyboard.TargetName="img">
            <EasingDoubleKeyFrame KeyTime="0" Value="900"/>
            <EasingDoubleKeyFrame KeyTime="0:0:2" Value="0" />
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Height="250" >
        <Button x:Name="playbtn" Height="50" Margin="0,5,0,5" Content="Play Slides" HorizontalAlignment="Center" Click="playbtn_Click"></Button>

        <Image x:Name="img" HorizontalAlignment="Center">
            <Image.RenderTransform>
                <CompositeTransform TranslateY="900" />
            </Image.RenderTransform>
        </Image>
    </StackPanel>
</Grid>

First, it will be presented  the implementation without TaskCompletionSource. The Play Slides Click event is the following code:

private async void  playbtn_Click(object sender, RoutedEventArgs e)
{
    int i = 1;

    EventHandler<object> handler = null;

    handler = delegate
    {
        if (i <= 3)
        {
            playbtn.Content = string.Format("Slide Image {0}",i);

            LoadSourceImage(i);

            animImageSlideIn.Begin();

            i++;
        }
        else
        {
            playbtn.Content = "Play Slides";
            animImageSlideIn.Completed -= handler;
            LoadSourceImage(0);

        }
    };

    animImageSlideIn.Completed += handler;
    handler(null,null);
}

As we can see from the listing above the code is pretty much long and little bit confused because we subscribe to the handler and call it as much as we reach the magic number of slides. Whe the number of slides is reached we unsubscribed from the handler and exit  the method.

Now implement the same functionality with the TaskCompletionSource class. The following listing shows the implementation:

private async void playbtn_Click(object sender, RoutedEventArgs e)
{

for(int i=1; i<=3; i++)
{
playbtn.Content = string.Format("Slide Image {0}",i);
LoadSourceImage(i);
await animImageSlideIn.RunAsync();
}

playbtn.Content = "Play Slides";
}

As we can see the implementation is very simple and concise. in for loop we call LoadSourceImage then asynchrony run animation.

The source code of the demo can be found by clicking the image below:

This blog post is inspired by Stephen Toub //build/ session.

Pausing and cancelling async method in C#


Responsiveness of your app is not just fee UI thread by implementing async. It is more that that. When a long operation is under process in your app, user sometimes wants to cancel it  or  pause the operation. Imagine your app processing hundreds of files or images. Such a operation can take more that few seconds and user must have option to cancel it. Canceling and pausing are very important feature for every app that implements long operations.

This blog post will present the way of using CancelationToken built in cancel feature in .NET, as well as a PauseToken custom implementation which is very similar to CancelationToken.

Original implementation of PauseToken is from the pfxteam blog which you can find here.

We will implement simple Windows Store app with cancel and pausing the async operation. The picture below shows the sample app:

screen_sample1

 

As you can see when the Start Process button is clicked it begins process of processing image files. There is also ProgressRing control which shows the progress and percentage of completeness. From the right side you can see two buttons. The Cancel button cancels the operation, and pause button pauses operation until the Pause button is clicked again.

The implementation behind Process button is the folowing:

private async  void btnProcess_Click(object sender, RoutedEventArgs e)
{
    //creating cancel and pause token sources
    m_pauseTokeSource = new PauseTokenSource();
    m_cancelationTokenSource = new CancellationTokenSource();

    //get al picture from picture library
    var picturesFolder = KnownFolders.PicturesLibrary;
    var fileList = await picturesFolder.GetFilesAsync();

    //set ProgressRing to active
    ring2.IsActive = true;

    try
    {
        //asynchrony process files, by passing pasue and calcel tokens

        await ProcessImages(fileList, m_pauseTokeSource.Token, m_cancelationTokenSource.Token);
    }
    catch (Exception)
    {
        //do nothing when somthing went wrong not when taks is canceled
    }
    finally
    {
        //make inactive ProgressRing
        ring2.IsActive = false;
    }
}

Click event implementation of the Start Process button 

First we create Cancel and Pause Source tokens. Gent the picture content in form of list of files. Then we call asynchonious ProcessImages method by passing list of images files, cancel and pause tokens. Process images is called within try catch finally blocks, because every cancel task throws exception.

Implementation ProcessImages async method

ProcesImage method is async method which accept cancelation and pasue token nad returns Task object.

public async Task ProcessImages(IEnumerable<StorageFile> images, PauseToken pauseToken, CancellationToken cancelToken)
{
    double count=images.Count();
    double current=0;
    foreach (var file in images)
    {
        //if the paise is active the code will wait here but not block UI thread
        await pauseToken.WaitWhilePausedAsync();

        ring2Text.Text = string.Format("{0}%",(int)(100*current / count));

        await ProcessAsync(file, cancelToken);
        current++;
    }
    ring2Text.Text = string.Format("100%");
}

In foreach loop first we await pauseToken.WaitWhilePausedAsync(); which wait if IsPause property of the Token class is true, otherwize there is no awaiting here. The next await is out Delay which takes cancelation token as parameters. When the Pause button is clicked, pauseToken is awaiting until the pause button is clicked again. In case of cancelation when the Cancel button is clicked the Cancel() method of the cancelationTokenSource is called and exception is thorwn. Then processImages method is interupted and finally blick progressring is disabled.
Pause and Cancel Click implementation are shown in the following listing:

private void btnPause_Click(object sender, RoutedEventArgs e)
{
 m_pauseTokeSource.IsPaused = !m_pauseTokeSource.IsPaused;
}

private void btnCancel_Click(object sender, RoutedEventArgs e)
{
 m_cancelationTokenSource.Cancel();
}

Complete source code can be downloaded from link below.

How to run code daily at specific time in C#


Update: Please see my Updated post about this subject: How to run code daily at specific time in C# part 2

When you want to make some delay in running code you can use Task.Delay(TimeSpan interval) method . This method is similar to Thread.Sleep, but it is nicer. The argument of the method represent TimeSpan type. For example if you want to wait 5 second you can call the following code:

Task.Delay(TimeSpan.FromSeconds(5));

Or you want to wait 2 hours:

Task.Delay(TimeSpan.FromHours(2));

You can easily use Task.Delay to run some code at certain time. For example you want to run some method every day at 1:00:00 AM. To implement this example you can use Task.Delay method on the following way:
First Convert the time in to DateTime type. Make diference between now and the time you want to run the code. Call Delay method with TimeSpan of previous time interval. The following code solve this problem:

class Program
    {
        static void Main(string[] args)
        {
            //Time when method needs to be called
            var DailyTime = &quot;01:00:00&quot;;
            var timeParts = DailyTime.Split(new char[1] { ':' });

            var dateNow = DateTime.Now;
            var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
                       int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
            TimeSpan ts;
            if (date &gt; dateNow)
                ts = date - dateNow;
            else
            {
                date = date.AddDays(1);
                ts = date - dateNow;
            }

            //waits certan time and run the code
            Task.Delay(ts).ContinueWith((x)=&quot; SomeMethod()&quot;);

            Console.Read();
        }

        static void SomeMethod()
        {
            Console.WriteLine(&amp;amp;amp;amp;quot;Method is called.&amp;amp;amp;amp;quot;);
        }
    }

If you want that code to run every day, just put it in while loop.

Update: The complete sample can be similar to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DailyTaskDemo
{
class Program
{
static void Main(string[] args)
{
//Time when method needs to be called
var DailyTime = “22:37:00″;
var timeParts = DailyTime.Split(new char[1] { ‘:’ });

while(true)
{

var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
TimeSpan ts;
if (date &gt; dateNow)
ts = date – dateNow;
else
{
date = date.AddDays(1);
ts = date – dateNow;
}

//waits certan time and run the code
Task.Delay(ts).Wait();
SomeMethod();

}

Console.Read();
}

static void SomeMethod()
{
Console.WriteLine(“Method is called.”);
}
}
}

Happy programming.

How to manually fix content error in Microsoft Word


Word2013_error1

Today while I was editing a document suddenly Word crashed and the document became unable to be opened. Every time I wanted to open it the same error was:

We’re sorry. We can’t open DocumentName.docx because we found a problem with its contents.
When I want to see Details the following message shows:
Unspecified error
Location: Part: /word/document.xml, Line 2, Column: 0.

Then I wanted to open auto-saved version of the document, the same error appeared. So I changed the DocumentName.docx  file in to DocumentName.zip, and extract the content, found document.xml file and opened it in Notepad++.

The picture below shows the content of the DocumentName.docx file, renamed in to zip and extracted:

Word2013_error2

If you didn’t know the word document with doc or docx extension is actually zip file, which you can extract.

I have opened the docuemnt.xml and try to find error in second line. This was mission impossible because all xml content is placed in this line. As you can see on the picture below:

Word2013_error3

To find which element cause the content problem we have to format XML content. I prefer using Notepad++ and XML Tool PlugIn. It can be installed through Plungins menu of Notepad++.

Word2013_error4

To format xml content choose option Pretty print (XML only – with line breaks) . After the content is formatted, back the Document.xml to zip, change the extension from zip to docx, and open the word document.

The same error appear, but when you choose for details you can read in which line is the error. Find the line in Notepad++ and delete whole tag element:

Word2013_error7

Copy document.xml back in to zip file, rename the extension and try to open. If you have another error, repeat the process again, otherwise your document is opened.

Word2013_error8

How to delete VisualStudio.com project from Windows 8.1 and Visual Studio 2013


More than year ago, I wrote blog post article how to delete project from tfspreview.com. I can say this blog post is one of the most visited post, probably because lot of people wanted to delete project but it is not so obvious task.

Today I run in the similar problem with Windows 8.1 OS and Visual Studio 2013 RTM version. In fact when I open Start Screen I wasn’t unable to find icon VS2013 x64 Native Tools Command Prompt, but only command prompt for VS 2012 which is not working because you have no VS2012 installed.

Actually you have to choose Visual Studio Tools folder from Visual Studio 2013 category.

visualStudio2013Tools 

Windows Explorer Window is opened.

visualStudio2013Tools1

 

Now select VS2013 x64 Native Tools Command prompt, and follow instruction in the previous blog post from  this link.

Using Dispatcher in Windows 8.1 Store Apps


If we want to inform the user about operation status which is running in the background by callback method, you have to be aware that the callback call is not in the UI thread. In this situation we cannot show Dialog message as ordinary, because we will go in trouble with cross-thread exception.

If we want to run eg. Dialog Message in Windows Store apps to inform user about operation status we need to run a “safe code”. This means we need to call Dispatcher, which cares that all calls related to UI components have to be from the main thread.

Lets assume we have callback method which gets call when user wants to see the payment status. Process of checking payment is not in UI thread, so the callback method of reporting status will also not be in the UI thread. In that situation, any code which touches UI must be executed with Dispatcher.

The following code  shows how to create MessageDialog and show it in Windows Store app, so that the user get information about payment status.

/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PaymentCheckCompleted(object sender, PaymentEventArgs e)
{
    MessageDialog dlg = null;
    if (e == null)
    {
        dlg = new MessageDialog("Status is NULL", "SMS Provider");
    }
    else if (e.status == PaymentStatus.ok)
    {
        dlg = new MessageDialog("Status is OK", "SMS Provider");
    }
    else if (e.status == PaymentStatus.cancelled)
    {
        dlg = new MessageDialog("Status is CANCELED", "SMS Provider");
    }
    else if (e.status == PaymentStatus.failed)
    {
        dlg = new MessageDialog("Status is FAILED", "SMS Provider");
    }
    else if (e.status == PaymentStatus.pending)
    {
        dlg = new MessageDialog("Status is PENDING", "SMS Provider");
    }
    else
    {
        dlg = new MessageDialog("Status is UNKNOWN", "SMS Provider");
    }

    dlg.Commands.Add(new UICommand("OK"));
    dlg.DefaultCommandIndex = 0;
    dlg.CancelCommandIndex = 0;
    dlg.Options = MessageDialogOptions.None;

    this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => dlg.ShowAsync());

}

The last line in the example above shows how to use Dispatcher, and how to show dialog so that we never see cross-thread exception.