EWS + Async/Await

Hi!
I am currently migrating a .NET Windows Service to use the async/await pattern. The service is polling the Microsoft Exchange Server a lot via the use of Exchange
Web Services Managed API.  Since the amount of mails is increasing quickly (around 10k/day), I am ask to improve it's throughput. Making the application parallel most likely will produce some issues due to Exchange
throttling. Since the wait time is basically IO related not CPU, I thought it would be beneficial to use async/await and await the calls to Exchange.
Does someone have experience how to archive this? The EWS Managed API does not provide any async methods.
Many thanks in advance
Fabian

Many thanks for the hint!
Seems to be possible to use the API asynchronously without the usage of EWS Managed API.
Currently I am not sure, if I want to spare the EWS Managed API (complexity, updates,..).
I have to do a PoC in order to get a feeling for it.
Regarding batch updates:
My application accesses around 130 mailboxes.
For every mailbox it does the following steps:
Extract x mails from the mailbox
Export each mail to the file system including some metainformation
Move the mail to a "done" folder on the exchange server
If an error occurs, the mail must be moved to an "error" folder on the exchange server
Following the processing of each mailbox must be synchronous in itself,
but it's possible to use a thread for each mailbox (=can be parallel & asynchronous).
An simple alternative would be to just use a Task.Run... for each mailbox.

Similar Messages

  • Async / Await in Cloud Services Worker Roles?

    Good evening,
    I was wondering if and how one would be able to utilize async / await for Azure Cloud Services' Worker Roles? Basically I have background jobs that will/shall run on worker roles, however many of those are performing up/downloads from Azure Storage blobs
    and ideally I'd like to await those calls.
    So is async/await natively supported for CS Worker Roles (using Azure SDK 2.5) and if so, how? And if not.. is it planned at all?
    Thanks,
    -Jörg

    Hi,
    I would suggest you have a look at this thread:
    http://stackoverflow.com/questions/15991287/async-await-in-azure-worker-role-causing-the-role-to-recycle
    A simple solution is to just do this:
    public override void Run()
    RunAsync().Wait();
    public async Task RunAsync()
    while (true)
    await Task.Delay(60000);
    Hope this helps.
    Best Regards,
    Jambor
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Async task conversion

    I have a method which invokes a while loop with a condition defined as a specified time. The body of the loop must remain synchronous up to the very end, the last couple commands are a brutally long call into some other api. I know I can execute the body
    of the loop synchronously over and over and queue the object it produces to be consumed by a parallel foreach as one option.
    I do not want to exceed a defined threshold on the number of objects produced by the while loop, so one neat approach I saw was the second answer to http://stackoverflow.com/questions/22492383/throttling-asynchronous-tasks by
    Noseratio.
    I admit, I am new to async tasks and really not clear on the best approach to move out the small bit of code at the end of the loop into an async method. I assume I could run the loop entirely with the using context of a SemaphoreSlim and await
    _semaphore.WaitAsync(); *after* the object is submitted for asynchronous completion so as not exceed the max number of tasks.
    My confusion comes from the format of the new method containing the long waiting call I want moved out? I see so much literature on async/await/Task.FromResult etc?
    In his second code block where he speaks of TPL Dataflow or Rx, why do I mostly see the pattern of a method with an async Task signature called from a method with an async void sig? Why not dispatch an asynchronous method directly and if needed, grab the
    return if one needs to utilize the result?
    Thanks!

    Async and tasks is tricky.
    It's easy to do simple stuff.  Quite easy to mess it up though.
    When you try and do hard things then it can easily go wrong and be quite difficult to work out what's up.
    I don't like the sound of putting ( what sounds like ) a very long call into a task this way.
    If it's a very long call I would prefer async and callback to tasks.
    I'd consider decoupling and putting it in a wcf or windows service.
    If there are a load of these potentially then I might even decouple further by message queue so the "main" app and this processing can carry on at different speeds.
    If there's a bunch of processing then windows workflow might be useful.
    If there's a shed load of processing then putting it on a different machine and maybe even appfabric is something to consider.
    That's probably well over the top though.
    Hope that helps.
    Recent Technet articles: Property List Editing;
    Dynamic XAML

  • Async Task with WhenAll() performance is off.

    Can anyone explain to me why my TIMINGS for test #2 operation is so SCREWED up
    370ms
    310ms  <---  this one should not be this slow.
    143ms
    119ms
    I have two methods...BOTH write the exact same byte array to a specified filename....(I've tried 5M & 10M file)
    One is synchronous and uses stream.write()
    using (FileStream strm = new FileStream(path, FileMode.Create, FileAccess.Write,
    FileShare.None, 4096, useAsync: false))
    strm.Write(text, 0, text.Length);
    ...the other is async and uses await stream.WriteAsync
    public static async Task WriteBigFileAsync(string path,
    byte[] text)
    using (FileStream strm = new FileStream(path, FileMode.Create, FileAccess.Write,
    FileShare.None, 4096, useAsync: true))
    await strm.WriteAsync(text, 0, text.Length);
    4 different test methods:
    1 calls Synch method x times. (set at 25 right now)
    for (int i = 0; i < numTimes; i++)
    WriteBigFile(Path.Combine(dir,
    Path.GetRandomFileName()), text);
    Next calls Asynch x times....firing all of them concurrently (if poss)...and then waiting until all are complete
    var tasks = new List<Task>();
    for (int i = 0; i < numtimes; i++)
    Task t = WriteBigFileAsync(Path.Combine(dir, Path.GetRandomFileName()), text);
    tasks.Add(t);
    await Task.WhenAll(tasks.ToArray());
    3rd uses PLINQ to throw them out to the thread pool, but calls Synchronous method
    Parallel.For(0, numTimes, (x) => WriteBigFile(Path.Combine(dir, Path.GetRandomFileName()), text));
    4rd is the same but calls Asynchronous method.
    Parallel.For(0, numTimes, async (x) => await WriteBigFile(Path.Combine(dir, Path.GetRandomFileName()), text));
    I KNOW that the best practice method for I/O intensive operations is to use async await.
    I KNOW that Parallel.For has the potential to gain great performance, but at the expense of a bunch of new threads which will just end up SITTING there while the file writes anyway.
    But WHY is the performance for the Asynchronous call so poor?
    And ideas would be appreciated.

    >I KNOW that the best practice method for I/O intensive operations is to use async await.
    But you need to understand _why_ it's a best practice.  Writing to a file using asynchronous IO is no faster than writing with synchronous IO.  The only difference is whether your thread blocks while waiting on the IO to complete.  Not blocking
    threads can help make your middle tier application scale better, and it can help keep a UI responsive.  But it doesn't make the IO any faster.
    All these methods are going to be gated by the throughput of your storage device, not your choice of API.
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Test Stand async Task bool

    I'm trying to learn more about NI Test Stand and calling a .NET Method in a test sequence.  I reviewed and understand the basic examples where you can call something like below...
    public bool DoSomething(out string result, out string error) { //...}
    I have a third-party libary and it includes some async Methods that must be called using the async/await feature that was introduced in .NET 4.5.  When using async, you can not use the out keyword in arguments, so I would have to modify the Method above to something like this...
    public Task<Tuple<bool, string, string>> DoSomething() { /.. }
    So my question is... does anyone know how to call into a .NET library with Test Stand and get the values that are returned via the async Task?  Any basic examples are appreciated.
    BTW, it does not have to be complex like above.  If you can explain something like Task<bool>, it would help, as well.
    Thanks.

    I haven't tried this specific case and am not familiar with the Task API, but you should be able to store the return value of that method in a TestStand Object Reference variable. Then, in a later step, select the class Task<Tuple<bool, string, string>> from your assembly and use the reference you got from the previous call as the class object and then just access the various methods and properties of that class.
    Hope this helps,
    -Doug

  • GetBlobReferenceFromServerAsync (and non-async) throw an exception with 404 (not found) if the blob doesn't exist.

    I'm trying to determine if a particular file exists in a blob store. I'm using container.GetBlobReferenceFromServerAsync and if the named blob does't exist I get an exception with a 404. ICloudBlob (which is returned by the method) defines an Exists method
    but it's functionally useless because the GetBlobReferenceFromServerAsync method call itself throws the exception. I do get the behavior I'm looking for if I call container.GetBlockBlobReference instead but there's no async version of that method.

    As I said I'd found that GetBlockBlobReference works but there's no async version of that method. I'm trying to determine IF a blob exists not create one. Since the GetBlobReferenceFromServer returns an ICloudBlob and ICloudBlob defines and Exists method
    you'd assume that it could be used to determine if a blob exists. I'd argue that the fact that it throws and exception when the blob does not exist is a bug in the implementation because it makes the Exist method on the ICloudBlob object functionally useless.
    Also, it seems like a fairly significant miss that there's no async version of GetBlockBlobReference. A query to a cloud resource is exactly the perfect use case for the async/await pattern.
    Does anyone know of an async way to check for the existence of a blob that doesn't involve catching a 404 exception?

  • App resume fail with MediaCapture WP8.1

    Hi everyone,
    Which is the good place to initialize MediaCapture? I used Panorama theme to create a TorchControl and on itemPanorama_Loaded I set:
    MediaCapture mc = new MediaCapture();
    await mc.InitializeAsync();
    mc.Failed += new MediaCaptureFailedEventHandler(Failed)
    When App start, nothing happen but if I use other apps and resume, it keep loading, then MediaCaptureFailedEventHandler throw error out about access cross-thread.
    If I tried to move code to button event then it fail to create MediaCapture on 2nd tap
    Any suggestion? Thank you

    Another finding : Keeping this MediaCapture initializing code inside the page event handlers might be an issue.I removed the async & await from Loaded / OnNavigatedTo event & the app resumed immediately but if the async await code is executed on
    these handlers then the app remains on that 'resuming' window for an infinite time.
    Suggestion : you can probably move the initializing code when user tries to capture the the picture and keep only one instance of it throughout and then check subsequently on each button click if its null, if it is then only create a new object otherwise
    not. You can declare a variable MediaCapture _mc at the top of page for this, to have its visibility throughout the page.
    http://developer.nokia.com/community/wiki/Using_Crypto%2B%2B_library_with_Windows_Phone_8
    Again, I actually did it the same as your suggestion before also. App resume normally but if the button event is raised (MediaCapture is created) then app can not be resumed

  • Error while creating DiscoveryClient object

    Hi,
    i have an issue creating DiscoveryClient object. I tried to solve this by granting all permissions and THEN generating the secret but i still the same Exception.
    public string discoveryId = "https://api.office.com/discovery/";
    public string cmmAth = "https://login.windows.net/Common";
    public async Task<OutlookServicesClient> EnsureClientCreatedAsync()
    try
    string authority = cmmAth;
    _authenticationContext = new AuthenticationContext(authority);
    DiscoveryClient discoCli = new DiscoveryClient(async () => await GetTokenHelperAsync(_authenticationContext, discoveryId));
    CapabilityDiscoveryResult discoResult = await discoCli.DiscoverCapabilityAsync("Calendar");
    var outlookCli = new OutlookServicesClient(discoResult.ServiceEndpointUri, async () => await GetTokenHelperAsync(_authenticationContext, discoResult.ServiceResourceId));
    return outlookCli;
    catch (AdalException e)
    MessageBox.Show(e.ToString());
    if(_authenticationContext != null && _authenticationContext.TokenCache != null){
    _authenticationContext.TokenCache.Clear();
    return null;
    public async Task<string> GetTokenHelperAsync(AuthenticationContext context, string resourceId)
    string accessToken = null;
    AuthenticationResult result = null;
    ClientCredential cliCred = new ClientCredential("xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx", "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy=");
    result = await context.AcquireTokenAsync(resourceId, cliCred);
    accessToken = result.AccessToken;
    return accessToken;
    and my AdalException is
    AADSTS70001: Application with identifier xxxxx-xxxx-xxxx-xxx-xxxxx was not found in the directory api.office.com
    thx for any Help
    Maciej 

    Hi,
    What the application type did you develop with: Web Application or Windows Client Application?
    To use Office 365 API in ASP.NET Web Application, I suggest you referencing the sample project
    O365-ASPNETMVC-Start.
    internal static async Task<OutlookServicesClient> EnsureOutlookServicesClientCreatedAsync(string capabilityName)
    var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));
    try
    DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
    async () =>
    var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId,
    new ClientCredential(SettingsHelper.ClientId,
    SettingsHelper.AppKey),
    new UserIdentifier(userObjectId,
    UserIdentifierType.UniqueId));
    return authResult.AccessToken;
    var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);
    return new OutlookServicesClient(dcr.ServiceEndpointUri,
    async () =>
    var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
    new ClientCredential(SettingsHelper.ClientId,
    SettingsHelper.AppKey),
    new UserIdentifier(userObjectId,
    UserIdentifierType.UniqueId));
    return authResult.AccessToken;
    catch (AdalException exception)
    //Handle token acquisition failure
    if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
    authContext.TokenCache.Clear();
    throw exception;
    return null;
    For Windows client application, you could get the token by using the code as following:
    private async void GetToken()
    string authority = "https://login.windows.net/Common";
    AuthenticationContext authenticationContext = new AuthenticationContext(authority);
    string discoveryResourceId = "https://api.office.com/discovery/";
    String clientId = "{Client ID}";
    Uri redirectUri = new Uri("http://localhost/{return GUID}");
    var token = authenticationContext.AcquireToken(discoveryResourceId, clientId, redirectUri);
    Regards,
    Jeffrey
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to use the code written in App.Xaml.cs in Windows Phone 8 in Windows Phone 8.1 Universal Apps

    i have a App.xaml.cs file in Windows Phone 8.0 , amd i want to use the code in that file to make work with App.xaml.cs file in Windows Phone 8.1 Universal Apps
    My Windows Phone 8 App.xaml.cs file is like as below
    namespace OnlineVideos
    public partial class App : Application
    #region Initialization
    public static dynamic group = default(dynamic);
    public static dynamic grouptelugu = default(dynamic);
    public static ShowList webinfo = default(ShowList);
    public static WebInformation webinfotable = new WebInformation();
    AppInitialize objCustomSetting;
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    DispatcherTimer timer;
    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
    public static bool AdStatus = false;
    public App()
    UnhandledException += Application_UnhandledException;
    if (System.Diagnostics.Debugger.IsAttached)
    Application.Current.Host.Settings.EnableFrameRateCounter = true;
    //RootFrame.UriMapper = Resources["UriMapper"] as UriMapper;
    AppSettings.NavigationID = false;
    objCustomSetting = new AppInitialize();
    timer = new DispatcherTimer();
    Constants.DownloadTimer = timer;
    InitializeComponent();
    InitializePhoneApplication();
    #endregion
    #region "Private Methods"
    void StartDownloadingShows()
    timer.Interval = TimeSpan.FromSeconds(10);
    timer.Tick += new EventHandler(timer_Tick);
    timer.Start();
    void timer_Tick(object sender, EventArgs e)
    try
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(StartBackgroundDownload);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.RunWorkerAsync();
    catch (Exception)
    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    if (AppSettings.StopTimer == "True")
    timer.Stop();
    AppSettings.StopTimer = "False";
    async void StartBackgroundDownload(object sender, DoWorkEventArgs e)
    switch (AppSettings.BackgroundAgentStatus)
    case SyncAgentStatus.DownloadFavourites:
    if (AppSettings.DownloadFavCompleted == false && AppSettings.SkyDriveLogin == true)
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    timer.Stop();
    ReStoreFavourites reStoreFav = new ReStoreFavourites();
    await reStoreFav.RestorefavFolder(ResourceHelper.ProjectName);
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadFavourites;
    timer.Start();
    else
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadFavourites;
    break;
    case SyncAgentStatus.UploadFavourites:
    bool result = Task.Run(async () => await Storage.FavouriteFileExists("Favourites.xml")).Result;
    if (AppSettings.SkyDriveLogin == true && result)
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    timer.Stop();
    UploadFavourites upLoad = new UploadFavourites();
    await upLoad.CreateFolderForFav(ResourceHelper.ProjectName);
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
    timer.Start();
    else
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
    break;
    case SyncAgentStatus.RestoreStory:
    if (AppSettings.DownloadStoryCompleted == false && AppSettings.SkyDriveLogin == true && (ResourceHelper.ProjectName == "Story Time" || ResourceHelper.ProjectName == "Vedic Library"))
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    timer.Stop();
    RestoreStory restore = new RestoreStory();
    //if (ResourceHelper.ProjectName == "Story Time")
    await restore.RestoreFolder("StoryRecordings");
    //else
    // await restore.RestoreFolder("VedicRecordings");
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadStory;
    timer.Start();
    else
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadStory;
    break;
    case SyncAgentStatus.UploadStory:
    if (AppSettings.SkyDriveLogin == true && (ResourceHelper.ProjectName == "Story Time" || ResourceHelper.ProjectName == "Vedic Library"))
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    timer.Stop();
    UploadStory st = new UploadStory();
    //if (ResourceHelper.ProjectName == "Story Time")
    await st.CreateFolder("StoryRecordings");
    //else
    // await st.CreateFolder("VedicRecordings");
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadFavourites;
    timer.Start();
    else
    AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadFavourites;
    break;
    default:
    ShowDownloader.StartBackgroundDownload(timer);
    break;
    #endregion
    #region "Application Events"
    private void pop_Opened_1(object sender, EventArgs e)
    DispatcherTimer timer1 = new DispatcherTimer();
    timer1.Interval = TimeSpan.FromSeconds(5);
    timer1.Tick += timer1_Tick;
    timer1.Start();
    void timer1_Tick(object sender, EventArgs e)
    (sender as DispatcherTimer).Stop();
    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
    Popup Adc = frameBorder.FindName("pop") as Popup;
    Adc.IsOpen = false;
    private void Application_Launching(object sender, LaunchingEventArgs e)
    SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(Constants.DataBaseConnectionstringForSqlite);
    Constants.connection = conn;
    AppSettings.AppStatus = ApplicationStatus.Launching;
    AppSettings.StopTimer = "False";
    objCustomSetting.CheckElementSection();
    SyncButton.Login();
    if (AppSettings.IsNewVersion == true)
    AppSettings.RatingUserName = AppResources.RatingUserName;
    AppSettings.RatingPassword = AppResources.RatingPassword;
    AppSettings.ShowsRatingBlogUrl = AppResources.ShowsRatingBlogUrl;
    if (ResourceHelper.AppName == Apps.Online_Education.ToString() || ResourceHelper.AppName == Apps.DrivingTest.ToString())
    AppSettings.QuizRatingBlogUrl = AppResources.QuizRatingBlogUrl;
    AppSettings.LinksRatingBlogUrl = AppResources.LinksRatingBlogUrl;
    AppSettings.ShowsRatingBlogName = AppResources.ShowsRatingBlogName;
    AppSettings.LinksRatingBlogName = AppResources.LinksRatingBlogName;
    if (ResourceHelper.AppName == Apps.Online_Education.ToString() || ResourceHelper.AppName == Apps.DrivingTest.ToString())
    AppSettings.QuizLinksRatingBlogName = AppResources.QuizLinksRatingBlogName;
    Constants.UIThread = true;
    group=OnlineShow.GetTopRatedShows().Items;
    grouptelugu = OnlineShow.GetRecentlyAddedShows().Items;
    Constants.UIThread = false;
    StartDownloadingShows();
    private void Application_Activated(object sender, ActivatedEventArgs e)
    AppSettings.AppStatus = ApplicationStatus.Active;
    if (ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString())
    AppSettings.ShowAdControl = false;
    private void Application_Deactivated(object sender, DeactivatedEventArgs e)
    AppSettings.AppStatus = ApplicationStatus.Deactive;
    AppState.RingtoneStatus = "TombStoned";
    private void Application_Closing(object sender, ClosingEventArgs e)
    AppSettings.AppStatus = ApplicationStatus.Closing;
    private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    FlurryWP8SDK.Api.LogError("Error at Application_UnhandledException in App.xaml.cs", e.ExceptionObject.InnerException);
    if (System.Diagnostics.Debugger.IsAttached)
    System.Diagnostics.Debugger.Break();
    else
    Exceptions.SaveOrSendExceptions("Exception in Application_UnhandledException Method In App.xaml.cs file.", e.ExceptionObject);
    e.Handled = true;
    return;
    #endregion
    #region Phone application initialization
    public PhoneApplicationFrame RootFrame { get; private set; }
    // Avoid double-initialization
    private bool phoneApplicationInitialized = false;
    // Do not add any additional code to this method
    private void InitializePhoneApplication()
    if (phoneApplicationInitialized)
    return;
    // Create the frame but don't set it as RootVisual yet; this allows the splash
    // screen to remain active until the application is ready to render.
    RootFrame = new PhoneApplicationFrame();
    if (App.Current.Resources["AdVisible"] as string == "True")
    RootFrame.Style = App.Current.Resources["RootFrameStyle"] as Style;
    RootFrame.ApplyTemplate();
    RootFrame.Navigated += CompleteInitializePhoneApplication;
    // Handle navigation failures
    RootFrame.NavigationFailed += RootFrame_NavigationFailed;
    // Ensure we don't initialize again
    phoneApplicationInitialized = true;
    //NonLinearNavigationService.Instance.Initialize(RootFrame);
    private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
    if (System.Diagnostics.Debugger.IsAttached)
    System.Diagnostics.Debugger.Break();
    else
    Exceptions.SaveOrSendExceptions("Exception in RootFrame_NavigationFailed Method In App.xaml.cs file.", e.Exception);
    e.Handled = true;
    return;
    // Do not add any additional code to this method
    private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
    // Set the root visual to allow the application to render
    if (RootVisual != RootFrame)
    RootVisual = RootFrame;
    // Remove this handler since it is no longer needed
    RootFrame.Navigated -= CompleteInitializePhoneApplication;
    #endregion
    Mohan Rajesh Komatlapalli

    Basically you are asking as how to port silverlight to Xaml (RT). Go one by one converting each API from silverlight to XAML, like IsolatedStorage isn't there in RT, so look for its alternative etc.
    See here the namespace/class mappings : Windows Phone Silverlight to Windows Runtime namespace and class mappings
    http://developer.nokia.com/community/wiki/Using_Crypto%2B%2B_library_with_Windows_Phone_8

  • Background worker doesn't refresh datagrid

    I have a simple datagrid and a progressbar as user controls and what I am trying to achive is to load my Customer object and show the progress with a progressbar. Progressbar works and displays remaning percentage but Datagrid isnt refresing everytime a
    customer binded in the loop. It doesnt have to reload eveytime even it would be sufficient to display all results at the end but also doesnt work. here is my xaml and viewmodel class. I use MVVM patern.
    Please advise what I do wrong.
    <Window x:Class="Main"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
    xmlns:local="clr-namespace:local"
    Title="startForum" MinHeight="700" MinWidth="1000"
    WindowStartupLocation="CenterScreen">
    <Grid>
    <StackPanel>
    <local:ucProgressBar/>
    <local:ucCustomers/>
    </StackPanel>
    </Grid>
    </Window>
    <UserControl x:Class="ucCustomers"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
    <DataGrid x:Name="grdData" Height="200" ItemsSource="{Binding Path=CustomerModels}"/>
    </Grid>
    </UserControl>
    <UserControl x:Class="ucProgressBar"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" >
    <StackPanel>
    <Button Command="{Binding LoadCommand}">Test</Button>
    <ProgressBar Value="{Binding CurrentProgress,UpdateSourceTrigger=PropertyChanged}" Height="20" Width="200"
    Visibility="{Binding ProgressVisibility}"></ProgressBar>
    </StackPanel>
    </UserControl>
    Namespace ViewModels
    Public Class CustomerModelsVM
    Implements INotifyPropertyChanged
    Implements ICustomerModelsVM
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    Private ReadOnly worker As BackgroundWorker
    Private m_currentProgress As Integer
    Private myLoadCommand As ICommand
    Private Sub OnPropertyChanged(Optional ByVal propertyName As String = Nothing)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub
    Public Sub New()
    Me.worker = New BackgroundWorker()
    worker.WorkerReportsProgress = True
    AddHandler Me.worker.DoWork, AddressOf Me.DoWork
    AddHandler Me.worker.ProgressChanged, AddressOf Me.ProgressChanged
    AddHandler Me.worker.RunWorkerCompleted, AddressOf Me.BackgroundWorker_RunWorkerCompleted
    myLoadCommand = New DelegateCommand(AddressOf LoadClick)
    End Sub
    Private Sub LoadClick()
    Me.worker.RunWorkerAsync()
    End Sub
    Public Sub ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
    Me.m_currentProgress = e.ProgressPercentage
    OnPropertyChanged("CurrentProgress")
    End Sub
    Private Function Progressisbusy() As Boolean
    Return Not Me.worker.IsBusy
    End Function
    Private Sub BackgroundWorker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
    End Sub
    Private _CustomerModels As ObservableCollection(Of Models.CustomerModel)
    Public Property CustomerModels() As ObservableCollection(Of Models.CustomerModel)
    Get
    Return _CustomerModels
    End Get
    Private Set(value As ObservableCollection(Of Models.CustomerModel))
    _CustomerModels = value
    OnPropertyChanged("CustomerModels")
    End Set
    End Property
    Public ReadOnly Property btnClick() As ICommand
    Get
    Return myLoadCommand
    End Get
    End Property
    Public Property CurrentProgress() As Integer
    Get
    Return Me.m_currentProgress
    End Get
    Private Set(value As Integer)
    Me.m_currentProgress = value
    End Set
    End Property
    Public Property LoadCommand() As ICommand
    Get
    Return myLoadCommand
    End Get
    Set(ByVal value As ICommand)
    myLoadCommand = value
    End Set
    End Property
    Private Function CalculateProgress(total As Integer, complete As Integer) As Integer
    ' avoid divide by zero error
    If total = 0 Then
    Return 0
    End If
    ' calculate percentage complete
    Dim result = CDbl(complete) / CDbl(total)
    Dim percentage = result * 100.0
    ' make sure result is within bounds and return as integer;
    Return Math.Max(0, Math.Min(100, CInt(Math.Truncate(percentage))))
    End Function
    Private Sub DoWork(sender As Object, e As DoWorkEventArgs)
    Dim myCustomers = getCustomers().ToList
    Dim myCustomerUrl As String = ""
    Dim myCounter As Integer = 0
    _CustomerModels = New ObservableCollection(Of Models.CustomerModel)
    For Each myCustomer In myCustomers
    Dim CustomerModel As New CustomerModel With {
    .customerName = myCustomer.name, _
    .customersurname = myCustomer.surname _
    Application.Current.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Background, Sub()
    _CustomerModels.Add(CustomerModel)
    end Sub
    worker.ReportProgress(CalculateProgress(myCustomers.Count, myCustomers.IndexOf(myCustomer)))
    Next
    End Sub
    End Class
    End Namespace
    "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

    Sorry, I can't really work on a random project on this particular machine.
    Check your datacontext if nothing binds.
    Is  there any binding error in your output window?
    Here's a piece of c# code.
    protected async override void GetData()
    ThrobberVisible = Visibility.Visible;
    ObservableCollection<CustomerVM> _customers = new ObservableCollection<CustomerVM>();
    var customers = await (from c in db.Customers
    orderby c.CustomerName
    select c).ToListAsync();
    // await Task.Delay(9000);
    foreach (Customer cust in customers)
    _customers.Add(new CustomerVM { IsNew = false, TheCustomer = cust });
    Customers = _customers;
    RaisePropertyChanged("Customers");
    ThrobberVisible = Visibility.Collapsed;
    That uses async await for an asynchronous read via entity framework.
    That ToListAsync is key.
    A list of entities is returned to the UI thread and processing will continue when it is returned.
    This means your UI is fine whilst it's heading off to the database across any network and reading data.
    This is the slow bit.
    Once you get the data back then manipulating a few hundred records is so quick it's not noticeable to the user.
    I iterate the list of entities, and wrap them in a viewmodel each, adding  them to an observablecollection.
    I then set the public observablecollection to that and raise property changed.
    It's this last bit which gets the view to re read the collection and it gets shown then.
    Couple of points.
    I show a spinner rather than a progress bar.
    The reason being that the read is the slow bit and processing records is so fast that worrying about each record is irrelevent.  So  linear progressbar would sit there until you get the data back then bam! it's 100%.
    Manipulating the records is very fast partly because I only ever show a maximum of 300 or so at a time.
    Users can't cope with 1000 rows let alone 10,000 rows.  If you have a lot of data you want to show then give them a way of picking a subset to see in the datagrid rather than giving them so much data they have to scroll and scroll and scroll.
    You can see that code in action:
    http://social.technet.microsoft.com/wiki/contents/articles/28209.wpf-entity-framework-mvvm-walk-through-1.aspx
    If you don't mind reading c# then I have a number of articles and samples you might find interesting.
    search on andy25 technet wiki.
    Please don't forget to upvote posts which you like and mark those which answer your question.
    My latest Technet article - Dynamic XAML

  • C#: when adding listview items the screen flashes and only single listview column loads?

    When adding listview items, the listview1 items flash and only the first listview column loads (there are 5 columns in all)?
    Background...
    I was having cross-threading issues on 3 form components which I was able to resolve (see
    code here). Now I think the soluiton which involves creating a delegate and performing an "InvokeRequired" check (see
    what I used), I'm having an issue passing 5 values for each column. Below is the code involved calling this invoking check for each and their methods.
    Before having the cross-thread issue the "listview1.Items.Add(values.text) add the comma separated string values to the appropriate columns, but that doesn't happen through the cross-thread fix required.
    The "Loading()" method is handled through and async/await method causing the initial cross-thread issue.
    private void Loading()
    int t = 1;
    foreach (string line in scripts)
    string[] listValues = line.Split(',');
    ListViewItem values = new ListViewItem(listValues);
    if (t == 1)
    AddColumn("Script Name", 200); // Creates column headings
    AddColumn("Date and Time", 150);
    AddColumn("SID", 75);
    AddColumn("Environment", 75);
    AddColumn("Client", 75);
    t++;
    else
    if ((values.Text != "") && (values.Text != "Script Name"))
    //listView1.Items.Add(values);
    AddItem(values.Text);
    if (!dictScript.Contains(values.Text))
    dictScript.Add(values.Text);
    //cbxScriptList.Items.Add(values.Text);
    AddScript(values.Text);
    private void AddItem(object o)
    if (this.listView1.InvokeRequired)
    AddItemCallback d = new AddItemCallback(AddItem);
    this.Invoke(d, new object[] { o });
    else
    { // code that adds item to listView (in this case $o)
    listView1.Items.Add(o.ToString());
    private void AddScript(object o)
    if (this.listView1.InvokeRequired)
    AddCBXCallback d = new AddCBXCallback(AddScript);
    this.Invoke(d, new object[] { o });
    else
    { // code that adds item to listView (in this case $o)
    cbxScriptList.Items.Add(o.ToString());
    private void AddColumn(object o1, object o2)
    if (this.listView1.InvokeRequired)
    AddColCallback d = new AddColCallback(AddColumn);
    this.Invoke(d, new object[] { o1, o2 });
    else
    { // code that adds item to listView (in this case $o)
    listView1.Columns.Add(o1.ToString(), (int)o2); // Creates column headings
    SV

    Ok, I still have the flickering issue, I could use some guidance on that. And I should note that before I had the code-threading issue, I never had any flickering, it all appeared simultaneously.
    However, I was able to populate all columns (5 in all).  I had two corrections to make.
    1) My method should not have been passing the parameter as text but as the object ListViewItem:
    // Not This...
    AddItem(values.text)
    // This is Correct...
    AddItem(values)
    2) Then I needed to cast my object as a ListViewItem in my method call:
    private void AddItem(object o)
    if (this.listView.InvokeRequired)
    AddItemCallback d = new AddItemCallback(AddItem);
    this.Invoke(d, new object[] { (ListViewItem)o });
    else { // code that adds item to listView (in this case $o)
    listView1.Items.Add((ListViewItem)o);
    SV

  • Black window remains open even after closing the window programatically

    I have an application which has multiple windows. From mainwindow button click event I am closing the child form of the application. The child window is opened after a successful socket, serial or gateway connection attempt, after which the application
    do work with some threads and while clicking on a button on mainwindow I am closing this child window after disconnecting the respective connection mode. But after the close event the child window background gets black and it remains open unless and until
    I just do a minimize and maximize the application. Please help me on this to get this issue fixed.

    Well the details are rather going to depend on what it's doing.
    It's a very open ended question really.
    But...
    Your options include.
    Background worker.
    https://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
    DIspatcherTimer
    https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.110).aspx
    Async Await
    https://msdn.microsoft.com/en-us/library/hh191443.aspx
    Tasks
    Task.Factory.StartNew(() => { Dosomething(); });
    Or just a plain thread
    using System.Threading;
    new Thread(() =>
    Thread.CurrentThread.IsBackground = true;
    // DoSomething();
    }).Start();
    Where DoSomething is a method.
    You can also have inline code of course instead of a method.
    Whilst on a different thread to the UI you can't update UI objects.
    You'll get a thread affinity error message if you try.
    That means you either return your results to the ui thread and process them there ( particularly convenient with async await ).
    Or you update something which doesn't have thread affinity.
    An observablecollection bound to an itemssource doesn't have thread affinity eg.
    You do need to raise property changed at the end of your processing with that option because it notifies collectionchanged on the wrong thread and the UI won't know it changed.
    Or you can dispathcher.begininvoke to get back to the UI thread.
    All depends what you're doing but hopefully one of those options there will suit you.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • Alternative to Thread.Sleep in catch?

    Is there any other way to make the code wait than using Thread.Sleep in catch, because Thread.Sleep disturbs other objects on my form. Here is what I'm trying to do:
    Try{
    //do something
    catch
    // wait 10 seconds
    //retry

    Timers are a bit of a nuisance what with keeping your form in memory even when you try and dispose the things.
    You could push the thing you're doing onto another thread.
    Use async await.
    You could then use Task.Delay.
    A very simplified example:
    private async void Button_Click1(object sender, RoutedEventArgs e)
    await Task.Delay(2000);
    // Do something
    Because that's an async method processing returns to the caller when it hits the await.
    That then pauses 2 seconds without impinging on your UI thread.
    Before the separate thread continues with the code after your await.
    You could put your try catch into a method like that and it'd do what you want without a timer.
    10 seconds seems a bit of a short time by the way.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • Parallel function call and thread issue

    Sorry to post one issue here which is related to code. i was debugging a code which was wrote long time back by one developer. the issue is two function is called parallel using thread and one function set a variable true at end and another function just
    looping until the variable is set to true. the variable value is not getting set to true. here i am posting a code snippet and just tell me what is mistake in the code for which variable is not getting set to true by first function.
    when user click button then two function is invoked
    private void UPDATE_Click(object sender, System.EventArgs e)
    SavedFirst();
    AddCheckThread();
    public void SavedFirst()
    IsOpen = true;
    System.Threading.Thread loadT = new System.Threading.Thread(new System.Threading.ThreadStart(SaveAll));
    loadT.Start();
    IsOpen = false;
    private void AddCheckThread()
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(addCheck));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    private void SaveAll()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(AddProducts));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    return;
    private void AddProducts()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into the Database?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    if (comboOUR.SelectedItem == null || comboCountry.SelectedItem == null || comboSelleble.SelectedItem == null || txtOereff.Text == "" || txtUKPrice.Text == "" || txtUSPrice.Text == "" || txtSUrCharge.Text == "" || txtOURUS.Text == "" || txtOURUK.Text == "")
    FormValidation();
    else
    Gather_Data();
    bool isInserted = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into \"Detailed-Product\" Too?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    isInserted = bbaProduct.BBASaveProduct();
    if (isInserted == true)
    isInserted = false;
    isInserted = bbaProduct.InsertInProductTable(BBAProduct.DetailProductID);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Product Successfully Added ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    isInserted = bbaProduct.InsertInProductTable(0);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Successfully Inserted Into the database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Process Cancelled By The User", "Add");
    ALLFlag = true;
    return;
    #region Add Check
    private void addCheck()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    this.Opacity = 0.8;
    axShockwaveFlash1.Visible = true;
    axShockwaveFlash1.Play();
    while (!ALLFlag)
    int x = 0;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.StopPlay();
    this.Opacity = 1;
    ALLFlag = false;
    loadingThread.Abort();
    return;
    help me to locate where is the mistake for which ALLFlag value is not getting set to true. thanks

    Your reliance on a field value across threads isn't going to work reliably.  In a multi-core/multi-threaded world the memory model allows for reading data out of order for optimization reasons.  Additionally the CPU can and will cache recently
    used data in memory that isn't shared across processors.  This can get you into trouble as you will not be reading the same value across processors.
    The only correct way to ensure that multiple threads access the same data correctly is to use sync objects that are designed for that such as a Semaphore or Mutex.  Sync objects allow you to safely share data across threads.
    Overall your code appears to be trying to update the UI using a thread but since it is calling Invoke each time you are basically spawning a thread that then blocks waiting for the UI thread.  You could pretty much eliminate your issues by getting rid
    of the threading calls altogether along with any sort of state management variables that were arbitrarily created (ALLflags) and simply use BeginInvoke.  You didn't post who was calling your higher level save methods but if it is a UI element then BeginInvoke
    and InvokeRequired are completely redundant as is all the threading.
    You can cleanly update this code to eliminate all the extra variables and threading and simply use the newer async/await functionality to help resolve the issues your code is having.  But you still have problems with the invoked code.  In one of
    the methods you are looping while waiting for a variable to be set.  But since you invoked it then it is occurring on the UI thread.  Because it is on the UI thread and that can only do 1 thing at a time, if ALLflag is false your code will deadlock. 
    The only other code that would set it to true cannot run because it is also invoked on the UI thread and only one of them can run at any one time.  Basically each of your threads are going to try to run on the same thread and only 1 of them will be able
    to.  Until the first thread method finishes the second one will never run.
    If you need Boolean flags then consider using a ManualResetEvent instead.  It is thread safe, works across threads and doesn't have any of the problems of a Boolean field when talking about threading. But you still have a deadlock between your invoked
    code that nothing will solve except rewriting your code.
    Michael Taylor
    http://blogs.msmvps.com/p3net

  • Crash when user attempts to purchase in-app product

    hi all,
    I didn't use to get any crash reports before introducing in-app purchase. I have approx. 30 downloads a day and 5 crashes a day now which doesn't sound right.
    Please could you help me find out why this is?
    Here is the crash info. It seems like something goes wrong when the user presses the 'Buy Product button' and it looks like it's got something to do with the async/awaiting business. I'm very new to this and don't really understand.
    Frame Image Function Offset
    0 mscorlib.ni.dll System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess 0x0023a00e
    1 mscorlib.ni.dll System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification 0x0000003a
    2 mscorlib.ni.dll System.Runtime.CompilerServices.TaskAwaiter_1[[System.__Canon,_mscorlib]].GetResult 0x0000001c
    3 BACanglais.ni.DLL BACanglais.WhatsIncluded+_Button_Click_d__2.MoveNext 0x000000b8
    4 mscorlib.ni.dll System.Runtime.CompilerServices.AsyncMethodBuilderCore._ThrowAsync_b__0 0x00000036
    my code behind the "Buy Product button" is as follows:
    async private void Button_Click(object sender, RoutedEventArgs e)
    // go to the buy product page
    var listing = await CurrentApp.LoadListingInformationAsync();
    var product1 =
    listing.ProductListings.FirstOrDefault(p => p.Value.ProductId == "33333" && p.Value.ProductType == ProductType.Durable);
    try
    if (CurrentApp.LicenseInformation.ProductLicenses[product1.Value.ProductId].IsActive)
    myVersionLine.Text = "FULL Version";
    myUpgradeButton.Visibility = System.Windows.Visibility.Collapsed;
    MessageBox.Show("You already own this product");
    else
    receipt = await CurrentApp.RequestProductPurchaseAsync(product1.Value.ProductId, true);
    catch (Exception ex)
    //MessageBox.Show(ex.ToString());
    MessageBox.Show("Purchase did not take place");
    thanks for your help. I'd hate to think that those 5 crashes a day are 5 potential buyers! what's strange is that no-one contacted me to say there was a problem.
    anyone ran into a similar problem or has any idea?
    many thanks!
    cypripri

    I can suggest to use the following strategy.
    Define listing outside the Button_Click event
    private ListingInformation listing = null;
    and try to load the listing information before the user can tap on the button and you can enable the button after the listing has been loaded. For example, in the Loaded event of your page you can:
    try
    Task.Run(async () =>
    listing = await CurrentApp.LoadListingInformationAsync();
    }).Wait();}
    catch { }
    Button.IsEnabled = (listing != null);
    In the Button_Click event verify that listing is not null, otherwise try to reload it.

Maybe you are looking for

  • Unable to amend life of an asset

    I am attempting to amend the life of an asset by navigating to Assets => Asset Workbench, querying the asset and then selecting the 'Books' button. The details of the asset appear and then withih the depreciation tab under Method, I amend the life in

  • Bug in apex 4.2.2.00.11, union with queries in parentheses

    Hello, with apex 4.2.2.00.11 trying to build a simple report with the following query (select 1 a from dual) union (select 2 a from dual) gives: ORA-20001: Query must begin with SELECT or WITH without parentheses it works fine select 1 a from dual un

  • SAP 8.8 Add-On Connection Timed Out....

    Hi Experts, I am new to SAP 8.8.I Created a Customized Add-On by using  B1DESetup_2.1 Specifically give for the SAP 8.8.  I Installed the AddOn in the Same PC(Machine) where i Developed the Customization. It Installs fine...But when i Start the Add-O

  • Remove Advanced Pulldown and Duplicate Frames

    I've been researching this but still have not figured it out: When I import Canon XF100 footage shot in 24fps from my CF card into FCP 7, in the "Log and Transfer" window under "Preferences", should I check or uncheck "Remove Advanced Pulldown and Du

  • Lost files on my PC... if I sync with iphone will it wipe all?

    well...to cut a long story short, My PC has been wiped, toasted, bamboozled, gone, tata, etc... If I want to add more music to my phone, or photos I will need to sync.... my question is, will this mean I loose everything already on my phone?... or is