public WatchFolder(CloudMediaContext context, IEnumerable<IAsset> selectedassets, WatchFolderSettings watchfoldersettings)
 {
     InitializeComponent();
     this.Icon = Bitmaps.Azure_Explorer_ico;
     _context = context;
     _WatchFolderSettings = watchfoldersettings;
     _SelectedAssets = selectedassets;
 }
        private async Task ProcessUploadFileAndMore(object name, int index, AssetCreationOptions assetcreationoptions, WatchFolderSettings watchfoldersettings = null, string storageaccount = null)
        {
            // If upload in the queue, let's wait our turn
            DoGridTransferWaitIfNeeded(index);

            if (storageaccount == null) storageaccount = _context.DefaultStorageAccount.Name; // no storage account or null, then let's take the default one

            TextBoxLogWriteLine("Starting upload of file '{0}'", name);
            bool Error = false;
            IAsset asset = null;
            try
            {
                asset = _context.Assets.CreateFromFile(
                                                      name as string,
                                                      storageaccount,
                                                      assetcreationoptions,
                                                      (af, p) =>
                                                      {
                                                          DoGridTransferUpdateProgress(p.Progress, index);
                                                      }
                                                      );
                AssetInfo.SetFileAsPrimary(asset, Path.GetFileName(name as string));
            }
            catch (Exception e)
            {
                Error = true;
                DoGridTransferDeclareError(index, e);
                TextBoxLogWriteLine("Error when uploading '{0}'", name, true);
                TextBoxLogWriteLine(e);
                if (watchfoldersettings != null && watchfoldersettings.SendEmailToRecipient != null)
                {
                    Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: upload error " + name, e.Message);
                }

            }
            if (!Error)
            {
                DoGridTransferDeclareCompleted(index, asset.Id);
                if (watchfoldersettings != null && watchfoldersettings.DeleteFile) //user checked the box "delete the file"
                {
                    try
                    {
                        File.Delete(name as string);
                        TextBoxLogWriteLine("File '{0}' deleted.", name);
                    }
                    catch (Exception e)
                    {
                        TextBoxLogWriteLine("Error when deleting '{0}'", name, true);
                        if (watchfoldersettings.SendEmailToRecipient != null) Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: Error when deleting " + asset.Name, e.Message);

                    }
                }

                if (watchfoldersettings != null && watchfoldersettings.JobTemplate != null) // option with watchfolder to run a job based on a job template
                {
                    string jobname = string.Format("Processing of {0} with template {1}", asset.Name, watchfoldersettings.JobTemplate.Name);
                    List<IAsset> assetlist = new List<IAsset>() { asset };
                    // if user wants to insert a workflow or other asstes as asset #0
                    if (watchfoldersettings.TypeInputExtraInput != TypeInputExtraInput.None)
                    {
                        if (watchfoldersettings.ExtraInputAssets != null) assetlist.InsertRange(0, watchfoldersettings.ExtraInputAssets);
                    }

                    TextBoxLogWriteLine(string.Format("Submitting job '{0}'", jobname));

                    // Submit the job
                    IJob job = _context.Jobs.Create(jobname, watchfoldersettings.JobTemplate, assetlist, Properties.Settings.Default.DefaultJobPriority);

                    try
                    {
                        job.Submit();
                    }
                    catch (Exception e)
                    {
                        // Add useful information to the exception
                        TextBoxLogWriteLine("There has been a problem when submitting the job '{0}'", job.Name, true);
                        TextBoxLogWriteLine(e);
                        if (watchfoldersettings.SendEmailToRecipient != null)
                        {
                            Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: Error when submitting job for asset " + asset.Name, e.Message);
                        }
                        return;
                    }

                    DoRefreshGridJobV(false);

                    IJob myjob = GetJob(job.Id);
                    while (myjob.State == JobState.Processing || myjob.State == JobState.Queued || myjob.State == JobState.Scheduled)
                    {
                        System.Threading.Thread.Sleep(1000);
                        myjob = GetJob(job.Id);
                    }
                    if (myjob.State == JobState.Finished)
                    {
                        // job template does not rename the output assets. As a fix, we do this:
                        int taskind = 1;
                        foreach (var task in myjob.Tasks)
                        {
                            int outputind = 1;
                            foreach (var outputasset in task.OutputAssets)
                            {
                                IAsset oasset = AssetInfo.GetAsset(outputasset.Id, _context);
                                try
                                {
                                    oasset.Name = string.Format("{0} processed with {1}", asset.Name, watchfoldersettings.JobTemplate.Name);
                                    if (myjob.Tasks.Count > 1)
                                    {
                                        oasset.Name += string.Format(" - task {0}", taskind);
                                    }
                                    if (task.OutputAssets.Count > 1)
                                    {
                                        oasset.Name += string.Format(" - output asset {0}", outputind);
                                    }
                                    oasset.Update();
                                    TextBoxLogWriteLine("Output asset {0} renamed.", oasset.Name);
                                }
                                catch (Exception e)
                                {
                                    TextBoxLogWriteLine("Error when renaming an output asset", true);
                                    TextBoxLogWriteLine(e);
                                }

                                outputind++;
                            }
                            taskind++;
                        }


                        if (watchfoldersettings.PublishOutputAssets) //user wants to publish the output asset when it has been processed by the job 
                        {
                            IAccessPolicy policy = _context.AccessPolicies.Create("AP:" + myjob.Name, TimeSpan.FromDays(Properties.Settings.Default.DefaultLocatorDurationDaysNew), AccessPermissions.Read);
                            foreach (var oasset in myjob.OutputMediaAssets)
                            {
                                ILocator MyLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, oasset, policy, null);
                                if (watchfoldersettings.SendEmailToRecipient != null)
                                {
                                    IStreamingEndpoint SelectedSE = AssetInfo.GetBestStreamingEndpoint(_context);
                                    StringBuilder sb = new StringBuilder();
                                    Uri SmoothUri = MyLocator.GetSmoothStreamingUri();
                                    if (SmoothUri != null)
                                    {
                                        string playbackurl = AssetInfo.DoPlayBackWithStreamingEndpoint(PlayerType.AzureMediaPlayer, SmoothUri.AbsoluteUri, _context, this, oasset, launchbrowser: false, UISelectSEFiltersAndProtocols: false);
                                        sb.AppendLine("Link to playback the asset:");
                                        sb.AppendLine(playbackurl);
                                        sb.AppendLine();
                                    }
                                    sb.Append(AssetInfo.GetStat(oasset, SelectedSE));
                                    Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: Output asset published for asset " + asset.Name, sb.ToString());
                                }
                            }
                        }
                        else // no publication
                        {
                            foreach (var oasset in myjob.OutputMediaAssets)
                            {
                                if (watchfoldersettings.SendEmailToRecipient != null)
                                {
                                    StringBuilder sb = new StringBuilder();
                                    sb.Append(AssetInfo.GetStat(oasset));

                                    Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: asset uploaded and processed " + asset.Name, sb.ToString());
                                }
                            }

                        }
                    }
                    else  // not completed successfuly
                    {
                        if (watchfoldersettings.SendEmailToRecipient != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append((new JobInfo(job).GetStats()));
                            Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: job " + job.State.ToString() + " for asset " + asset.Name, sb.ToString());
                        }
                    }
                }
                else // user selected no processing. Upload successfull
                {
                    if (watchfoldersettings != null && watchfoldersettings.SendEmailToRecipient != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append(AssetInfo.GetStat(asset));
                        Program.CreateAndSendOutlookMail(watchfoldersettings.SendEmailToRecipient, "Explorer Watchfolder: upload successful " + asset.Name, sb.ToString());
                    }
                }
            }
            DoRefreshGridAssetV(false);
        }
        private void DoWatchFolder()
        {
            WatchFolder form = new WatchFolder(_context, ReturnSelectedAssets(), MyWatchFolderSettings)
            {
                WatchUseQueue = Properties.Settings.Default.useTransferQueue,
            };

            if (form.ShowDialog() == DialogResult.OK)
            {
                MyWatchFolderSettings = form.WatchFolderGetSettings;
                Properties.Settings.Default.useTransferQueue = form.WatchUseQueue;
                Program.SaveAndProtectUserConfig();


                if (!MyWatchFolderSettings.IsOn) // user want to stop the watch folder (if if exists)
                {
                    if (MyWatchFolderSettings.Watcher != null)
                    {
                        MyWatchFolderSettings.Watcher.EnableRaisingEvents = false;
                        MyWatchFolderSettings.Watcher = null;
                    }
                    toolStripStatusLabelWatchFolder.Visible = false;

                }
                else // User wants to active the watch folder
                {
                    if (MyWatchFolderSettings.Watcher == null)
                    {
                        // Create a new FileSystemWatcher and set its properties.
                        MyWatchFolderSettings.Watcher = new FileSystemWatcher();


                        /* For later development : use notification queue
                        //create notifcation queue
                        //create the cloud storage account from name and private key


                        // TO DO: check that storage key exist
                        CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(_context.DefaultStorageAccount.Name, _credentials.StorageKey), _credentials.ReturnStorageSuffix(), true);


                        //create the cloud queue client from the storage connection string
                        CloudQueueClient cloudQueueClient = cloudStorageAccount.CreateCloudQueueClient();

                        //get a cloud queue reference
                        CloudQueue notificationsQueue = cloudQueueClient.GetQueueReference(Constants.AzureNotificationNameWatchFolder);

                        //create the queue if it does not exist
                        notificationsQueue.CreateIfNotExists();
                        

                        //create a notification endpoint and store it the glbal variable
                        MyWatchFolderSettings.NotificationEndPoint =
                            _context.NotificationEndPoints
                                .Create("notificationendpoint", NotificationEndPointType.AzureQueue, Constants.AzureNotificationNameWatchFolder);
                         */

                    }

                    MyWatchFolderSettings.Watcher.Path = MyWatchFolderSettings.FolderPath;
                    /* Watch for changes in LastAccess and LastWrite times, and
                       the renaming of files or directories. */
                    MyWatchFolderSettings.Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                       | NotifyFilters.FileName; //| NotifyFilters.DirectoryName;
                    // Only watch text files.
                    MyWatchFolderSettings.Watcher.Filter = "*.*";
                    MyWatchFolderSettings.Watcher.IncludeSubdirectories = false;

                    // Begin watching.
                    MyWatchFolderSettings.Watcher.EnableRaisingEvents = true;
                    toolStripStatusLabelWatchFolder.Visible = true;

                    MyWatchFolderSettings.Watcher.Created += (s, e) =>
                    {
                        if (!this.seen.ContainsKey(e.FullPath)
                            || (DateTime.Now - this.seen[e.FullPath]) > this.seenInterval)
                        {
                            this.seen[e.FullPath] = DateTime.Now;
                            ThreadPool.QueueUserWorkItem(
                                this.WaitForCreatingProcessToCloseFileThenDoStuff, e.FullPath);
                        }
                    };
                }
            }
        }