private void btnMessage_Comment_Browse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ClGlobul.CommentMessagesList.Clear();

                txtCommentMessage.IsReadOnly = true;
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".txt";
                dlg.Filter = "Text documents (.txt)|*.txt";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    txtCommentMessage.Text = dlg.FileName.ToString();
                }
                try
                {
                    ClGlobul.CommentMessagesList = GlobusFileHelper.ReadFile(txtCommentMessage.Text.Trim());
                }
                catch (Exception ex)
                {
                    GlobusLogHelper.log.Info(" Please Select File ");
                }
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error :" + ex.StackTrace);
            }
        }
 void AddDependency(object pSender, RoutedEventArgs pEvents)
 {
   var lDialog = new Microsoft.Win32.OpenFileDialog()
   {
     Title = "Choose dependency Assembly",
     CheckFileExists = true,
     Filter = "Assemblies|*.dll;*.exe;*.winmd|All Files|*.*",
     Multiselect = true
   };
   if (lDialog.ShowDialog() == true)
   {
     foreach (string lName in lDialog.FileNames)
     {
       // Check if the dependency is already on the list.
       var lSameLib = (
           from ListViewItem lItem in DependencyList.Items
           where lItem.Content.Equals(lName)
           select lItem);
       if (lSameLib.Count() == 0)
       {
         ListViewItem lEntry = new ListViewItem();
         lEntry.Content = lName;
         DependencyList.Items.Add(lEntry);
       }
     }
   }
 }
示例#3
0
        private void cc_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog d = new Microsoft.Win32.OpenFileDialog();
            d.Filter = "JPEG Image (*.JPG)|*.JPG";
               bool? result =  d.ShowDialog(this);
               if (result == true)
               {
               System.IO.FileInfo fi = new System.IO.FileInfo(d.FileName);
               //fi.CopyTo("..\\..\\Resources\\"+fi.Name,true);
               XmlDataProvider xdp = this.Resources["BookData"] as XmlDataProvider;
               System.Xml.XmlElement xe = (System.Xml.XmlElement)(e.Source as System.Windows.Controls.ContentControl).Content;
               if (xe["Image"] != null)
               {
                   xe["Image"].InnerText = fi.FullName;
                   //System.Xml.XmlTextWriter xr = new System.Xml.XmlTextWriter(new System.IO.FileStream(@"C:\a.txt", System.IO.FileMode.OpenOrCreate), Encoding.Unicode);
                   //xe.WriteTo(xr);
                   //xr.Close();

               }
               else
               {
                   System.Xml.XPath.XPathNavigator navigator = xe.CreateNavigator();
                   navigator.AppendChildElement(null, "Image", null, fi.FullName);
                   this.listBox.Items.Refresh();
               }
               }
        }
示例#4
0
        public FindFileDialogue(string filter)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            switch (filter)
            {
                case "csv":
                    dlg.DefaultExt = ".csv";
                    dlg.Filter = "CSV Files (*.csv)|*.csv|All Files |*.*";
                    break;
            }

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                LocationOfFile = filename;
            }
        }
 private void btn_AccountCreation_BrowseAccountFile_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
         dlg.DefaultExt = ".txt";
         dlg.Filter = "Text documents (.txt)|*.txt";
         Nullable<bool> result = dlg.ShowDialog();
         if (result == true)
         {
             GlobalDeclaration.objAccountCreation.QueueOfProxy.Clear();
             txt_AccountCreation_LoadAccountFilePath.Text = dlg.FileName.ToString();
             List<string> tempList= Globussoft.GlobusFileHelper.ReadFiletoStringList(dlg.FileName);
             foreach(string item in tempList)
             {
                 GlobalDeclaration.objAccountCreation.QueueOfProxy.Enqueue(item);
             }
         }
         GlobusLogHelper.log.Info(" [ " + GlobalDeclaration.objAccountCreation.QueueOfProxy.Count + " ] Proxy Uploaded");
         lbl_AccountCreation_Report_NoOfAccountLoaded.Dispatcher.Invoke(new Action(() =>
         {
             lbl_AccountCreation_Report_NoOfAccountLoaded.Content = GlobalDeclaration.objAccountCreation.QueueOfProxy.Count.ToString();
         }));
     }
     catch (Exception ex)
     {
         GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
     }
 }
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     var ofd = new Microsoft.Win32.OpenFileDialog();
     var result = ofd.ShowDialog();
     if (result == false) return;
     nombreArchivo.Text = ofd.FileName;
 }
示例#7
0
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     // Create OpenFileDialog 
     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
     // Set filter for file extension and default file extension 
     dlg.DefaultExt = ".png";
     // Display OpenFileDialog by calling ShowDialog method 
     if (dlg.ShowDialog() == true)
     {
         StatusLabel.Content = "Uploading image...";
         new Thread(delegate()
         {
             try
             {
                 String url = ImageAPI.imgur.imgur.UploadImage(dlg.FileName);
                 Dispatcher.Invoke(new Action(() => {
                     MessageTextBox.Text += "\r\n" + url;
                     StatusLabel.Content = "画像を投稿しました";
                 }));
             }
             catch(Exception ex)
             {
                 Dispatcher.Invoke(new Action(() =>
                 {
                     StatusLabel.Content = ex.Message;
                 }));
             }
         }).Start();
     }
 }
 private void LoadTests()
 {
     var fileDialog = new Microsoft.Win32.OpenFileDialog
     {
         FileName = "../../tests.txt"
     };
     try
     {
         var fileLines = File.ReadAllLines(fileDialog.FileName);
         foreach (string line in fileLines)
         {
             var sample = new Sample
             {
                 Cells = new int[Globals.GridSize]
             };
             var splitedLine = line.Split(' ');
             int j;
             for (j = 0; j < Globals.GridSize; j++)
             {
                 sample.Cells[j] = Convert.ToInt32(splitedLine[j]);
             }
             sample.Digit = splitedLine[j];
             _samples.Add(sample);
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
     }
 }
示例#9
0
 private void btnOpenFile_Click(object sender, RoutedEventArgs e)
 {
     Button btn = sender as Button;
     switch (btn.Tag.ToString())
     {
         case "OpenFile":
             //添加显示的图片。
             Microsoft.Win32.OpenFileDialog file = new Microsoft.Win32.OpenFileDialog();
             file.Filter = "*.jpg|*.jpg|*.bmp|*.bmp|*.gif|*.gif|*.png|*.png";
             file.ShowDialog();
             this.ImgInfo.Source = new BitmapImage(new Uri(file.FileName));
             break;
         case "InitImage":
             //图片重置大小。
             ScaleTransform scale = this.Scroll.GetTransFormGroup().Children[0] as ScaleTransform;
             scale.ScaleX = 1;
             scale.ScaleY = 1;
             break;
         case "OcrKnow":
             //调用一个exe程序的方面实现。
             this.Execute(this.ImgInfo.Source.ToString());
             break;
         case "SaveText":
             this.SaveText();
             break;
         case "RotateTransform":
             //图片旋转90度的。
             this.Scroll.DoImageRotate();
             break;
         case "AboutBox":
             MessageBox.Show("AboutBox");
             break;
     }
 }
        private void btn_MentionUsers_BrowseMessage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".txt";
                dlg.Filter = "Text documents (.txt)|*.txt";
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        txt_MentionUser_LoadMessage_MessageFilePath.Text = dlg.FileName;
                    }));

                    List<string> tmpList = Globussoft.GlobusFileHelper.ReadFiletoStringList(dlg.FileName);
                    GlobalDeclration.objMentionUser.listOfMessageToComment = tmpList.Distinct().ToList();

                    GlobusLogHelper.log.Info(tmpList.Count + " Urls Uploaded ");

                }
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error ==> " + ex.Message);
            }
        }
        private void loadDocumentBtn_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".png";
            dlg.Filter = "Image documents (.png)|*.png";

            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                ocrData.clearData();

                filePath = dlg.FileName;
                sourcePathTxtBox.Text = filePath;

                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = new Uri(filePath);
                bi.EndInit();

                sourceImage.Stretch = Stretch.Uniform;
                sourceImage.Source = bi;

                ocrData.filename = Regex.Match(filePath, @".*\\([^\\]+$)").Groups[1].Value;
                ocrData.created = File.GetCreationTime(filePath);

                processBtn.IsEnabled = true;
            }
        }
        private void btnPinUrls_Like_Browse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtLikePinUrl.IsReadOnly = true;
                ClGlobul.lstAddToBoardUserNames.Clear();
                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.DefaultExt = ".txt";
                ofd.Filter = "Text documents (.txt)|*.txt";
                Nullable<bool> result = ofd.ShowDialog();

                if (result == true)
                {
                    txtLikePinUrl.Text = ofd.FileName.ToString();
                    Thread ReadLargeFileThread = new Thread(ReadLargeLikePinUrlsFile);
                    ReadLargeFileThread.Start(ofd.FileName);
                    ClGlobul.lstAddToBoardUserNames = GlobusFileHelper.ReadFile(txtLikePinUrl.Text.Trim());
                    GlobusLogHelper.log.Info(" => [ " + ClGlobul.lstAddToBoardUserNames.Count + " Pin Urls Uploaded ]");
                }
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Info("Error :" + ex.StackTrace);
            }
        }
示例#13
0
        private void BrowseWaitingListButton_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            if (!string.IsNullOrEmpty(WaitingListFileTextBox.Text))
            {
                string dir = System.IO.Path.GetDirectoryName(WaitingListFileTextBox.Text);
                if (Directory.Exists(dir))
                {
                    dlg.InitialDirectory = dir;
                }
            }

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".csv";
            dlg.Filter = "CSV Files (*.csv)|*.csv";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                WaitingListFileTextBox.Text = dlg.FileName;
            }
        }
    public void UpdateThumbnail(object sender, EventArgs e)
    {
      Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
      dlg.FileName = ""; // Default file name
      dlg.DefaultExt = ".png"; // Default file extension
      dlg.Filter = "Image Files(*.PNG;*.JPG;*.BMP;*.GIF)|*.PNG;*.JPG;*.BMP;*.GIF|All files (*.*)|*.*";

      Nullable<bool> result = dlg.ShowDialog();
      if (true == result)
      {
        if (null != dlg.FileName && 0 < dlg.FileName.Length && File.Exists(dlg.FileName))
        {
          // loadimage
          try
          {
            // fetch via URL
            Uri imageUri = new Uri(dlg.FileName);
            BitmapDecoder bmd = BitmapDecoder.Create(imageUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            // reset width
            ThumbnailImage.Width = double.NaN;

            // set the source
            _thumbnailImage.Source = bmd.Frames[0];
            _isDefault = false;
          }
          catch (Exception) { /* noop */ }
        }
      }
    }
示例#15
0
        private void openList_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = "mp3 files (*.mp3)|*.mp3";
            dlg.DefaultExt = "mp3";
            dlg.Title = "Browse MP3 Files";
            dlg.Multiselect = true;

            if(player.IsInit){
                // Display OpenFileDialog by calling ShowDialog method
                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    List<String> paths = new List<string>();
                    
                    foreach (String file in dlg.FileNames)
                    {
                        paths.Add(file);
                        char[] st = {'\\'};
                        String[] name = file.Split(st);
                        //MessageBox.Show(name[name.Length - 1]);
                        listBox1.Items.Add(name[name.Length - 1]);
                    }

                    listBox1.Tag = paths;
                }
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.InitialDirectory = Worker.templates_dir;
            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".txt";
            dlg.Filter = "XML Files (*.xml)|*.xml";

            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();

            string filename = "";
            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                filename = dlg.FileName;
                TextBox.Text = filename;
                
            }
            Select_DPI new_window = new Select_DPI();
            new_window.ShowDialog();
            sheet = new Sheet(filename);
            lbl_id.Content = sheet.id;
            lbl_choices.Content = sheet.choice;
            lbl_questions.Content = sheet.questions;

        }
        private void OpenForeignDB(object sender, RoutedEventArgs e)
        {
            var DbFile = new Microsoft.Win32.OpenFileDialog() { Filter = "DataBase Files (*.db)|*.db" };
            var result = DbFile.ShowDialog();

            if ((bool)result)
            {
                var file = DbFile.FileName;

                ForeignDB = new DbHandle(new SQLIteClient("", "", "", @file));

                ForeignColection = new CookingBookDataCollection(ForeignDB);

                ForeignColection.GetAll();

                ForeignDbListViev.ItemsSource = ForeignColection.ListOfRecipes;

                CollectionView ForeignRecipeViev = (CollectionView)CollectionViewSource.GetDefaultView(ForeignDbListViev.ItemsSource);
                ForeignRecipeViev.Filter = (item => (String.IsNullOrEmpty(ForeignRecipeFilterText.Text) ? true : ((item as Recipe).Name.IndexOf(ForeignRecipeFilterText.Text, StringComparison.OrdinalIgnoreCase) >= 0)));
                OpenedName.Text = @DbFile.SafeFileName;
            }
            else
            {
                MessageBox.Show("dsfgds");
            }
        }
示例#18
0
        //public RelayCommand _browseButtonCommand;
        
        public void brows()
        {
            //MessageBox.Show(show);
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".png";
            //dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
            dlg.Filter = "EXCEL Files (*.xls)|*.xls|EXCEL Files (*.xlsx)|*.xlsx";
            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();
            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                filePath = dlg.FileName;
                MainViewModel.staticFilePath = filePath;
                //return fileName;
            }
            else
            {
                filePath = null;
                MainViewModel.staticFilePath = filePath;
                //return fileName;
            }

        }
示例#19
0
        public string[] GetFileOpenPath(string title, string filter)
        {
            if (VistaOpenFileDialog.IsVistaFileDialogSupported)
            {
                VistaOpenFileDialog openFileDialog = new VistaOpenFileDialog();
                openFileDialog.Title = title;
                openFileDialog.CheckFileExists = true;
                openFileDialog.RestoreDirectory = true;
                openFileDialog.Multiselect = true;
                openFileDialog.Filter = filter;

                if (openFileDialog.ShowDialog() == true)
                    return openFileDialog.FileNames;
            }
            else
            {
                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.Title = title;
                ofd.CheckFileExists = true;
                ofd.RestoreDirectory = true;
                ofd.Multiselect = true;
                ofd.Filter = filter;

                if (ofd.ShowDialog() == true)
                    return ofd.FileNames;
            }

            return null;
        }
示例#20
0
        private void OpenFolderOrFile(object sender, ExecutedRoutedEventArgs e)
        {
            var dialog = new Microsoft.Win32.OpenFileDialog { CheckFileExists = true, CheckPathExists = true, Multiselect = false };

            if (lastAddedPath != null)
            {
                dialog.FileName = lastAddedPath;
            }

            var ret = dialog.ShowDialog(this);
            if (ret.HasValue && ret.Value)
            {
                lastAddedPath = dialog.FileName;

                string filename = null;
                if (File.Exists(lastAddedPath))
                {
                    filename = lastAddedPath;
                    lastAddedPath = Path.GetDirectoryName(lastAddedPath);
                }
                DirectoryController.Scan(lastAddedPath);
                DirectoryController.SelectFile(filename);
                ShowFile();
            }
        }
示例#21
0
        public static string AskForImageFilePathViaDialog()
        {
            //BitmapImage returnImage = null;

            dynamic op = new Microsoft.Win32.OpenFileDialog();
            op.Title = "画像を選択してください。";
            op.Filter = "|*.jpg;*.jpeg;*.png;*.bmp;.gif|" + "JPEG形式 (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + "PNG形式 (*.png)|*.png|" + "GIF形式(*.gif)|*.gif|" + "BMP形式(*.bmp)|*.bmp";
            //"全ての形式|*.*|";

            //初期位置は前のを覚えていればそれを、なければマイドキュメント
            //Dim previousPath = LocalSettings.ReadSetting(Constants.PreviousOpenFilePath)
            //If previousPath IsNot Nothing Then
            //    op.InitialDirectory = previousPath
            //Else
            //    op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
            //End If

            //FilterIndexは1から始まる
            //op.FilterIndex = 1;
            if (op.ShowDialog() == true)
            {
                return op.FileName;
                //Dim rawImage = New RawImage(op.FileName)
                //returnImage = rawImage.CreateBitmapImage()

                //ファイルパスは覚えておく
                //LocalSettings.AddUpdateAppSettings(Constants.PreviousOpenFilePath, op.FileName)
            }

            return null;
        }
        private void btLoad_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.FileOk += dialog_FileOk;
            dialog.ShowDialog();
        }
        ///<summary>
        /// Imports a protected key from a file and updates a <see cref="ProtectedKeySettings"/> structure with the imported values.
        ///</summary>
        ///<param name="uiService">The user-interface service for displaying messages and windows to the user.</param>
        ///<param name="keySettings">The key settings structure to update.</param>
        public static void ImportProtectedKey(IUIServiceWpf uiService, ProtectedKeySettings keySettings)
        {
            string protectedKeyFilename = keySettings.FileName;
            DataProtectionScope protectedKeyScope = keySettings.Scope;

            if (!File.Exists(protectedKeyFilename))
            {
                var dialogResult = uiService.ShowMessageWpf(
                                        string.Format(CultureInfo.CurrentCulture, Resources.MessageboxMessageUnableToLocateCryptoKey, keySettings.FileName),
                                        Resources.MessageboxTitleUnableToLocateCryptoKey,
                                        System.Windows.MessageBoxButton.YesNo);
                if (dialogResult == System.Windows.MessageBoxResult.Yes)
                {

                    Microsoft.Win32.OpenFileDialog locateCryptoKeyDialog = new Microsoft.Win32.OpenFileDialog
                    {
                        Title = Resources.MessageboxTitleUnableToLocateCryptoKey
                    };

                    var locateFileDislogresult = uiService.ShowFileDialog(locateCryptoKeyDialog);
                    if (true == locateFileDislogresult.DialogResult)
                    {
                        protectedKeyFilename = locateCryptoKeyDialog.FileName;
                    }
                }
            }

            using (Stream keyFileContents = File.OpenRead(protectedKeyFilename))
            {
                var key = KeyManager.Read(keyFileContents, protectedKeyScope);
                keySettings.ProtectedKey = key;
                keySettings.Scope = protectedKeyScope;
                keySettings.FileName = protectedKeyFilename;
            }
        }
        private void BT_AddImage_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.DefaultExt = ".jpeg";
            dialog.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";

            Nullable<bool> result = dialog.ShowDialog();

            if (result == true)
            {

                CB_Images.Items.Add(dialog.FileName.ToString());
                IMG_SelectedImage.Source = CloneImage(dialog.FileName.ToString());
                imageSource.Add(dialog.FileName.ToString());
                imageCaptions.Add("");

                if( (CB_Images.Items.Count-1)  == 0 )
                {
                    CB_Images.SelectedIndex = 0;
                }
                else
                {
                    CB_Images.SelectedIndex = CB_Images.Items.Count - 1;
                }
            }
        }
示例#25
0
        private void menuItemFileOpen_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openXmlFileDialog = new Microsoft.Win32.OpenFileDialog();
            openXmlFileDialog.DefaultExt = "xml";
            openXmlFileDialog.Filter = "XML(.xml)|*.xml";
            //show dialog
            Nullable<bool> result = openXmlFileDialog.ShowDialog();

            //wait the result
            if (result == true && openXmlFileDialog.FileName != "")
            {
                try
                {
                    //http://blog.csdn.net/zengjibing/archive/2009/01/16/3797837.aspx
                    XmlDocument answerXmlSource = new XmlDocument();
                    answerXmlSource.Load(openXmlFileDialog.FileName);
                    XmlDataProvider answerXmlprovider = this.FindResource("answerXmlDoc") as XmlDataProvider;
                    answerXmlprovider.Document = answerXmlSource;
                    answerXmlprovider.XPath = "/ArrayOfQuestion/Question";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            }
        }
示例#26
0
        //<< --------------------------   >>//
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".jpg";
            dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";


            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                string filename = dlg.FileName;
                lblFilename.Content = filename;
                imgCategoryImage.Source = new BitmapImage(new Uri(filename));
            }

        }
        private void ChoosePackageDialog()
        {
            // Configure open file dialog box 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document"; // Default file name 
            dlg.DefaultExt = ".AGT"; // Default file extension 
            dlg.Filter = "Agent Package (.agt)|*.agt"; // Filter files by extension 

            // Show open file dialog box 
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results 
            if (result == true)
            {
                // Open document 
                PackageSource = dlg.FileName;

                ICSharpCode.SharpZipLib.Zip.FastZip fz = new FastZip();

                var root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), (Guid.NewGuid().ToString()));

                fz.ExtractZip(PackageSource, root, FastZip.Overwrite.Always, null, null, null, true);

                PackageFile = System.IO.Path.Combine(root, "package.json");

                if (System.IO.File.Exists(PackageFile))
                {
                    var cnt =  System.IO.File.ReadAllText(PackageFile);
                    Contents = cnt;
                }
            }
        }
示例#28
0
        private void OnCommand()
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            //dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".jws"; // Default file extension
            dlg.Filter = "Jade Workspace files (.jws)|*.jws"; // Filter files by extension
            dlg.CheckFileExists = true;
            dlg.CheckPathExists = true;

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;

                try
                {
                    JadeData.Workspace.IWorkspace workspace = JadeData.Persistence.Workspace.Reader.Read(filename);
                    _viewModel.Workspace = new JadeControls.Workspace.ViewModel.Workspace(workspace);
                }
                catch (System.Exception e)
                {

                }
            }
        }
示例#29
0
        private void btnSource_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.FileName = "Select File to Convert";

            Nullable<bool> result = openFileDialog.ShowDialog();

            if (result == true)
            {
                entSource.Text = openFileDialog.FileName.ToLower();
                if (!(entSource.Text.EndsWith(".shp") ||
                       entSource.Text.EndsWith(".kml")))
                {
                    entSource.Text = "Extension Must be SHP or KML";
                    btnConvert.IsEnabled = false;
                }

                else
                {
                    if (entDestination.Text.EndsWith(".shp") ||
                           entDestination.Text.EndsWith(".kml"))
                    {
                        btnConvert.IsEnabled = true;
                    }
                }
            }
        }
示例#30
0
        //选择目标文件
        private void OnSelectTarget(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.DefaultExt = ".xml";
            ofd.Filter     = "xml file|*.xml";


            ofd.ShowDialog();

            if (ofd.FileName == string.Empty)
            {
                return;
            }
            ReadXML(ofd.FileName);



            Tool.RobotsHome.RobotInfoCollect.GetInstance().ClearBinInfo();

            List <RobotInfo> list = new List <RobotInfo>();

            list = dcRobotInfo.Collection.ToList().Where(p => p.NetState == true || p.BinUpdate == true).ToList();

            string netidList = null;

            foreach (RobotInfo info in list)
            {
                if (info == null)
                {
                    continue;
                }
                netidList += info.NetId + "|";
            }

            if (null == netidList)
            {
                return;
            }

            string id      = TB_NodeId.Text.ToString();
            string can_bus = ComboxNodeMode.Text;
            int    node_id;
            int    can_bus_type;

            if (id == string.Empty)
            {
                node_id = 0;
            }
            else
            {
                node_id = Convert.ToInt32(id);
            }
            if (can_bus == string.Empty)
            {
                can_bus_type = 0;
            }
            else
            {
                can_bus_type = Convert.ToInt32(can_bus);
            }
        }
示例#31
0
        public MainWindow()
        {
            InitializeComponent();
            DockPanel dock       = new DockPanel();
            Window    winAudTest = new Window {
                Title = "Audio Tester", Content = dock
            };
            Grid visuals = new Grid();

            dock.Children.Add(visuals);
            DockPanel.SetDock(visuals, Dock.Bottom);
            for (int i = 0; i < brdz.Length; i++)
            {
                brdz[i] = new Border {
                    VerticalAlignment = VerticalAlignment.Bottom, Height = 100, Background = new SolidColorBrush(Color.FromRgb(255, 108, 0)), Margin = new Thickness(8, 0, 8, 0)
                };
                visuals.Children.Add(brdz[i]);
                visuals.ColumnDefinitions.Add(new ColumnDefinition());
                Grid.SetColumn(brdz[i], i);
            }
            winAudTest.Show();
            if (File.Exists($"{Directory.GetCurrentDirectory()}\\tray.ico"))
            {
                tBi.Icon = new System.Drawing.Icon($"{Directory.GetCurrentDirectory()}\\tray.ico");
            }
            else
            {
                MessageBox.Show("Can't find icon");
                Environment.Exit(1);
            }
            dT.Tick  += DT_Tick;
            dT2.Tick += DT2_Tick;
            Loaded   += MainWindow_Loaded;

            tBi.ContextMenu = new ContextMenu();
            MenuItem acts = new MenuItem {
                Header = "Actions"
            };
            MenuItem quit = new MenuItem {
                Header = "Quit"
            };

            quit.Click += ((a, b) => {
                Environment.Exit(0);
            });
            MenuItem cI = new MenuItem {
                Header = "Change Image"
            };

            cI.Click += ((a, b) => {
                Window w = new Window();
                w.Content = new Button {
                    Content = "Choose Image..."
                };
                ((Button)w.Content).Click += ((c, d) => {
                    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog {
                        Title = "Choose Image..."
                    };
                    if ((bool)ofd.ShowDialog())
                    {
                        sx.Source = new BitmapImage(new Uri(ofd.FileName));
                    }
                });
                w.ShowDialog();
            });
            MenuItem sets = new MenuItem {
                Header = "Settings"
            };

            sets.Click += ((a, b) => {
                TabControl tc = new TabControl {
                    TabStripPlacement = Dock.Left
                };
                Window settings = new Window {
                    Title = "Settings", WindowStartupLocation = WindowStartupLocation.CenterScreen, ResizeMode = ResizeMode.NoResize, Width = 768, Height = 512, Content = tc
                };
                StackPanel MainContent = new StackPanel();
                TabItem Main = new TabItem {
                    Header = "Main", Content = MainContent
                };
                tc.Items.Add(Main);
                MainContent.Children.Add(new Label {
                    Content = "Appearance", FontWeight = FontWeights.Thin, FontSize = 18
                });
                Button changePic = new Button {
                    Width = 100, Height = 32, Margin = new Thickness(8), Content = "Change Image", HorizontalAlignment = HorizontalAlignment.Left
                };
                changePic.Click += ((so, si) =>
                {
                    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog {
                        Title = "Change Image"
                    };
                    if ((bool)ofd.ShowDialog())
                    {
                        sx.Source = new BitmapImage(new Uri(ofd.FileName));
                    }
                });
                MainContent.Children.Add(changePic);
                settings.Show();
            });
            MenuItem ab = new MenuItem {
                Header = "About"
            };

            ab.Click += ((a, b) => {
                Environment.Exit(0);
            });
            acts.Items.Add(cI);
            acts.Items.Add(sets);
            tBi.ContextMenu.Items.Add(acts);
            tBi.ContextMenu.Items.Add(ab);
            tBi.ContextMenu.Items.Add(quit);
            Top = 0;
        }
示例#32
0
        // click on file picker button ("...")
        private void FilePicker_Click(object sender, RoutedEventArgs e)
        {
            // retrieve window parent object
            Window objWindow = (Window)FindParentWindow(sender);

            // if not found then end
            if (objWindow == null)
            {
                return;
            }

            if (((Button)sender).Name != "TargetFilePicker")
            {
                // create OpenFileDialog control
                Microsoft.Win32.OpenFileDialog objFileDialog = new Microsoft.Win32.OpenFileDialog();

                // set file extension filters
                if (((Button)sender).Name == "SourceFilePicker")
                {                       // button to TextBox "SourceFile"
                    objFileDialog.DefaultExt = ".ps1";
                    objFileDialog.Filter     = "PS1 Files (*.ps1)|*.ps1|All Files (*.*)|*.*";
                }
                else
                {                       // button to TextBox "IconFile"
                    objFileDialog.DefaultExt = ".ico";
                    objFileDialog.Filter     = "Icon Files (*.ico)|*.ico|All Files (*.*)|*.*";
                }

                // display file picker dialog
                Nullable <bool> result = objFileDialog.ShowDialog();

                // file selected?
                if (result.HasValue && result.Value)
                {                 // fill Texbox with file name
                    if (((Button)sender).Name == "SourceFilePicker")
                    {             // button to TextBox "SourceFile"
                        TextBox objSourceFile = (TextBox)objWindow.FindName("SourceFile");
                        objSourceFile.Text = objFileDialog.FileName;
                    }
                    else
                    {                           // button to TextBox "IconFile"
                        TextBox objIconFile = (TextBox)objWindow.FindName("IconFile");
                        objIconFile.Text = objFileDialog.FileName;
                    }
                }
            }
            else
            {             // use custom dialog for folder selection because there is no WPF folder dialog!!!
                TextBox objTargetFile = (TextBox)objWindow.FindName("TargetFile");

                // create OpenFolderDialog control
                OpenFolderDialog.OpenFolderDialog objOpenFolderDialog = new OpenFolderDialog.OpenFolderDialog();
                if (objTargetFile.Text != "")
                {                 // set starting directory for folder picker
                    if (System.IO.Directory.Exists(objTargetFile.Text))
                    {
                        objOpenFolderDialog.InitialFolder = objTargetFile.Text;
                    }
                    else
                    {
                        objOpenFolderDialog.InitialFolder = System.IO.Path.GetDirectoryName(objTargetFile.Text);
                    }
                }
                else
                {                 // no starting directory for folder picker
                    objOpenFolderDialog.InitialFolder = "";
                }

                // display folder picker dialog
                System.Windows.Interop.WindowInteropHelper windowHwnd = new System.Windows.Interop.WindowInteropHelper(this);
                Nullable <bool> result = objOpenFolderDialog.ShowDialog(windowHwnd.Handle);

                if ((result.HasValue) && (result == true))
                {                 // get result only if a folder was selected
                    objTargetFile.Text = objOpenFolderDialog.Folder;
                }
            }
        }
示例#33
0
        private void loadRegisters_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
            {
                DefaultExt = ".txt",
                Filter     = "Pliki tekstowe (.txt)|*.txt"
            };
            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                String[]      xa;
                String        x, a;
                List <String> aL = new List <String>(), xL = new List <String>();
                System.Text.RegularExpressions.Regex _regex = new System.Text.RegularExpressions.Regex("[0-1]+;[0-1]*");
                var lines = File.ReadLines(dlg.FileName);
                if (lines.Count() % 2 == 0 || lines.Count() < 3)
                {
                    showAlert("Parzysta lub mniejsza niż trzy liczba rejestrów."); return;
                }
                registers.Clear();
                int          validLines = 0;
                List <short> lengths    = new List <short>();

                foreach (var line in lines)
                {
                    if (!_regex.IsMatch(line))
                    {
                        continue;
                    }
                    xa = line.Split(';');
                    x  = xa[0];
                    a  = xa[1];
                    if (lengths.Contains((short)x.Length))
                    {
                        registers = CopyList(registersBackup);
                        showAlert("Rejestry o takiej samej długości.");
                        return;
                    }
                    else
                    {
                        lengths.Add((short)x.Length);
                    }

                    if (!x.Contains('1'))
                    {
                        x.Remove(0, 1); x += '1';
                    }
                    if (a == "" || a.Length != x.Length)
                    {
                        aL = perfectPolynomians.Where(z => z.Key == x.Length).Select(y => y.Value).ToList()[0];
                    }
                    else
                    {
                        if (!a.Last().Equals('1'))
                        {
                            a.Remove(a.Length - 1, 0); a += '1';
                        }
                        aL = a.Select(y => y.ToString()).ToList();
                    }
                    xL = x.Select(y => y.ToString()).ToList();
                    registers.Add(new KeyValuePair <List <string>, List <string> >(xL, aL));

                    validLines++;
                }
                if (validLines % 2 == 0 || validLines < 3)
                {
                    registers = CopyList(registersBackup);
                    showAlert("Parzysta lub mniejsza niż trzy liczba POPRAWNYCH rejestrów.");
                    return;
                }
                registersBackup.Clear();
                registersBackup = CopyList(registers);
                fillTheRegistersStackPanel();
                keyLengthWrapPanel.Visibility = Visibility.Visible;
                generateKeyBtn.Visibility     = Visibility.Visible;
            }
        }
示例#34
0
        public virtual async Task <Mat[]> LoadImages(String[] imageNames, String[] labels = null)
        {
            Mat[] mats = new Mat[imageNames.Length];

            for (int i = 0; i < mats.Length; i++)
            {
                String pickImgString = "Use Image from";
                if (labels != null && labels.Length > i)
                {
                    pickImgString = labels[i];
                }

                bool captureSupported;

                if (Device.RuntimePlatform == Device.WPF ||
                    Device.RuntimePlatform == Device.macOS)
                {
                    //Pick image from camera is not implemented on WPF.
                    captureSupported = false;
                }
                else
                {
                    captureSupported = Xamarin.Essentials.MediaPicker.IsCaptureSupported;
                }

                String        action;
                List <String> options = new List <string>();
                options.Add("Default");

                options.Add("Photo Library");

                if (captureSupported)
                {
                    options.Add("Photo from Camera");
                }

                if (Device.RuntimePlatform == Device.Android ||
                    Device.RuntimePlatform == Device.iOS ||
                    Device.RuntimePlatform == Device.UWP)
                {
                    if (this.HasCameraOption && captureSupported)
                    {
                        options.Add("Camera");
                    }
                }
                else if (Device.RuntimePlatform == Device.WPF)
                {
                    options.Add("Camera");
                }


                if (options.Count == 1)
                {
                    action = "Default";
                }
                else
                {
                    action = await DisplayActionSheet(pickImgString, "Cancel", null, options.ToArray());

                    if (
                        action == null || //user clicked outside of action sheet
                        action.Equals("Cancel")    // user cancel
                        )
                    {
                        return(null);
                    }
                }

                if (action.Equals("Default"))
                {
#if __ANDROID__
                    mats[i] = Android.App.Application.Context.Assets.GetMat(imageNames[i]);
#else
                    if (!File.Exists(imageNames[i]))
                    {
                        throw new FileNotFoundException(String.Format("File {0} do not exist.", imageNames[i]));
                    }
                    mats[i] = CvInvoke.Imread(imageNames[i], ImreadModes.Color);
#endif
                }
                else if (action.Equals("Photo Library"))
                {
                    if (Device.RuntimePlatform == Device.WPF)
                    {
#if !(__MACOS__ || __ANDROID__ || __IOS__ || NETFX_CORE)
                        Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
                        dialog.Multiselect = false;
                        dialog.Title       = "Select an Image File";
                        dialog.Filter      = "Image | *.jpg;*.jpeg;*.png;*.bmp;*.gif | All Files | *";
                        if (dialog.ShowDialog() == false)
                        {
                            return(null);
                        }
                        mats[i] = CvInvoke.Imread(dialog.FileName, ImreadModes.AnyColor);
#endif
                    }
                    else
                    {
                        var fileResult = await Xamarin.Essentials.FilePicker.PickAsync(Xamarin.Essentials.PickOptions.Images);

                        if (fileResult == null) //canceled
                        {
                            return(null);
                        }
                        using (Stream s = await fileResult.OpenReadAsync())
                            mats[i] = await ReadStream(s);
                    }
                }
                else if (action.Equals("Photo from Camera"))
                {
                    var takePhotoResult = await Xamarin.Essentials.MediaPicker.CapturePhotoAsync();

                    if (takePhotoResult == null) //canceled
                    {
                        return(null);
                    }
                    using (Stream stream = await takePhotoResult.OpenReadAsync())
                        mats[i] = await ReadStream(stream);
                }
                else if (action.Equals("Camera"))
                {
                    mats = new Mat[0];
                }
            }

            return(mats);
        }
示例#35
0
        /// <summary>
        /// Pick image and call find similar for each faces detected
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FindSimilar_Click(object sender, RoutedEventArgs e)
        {
            // Show file picker
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".jpg";
            dlg.Filter     = "Image files(*.jpg) | *.jpg";
            var filePicker = dlg.ShowDialog();

            if (filePicker.HasValue && filePicker.Value)
            {
                // User picked image
                // Clear previous detection and find similar results
                TargetFaces.Clear();
                FindSimilarCollection.Clear();

                var sw = Stopwatch.StartNew();
                SelectedFile = dlg.FileName;

                var imageInfo = UIHelper.GetImageInfoForRendering(SelectedFile);

                // Detect all faces in the picked image
                using (var fileStream = File.OpenRead(SelectedFile))
                {
                    MainWindow.Log("Request: Detecting faces in {0}", SelectedFile);

                    MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
                    string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

                    var faceServiceClient = new FaceServiceClient(subscriptionKey);
                    var faces             = await faceServiceClient.DetectAsync(fileStream);

                    // Update detected faces on UI
                    foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo))
                    {
                        TargetFaces.Add(face);
                    }

                    MainWindow.Log("Response: Success. Detected {0} face(s) in {0}", faces.Length, SelectedFile);

                    // Find similar faces for each face
                    foreach (var f in faces)
                    {
                        var faceId = f.FaceId;

                        MainWindow.Log("Request: Finding similar faces for face {0}", faceId);

                        try
                        {
                            // Call find similar REST API, the result contains all the face ids which similar to the query face
                            const int requestCandidatesCount = 3;
                            var       result = await faceServiceClient.FindSimilarAsync(faceId, _faceListName, requestCandidatesCount);

                            // Update find similar results collection for rendering
                            var gg = new FindSimilarResult();
                            gg.Faces     = new ObservableCollection <Face>();
                            gg.QueryFace = new Face()
                            {
                                ImagePath = SelectedFile,
                                Top       = f.FaceRectangle.Top,
                                Left      = f.FaceRectangle.Left,
                                Width     = f.FaceRectangle.Width,
                                Height    = f.FaceRectangle.Height,
                                FaceId    = faceId.ToString(),
                            };
                            foreach (var fr in result)
                            {
                                gg.Faces.Add(FacesCollection.First(ff => ff.FaceId == fr.PersistedFaceId.ToString()));
                            }

                            MainWindow.Log("Response: Found {0} similar faces for face {1}", gg.Faces.Count, faceId);

                            FindSimilarCollection.Add(gg);
                        }
                        catch (FaceAPIException ex)
                        {
                            MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                        }
                    }
                }
            }
        }
        public void LoadNodes()
        {
            ClearNodes();

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter      = "XML Files (.xml)|*.xml|All Files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;

            openFileDialog1.Multiselect = true;

            // Call the ShowDialog method to show the dialog box.
            bool?userClickedOK = openFileDialog1.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == true)
            {
                List <SerializeableNodeViewModel> SerializeNodes = new List <SerializeableNodeViewModel>();

                string path = openFileDialog1.FileName;

                XmlSerializer ser = new XmlSerializer(typeof(List <SerializeableNodeViewModel>), new Type[] { typeof(SerializeableVariableNode), typeof(SerializeableConditionNode), typeof(SerializeableDynamicNode), typeof(SerializeableRootNode) });

                using (XmlReader reader = XmlReader.Create(path))
                {
                    SerializeNodes = (List <SerializeableNodeViewModel>)ser.Deserialize(reader);
                }

                //ADD NODES
                foreach (var serializeableNodeViewModel in SerializeNodes)
                {
                    if (serializeableNodeViewModel is SerializeableRootNode)
                    {
                        SerializeableRootNode rootSerialized = serializeableNodeViewModel as SerializeableRootNode;

                        RootNode newNode = new RootNode();
                        newNode.Populate(rootSerialized);

                        Nodes.Add(newNode);
                    }

                    if (serializeableNodeViewModel is SerializeableVariableNode)
                    {
                        SerializeableVariableNode variableSerialized = serializeableNodeViewModel as SerializeableVariableNode;

                        VariableNode newNode = new VariableNode();
                        newNode.Populate(variableSerialized);

                        Nodes.Add(newNode);
                    }

                    if (serializeableNodeViewModel is SerializeableDynamicNode)
                    {
                        SerializeableDynamicNode dynamicSerialized = serializeableNodeViewModel as SerializeableDynamicNode;

                        DynamicNode newNode = new DynamicNode();
                        newNode.Populate(dynamicSerialized);

                        Nodes.Add(newNode);
                    }

                    if (serializeableNodeViewModel is SerializeableConditionNode)
                    {
                        SerializeableConditionNode conSerialized = serializeableNodeViewModel as SerializeableConditionNode;

                        ConditionNode newNode = new ConditionNode();
                        newNode.Populate(conSerialized);

                        Nodes.Add(newNode);
                    }
                }
            }

            //Node Connections
            foreach (var node in Nodes)
            {
                if (node is RootNode)
                {
                    //Connect output
                    RootNode rootNode = node as RootNode;
                    if (rootNode.OutputConnector.ConnectionNodeID <= 0)
                    {
                        return;
                    }

                    //Connect this output to the connection's input
                    Connector connectedTo = GetInConnectorBasedOnNode(rootNode.OutputConnector.ConnectionNodeID);
                    Connector.ConnectPins(rootNode.OutputConnector, connectedTo);
                }

                if (node is ConditionNode)
                {
                    ConditionNode conNode = node as ConditionNode;

                    //bool value Input
                    if (conNode.boolInput.ConnectionNodeID > 0)
                    {
                        //we're connected to a parameter
                        Connector connectedToVar = GetOutConnectorBasedOnNode(conNode.boolInput.ConnectionNodeID); //variable
                        Connector.ConnectPins(conNode.boolInput, connectedToVar);
                    }

                    //Input
                    if (conNode.InExecutionConnector.ConnectionNodeID > 0)
                    {
                        Connector connectedTo = GetOutConnectorBasedOnNode(conNode.InExecutionConnector.ConnectionNodeID);
                        Connector.ConnectPins(conNode.InExecutionConnector, connectedTo);
                    }

                    //Ouput true
                    if (conNode.OutExecutionConnectorTrue.ConnectionNodeID > 0)
                    {
                        Connector connectedTo = GetInConnectorBasedOnNode(conNode.OutExecutionConnectorTrue.ConnectionNodeID);
                        Connector.ConnectPins(conNode.OutExecutionConnectorTrue, connectedTo);
                    }

                    //Ouput false
                    if (conNode.OutExecutionConnectorFalse.ConnectionNodeID > 0)
                    {
                        Connector connectedTo = GetInConnectorBasedOnNode(conNode.OutExecutionConnectorFalse.ConnectionNodeID);
                        Connector.ConnectPins(conNode.OutExecutionConnectorFalse, connectedTo);
                    }
                }

                if (node is DynamicNode)
                {
                    //Connect output
                    DynamicNode dynNode = node as DynamicNode;

                    //Connect parameters
                    for (int i = 0; i < dynNode.ArgumentCache.Count(); i++)
                    {
                        Argument arg = dynNode.ArgumentCache.ElementAt(i);

                        if (arg.ArgIsExistingVariable)
                        {
                            Connector conID          = dynNode.GetConnectorAtIndex(i);
                            int       connectedToVar = arg.ArgumentConnectedToNodeID;

                            Connector varConnect = GetOutConnectorBasedOnNode(connectedToVar);
                            Connector.ConnectPins(conID, varConnect);
                        }
                    }

                    if (dynNode.OutExecutionConnector.ConnectionNodeID > 0)
                    {
                        //Connect this output to the connection's input
                        Connector connectedTo = GetInConnectorBasedOnNode(dynNode.OutExecutionConnector.ConnectionNodeID);
                        Connector.ConnectPins(dynNode.OutExecutionConnector, connectedTo);
                        //No need to connect this in to the connection's output so far.
                    }
                }
            }
        }
示例#37
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp     = commandData.Application;
            UIDocument    uidoc     = uiapp.ActiveUIDocument;
            Application   app       = uiapp.Application;
            Document      doc       = uidoc.Document;
            ViewSet       myViewSet = new ViewSet();

            DWGExportOptions DwgOptions = new DWGExportOptions
            {
                ExportingAreas = false,
                MergedViews    = true
            };

            int       c_f               = 0;
            Selection SelectedObjs      = uidoc.Selection;
            ICollection <ElementId> ids = uidoc.Selection.GetElementIds();

            foreach (ElementId eid in ids)
            {
                try
                {
                    View view = doc.GetElement(eid) as View;
                    myViewSet.Insert(view);
                }
                catch { c_f += 1; }
            }
            List <ElementId> viewIds = new List <ElementId>();

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            Nullable <bool> result             = dlg.ShowDialog();

            if (result == true)
            {
                string path = dlg.FileName;
                path = path.Remove(dlg.FileName.LastIndexOf(@"\")) + "\\DWG";
                var    ToRename = new List <String>();
                string display  = "List of Views:";
                foreach (View View in myViewSet)
                {
                    viewIds.Add(View.Id);
                    String Filename = doc.Title.Replace(" ", "").Replace(".", "-") + "-" + View.Title.Replace(":", " -") + ".dwg";
                    ToRename.Add(Filename);
                    display = display + Environment.NewLine + View.Title;
                }
                if (ToRename.Count == 0)
                {
                    TaskDialog.Show("Exit", "No Selection to Export");
                    return(Result.Succeeded);
                }
                TaskDialog td = new TaskDialog("Exporting DWGs")
                {
                    MainInstruction  = ToRename.Count + " Views will be Exported to: " + path,
                    CommonButtons    = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.No,
                    VerificationText = "Compatibility mode (Autocad 2007)",
                    ExpandedContent  = display
                };
                if (c_f != 0)
                {
                    td.MainInstruction = td.MainInstruction + Environment.NewLine + c_f + " Selected item was not a view";
                }

                TaskDialogResult response = td.Show();
                if ((response != TaskDialogResult.Cancel) && (response != TaskDialogResult.No))
                {
                    if (td.WasVerificationChecked())
                    {
                        DwgOptions.FileVersion = ACADVersion.R2007;
                    }
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    doc.Export(path, "", viewIds, DwgOptions);

                    for (int i = 0; i < ToRename.Count; i++)
                    {
                        string renamed = path + "\\" + ToRename[i].Substring(ToRename[i].LastIndexOf(" - ") + 3);
                        if (File.Exists(renamed))
                        {
                            File.Delete(renamed);
                        }
                        File.Move(path + "\\" + ToRename[i], renamed);
                    }
                }
            }
            return(Result.Succeeded);
        }
示例#38
0
        private void OpenFile(object parameter)
        {
            string fileName;

            // If the parameter is null, then this request
            // is coming from the file menu.
            if (parameter == null)
            {
                var ofd = new OpenFileDialog
                {
                    InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                    Filter           = "xml files (*.xml)|*.xml",
                    RestoreDirectory = true
                };

                // Call the ShowDialog method to show the dialog box.
                var ok = ofd.ShowDialog();

                // Process input if the user clicked OK.
                if (ok != true)
                {
                    return;
                }

                fileName = ofd.FileName;
            }
            // Otherwise, the request is coming from the recent
            // files list.
            else
            {
                fileName = parameter.ToString();
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("The specified file no longer exists.");
                    return;
                }
            }

            // Clear the runner
            if (runner != null)
            {
                DeinitializeFileWatcher();
                RemoveEventHandlers();
                runner.Dispose();
                runner = null;
            }

            runner = Runner.Load(fileName);

            if (runner == null)
            {
                Console.WriteLine("Test session could not be opened.");
                runner = new Runner();
                return;
            }

            InitializeFileWatcher();

            InitializeEventHandlers();

            RaisePropertyChanged("");
            RaisePropertyChanged("SelectedProductIndex");

            SaveRecentFile(fileName);
        }
        // Displays the image and calls Detect Faces.

        private async void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            // Get the image file to scan from the user.
            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            // Return if canceled.
            if (!(bool)result)
            {
                return;
            }

            // Display the image file.
            string filePath = openDlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            FacePhoto.Source = bitmapSource;

            // Detect any faces in the image.
            Title = "Detecting...";
            faces = await UploadAndDetectFaces(filePath);

            Title = String.Format("Detection Finished. {0} face(s) detected", faces.Length);

            if (faces.Length > 0)
            {
                // Prepare to draw rectangles around the faces.
                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi = bitmapSource.DpiX;
                resizeFactor     = 96 / dpi;
                faceDescriptions = new String[faces.Length];

                for (int i = 0; i < faces.Length; ++i)
                {
                    Face face = faces[i];

                    // Draw a rectangle on the face.
                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(Brushes.Red, 2),
                        new Rect(
                            face.FaceRectangle.Left * resizeFactor,
                            face.FaceRectangle.Top * resizeFactor,
                            face.FaceRectangle.Width * resizeFactor,
                            face.FaceRectangle.Height * resizeFactor
                            )
                        );

                    // Store the face description.
                    faceDescriptions[i] = FaceDescription(face);
                }

                drawingContext.Close();

                // Display the image with the rectangle around the face.
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                FacePhoto.Source = faceWithRectBitmap;

                // Set the status bar text.
                faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description.";
            }
        }
示例#40
0
        private void btnAddFiles_Click(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt  = ".zip";
            dlg.Filter      = "Zip Archive (*.zip)|*.zip|JS archive files (*.js)|*.js";
            dlg.Multiselect = true;

            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                foreach (var item in dlg.FileNames)
                {
                    //if the file is not already present
                    if (item.EndsWith(".js") && !jsFiles.Any(file => file.Path == item))
                    {
                        jsFiles.Add(new JsFile()
                        {
                            Path          = item,
                            Selected      = false,
                            OriginZipFile = "",
                            Filename      = item.Substring(item.LastIndexOf('\\') + 1)
                        });
                    }

                    if (item.EndsWith(".zip"))
                    {
                        using (ZipFile zipArchive = ZipFile.Read(item))
                        {
                            foreach (ZipEntry jsFile in zipArchive)
                            {
                                if (jsFile.FileName.EndsWith(".js") && jsFile.FileName.Contains(@"data/js/tweets") && !jsFiles.Any(file => file.Path == jsFile.FileName))
                                {
                                    jsFiles.Add(new JsFile()
                                    {
                                        Path          = jsFile.FileName,
                                        Selected      = false,
                                        Filename      = jsFile.FileName.Substring(jsFile.FileName.LastIndexOf('/') + 1),
                                        OriginZipFile = item
                                    });
                                }
                            }
                        }
                    }
                }


                foreach (var item in jsFiles)
                {
                    int tmpYear  = -1;
                    int tmpMonth = -1;

                    if (System.Text.RegularExpressions.Regex.IsMatch(item.Filename, @"\d{4}_\d{2}\.js", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        if (!Int32.TryParse(item.Filename.Substring(0, "2013".Length), out tmpYear))
                        {
                            tmpYear = -1;
                        }

                        if (!Int32.TryParse(item.Filename.Substring(item.Filename.IndexOf('_') + 1, "01".Length), out tmpMonth))
                        {
                            tmpMonth = -1;
                        }

                        if (tmpMonth < 1 || tmpMonth > 12)
                        {
                            tmpMonth = -1;
                        }
                    }

                    item.TweetYear  = tmpYear;
                    item.TweetMonth = tmpMonth;

                    if (item.TweetMonth != -1)
                    {
                        item.FriendlyFilename = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.TweetMonth);
                    }
                    else
                    {
                        item.FriendlyFilename = item.Filename;
                    }

                    // If not from zip archive
                    if (String.IsNullOrEmpty(item.OriginZipFile))
                    {
                        item.FriendlyFilename += "<external>";
                    }
                }

                yearsOfTweets = jsFiles.GroupBy(jsFile => jsFile.TweetYear,
                                                jsFile => jsFile,
                                                (key, g) => new { Year = key, TweetJsFiles = g })
                                .Select(a => new YearOfTweets()
                {
                    Year         = a.Year,
                    TweetJsFiles = a.TweetJsFiles.ToList <JsFile>()
                });
            }

            if (jsFiles.Count < 1)
            {
                MessageBox.Show("No Twitter archive or *.js files were loaded!", "Twitter Archive Eraser", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            treeFiles.ItemsSource = yearsOfTweets;
        }
示例#41
0
 public ViewerCanvas()
     : base()
 {
     openFileDialog = new Microsoft.Win32.OpenFileDialog();
     saveFileDialog = new Microsoft.Win32.SaveFileDialog();
 }
示例#42
0
        private async void ChannelBtn_Click(object sender, RoutedEventArgs e)
        {
            string      tag         = ((Button)sender).Tag.ToString();
            ImageSource imageSource = null;

            OpenFileDialog file = new OpenFileDialog
            {
                Filter = Helpers.ImagesFilter()
            };

            file.ShowDialog();

            if (!String.IsNullOrEmpty(file.FileName))
            {
                MagickImage img = new MagickImage(file.FileName);
                if (!img.CheckGrayscale())
                {
                    await this.ShowMessageAsync("Error!", "This image isn't grayscale!");

                    return;
                }

                imageSource = new BitmapImage(new Uri(file.FileName));
            }

            switch (tag.ToLower())
            {
            case "r":
                _channelPaths[0] = file.FileName;
                redPath.Text     = file.FileName;
                if (imageSource != null)
                {
                    RedImage.Source = imageSource;
                }
                break;

            case "g":
                _channelPaths[1] = file.FileName;
                greenPath.Text   = file.FileName;
                if (imageSource != null)
                {
                    GreenImage.Source = imageSource;
                }
                break;

            case "b":
                _channelPaths[2] = file.FileName;
                bluePath.Text    = file.FileName;
                if (imageSource != null)
                {
                    BlueImage.Source = imageSource;
                }
                break;

            case "a":
                _channelPaths[3] = file.FileName;
                alphaPath.Text   = file.FileName;
                if (imageSource != null)
                {
                    AlphaImage.Source = imageSource;
                }
                break;

            default:
                throw new ArgumentException("How? Just... how?");
            }
        }
示例#43
0
        private void LoadGameSave_Execute()
        {
            SeatDataBlock.ResetSeats();

            string         saveDir = Path.Combine(Core.PlaySaveDir, "class");
            OpenFileDialog opfd    = new OpenFileDialog
            {
                AddExtension     = true,
                CheckFileExists  = true,
                Filter           = "Save Files (*.sav)|*.sav",
                InitialDirectory = saveDir
            };

            opfd.CustomPlaces.Add(new FileDialogCustomPlace(saveDir));
            if (!opfd.ShowDialog(this)
                .Value)
            {
                return;
            }

            CharacterCollection collection = DataContext as CharacterCollection;

            if (collection != null)
            {
                while (!collection.ViewModelProvider.Finish())
                {
                    MessageBoxResult msg = MessageBox.Show(MESSAGE_ERROR_FINISH_PROVIDER,
                                                           "Error",
                                                           MessageBoxButton.OKCancel,
                                                           MessageBoxImage.Hand);
                    if (msg == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
                collection.Dispose();
            }

            ICharacterViewModelProvider viewModelProvider = new SaveFileCharacterViewModelProvider(opfd.FileName);

            viewModelProvider.Initialize(this);

            viewModelProvider.CharacterLoaded += ViewModelProviderOnCharacterLoaded;
            CharacterCollection characterCollection = new CharacterCollection(Dispatcher, viewModelProvider);

            viewModelProvider.CharacterLoaded -= ViewModelProviderOnCharacterLoaded;
            SetTitle();
            DataContext = characterCollection;

            SortBox.SelectedValue           = viewModelProvider.DefaultSortProperty;
            OrderBox.SelectedValue          = viewModelProvider.DefaultSortDirection;
            CharactersControl.SelectedIndex = 0;

            characterCollection.Characters.ForEach
                (model =>
            {
                int seat = (int)model.ExtraData["PLAY_SEAT"];
                SeatDataBlock.SetSeat(seat, model.Profile.FullName);
                model.Character.PropertyChanged += (sender, args) =>
                {
                    if (!args.PropertyName.Contains("NAME"))
                    {
                        return;
                    }

                    string name = model.Profile.FullName;
                    SeatDataBlock.SetSeat(seat, name);
                };
            });
        }
示例#44
0
        private void OnMainFileOpenMenuClicked(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.Filter = FilterTxt + "|" +
                            FilterJson + "|" +
                            FilterXml + "|" +
                            FilterSoap + "|" +
                            FilterBinary + "|" +
                            FilterAny;

            dialog.FilterIndex = 1;

            bool?dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                string filePath = dialog.FileName;
                if (System.IO.File.Exists(filePath))
                {
                    string content = System.IO.File.ReadAllText(filePath);

                    // determine which format the user want to save as
                    if (dialog.FilterIndex == 1)
                    {
                        // read as txt
                        System.IO.StringReader reader = new System.IO.StringReader(content);
                        string          line          = reader.ReadLine();
                        System.DateTime lastSaved;
                        if (System.DateTime.TryParse(line, out lastSaved))
                        {
                            // we read the line, so remove the line
                            line = string.Empty;
                        }
                        else
                        {
                            lastSaved = System.DateTime.Now;
                        }

                        content = line + reader.ReadToEnd();
                        Models.TodoTask document = new Models.TodoTask(content);
                        document.LastSaved = lastSaved;
                        content            = document.Content;

                        reader.Dispose();
                    }
                    else if (dialog.FilterIndex == 2)
                    {
                        // read as JSON
                        string json = content;
                        // deserialize to expected type (Models.Document)
                        object jsonObject = Newtonsoft.Json
                                            .JsonConvert
                                            .DeserializeObject(json, typeof(Models.TodoTask));

                        Models.TodoTask document = new Models.TodoTask(content);


                        // cast and assign JSON object to expected type (Models.Document)

                        // assign content from deserialized Models.Document
                        content = document.Content;
                    }
                    else if (dialog.FilterIndex == 3)
                    {
                        // read as XML for type of Models.Document
                        System.Xml.Serialization.XmlSerializer serializer =
                            new System.Xml.Serialization.XmlSerializer(typeof(Models.TodoTask));

                        // convert content to byte array (sequence of bytes)
                        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                        // make stream from buffer
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to an object
                        object xmlObject = serializer.Deserialize(stream);
                        // cast and assign XML object to actual type object
                        Models.TodoTask document = (Models.TodoTask)xmlObject;

                        content = document.Content;
                        stream.Dispose();   // release the resources
                    }
                    else if (dialog.FilterIndex == 4)
                    {
                        // read as soap
                        System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
                            new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();

                        // convert content to byte array (sequence of bytes)
                        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                        // make stream from buffer
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to an object
                        object soapObject = serializer.Deserialize(stream);
                        // cast and assign SOAP object to actual type object
                        Models.TodoTask document = (Models.TodoTask)soapObject;
                        // read content
                        content = document.Content;

                        stream.Dispose();   // release the resources
                    }

                    else if (dialog.FilterIndex == 5)
                    {
                        // read as binary
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
                            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                        // reading and writing binary data directly as string has issues, try not to do it
                        byte[] buffer = Convert.FromBase64String(content);
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to object
                        object binaryObject = serializer.Deserialize(stream);
                        // assign binary object to actual type object
                        Models.TodoTask document = (Models.TodoTask)binaryObject;
                        // read the content
                        content = document.Content;
                        stream.Dispose();   // release the resources
                    }
                    else // imply this is any file
                    {
                        // read as is
                    }

                    // assign content to UI control
                    TodoTaskNameText.Text = content;
                }
            }
        }
示例#45
0
        /// <summary>
        /// Pick image for face detection and set detection result to result container
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event argument</param>
        private async void Beard_Click(object sender, RoutedEventArgs e)
        {
            // Show file picker dialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".jpg";
            dlg.Filter     = "Image files (*.jpg, *.png, *.bmp, *.gif) | *.jpg; *.png; *.bmp; *.gif";
            var result = dlg.ShowDialog();

            if (result.HasValue && result.Value)
            {
                // User picked one image
                var pickedImagePath = dlg.FileName;
                var renderingImage  = UIHelper.LoadImageAppliedOrientation(pickedImagePath);
                var imageInfo       = UIHelper.GetImageInfoForRendering(renderingImage);
                SelectedFile = renderingImage;

                // Clear last detection result
                ResultCollection.Clear();
                DetectedFaces.Clear();
                DetectedResultsInText = string.Format("Detecting...");

                MainWindow.Log("Request: Detecting {0}", pickedImagePath);
                var sw = Stopwatch.StartNew();



                // Call detection REST API
                using (var fStream = File.OpenRead(pickedImagePath))
                {
                    try
                    {
                        MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
                        string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;
                        string     endpoint        = mainWindow._scenariosControl.SubscriptionEndpoint;

                        var faceServiceClient = new FaceServiceClient(subscriptionKey, endpoint);
                        ProjectOxford.Face.Contract.Face[] faces = await faceServiceClient.DetectAsync(fStream, false, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.HeadPose, FaceAttributeType.FacialHair, FaceAttributeType.Emotion, FaceAttributeType.Hair, FaceAttributeType.Makeup, FaceAttributeType.Occlusion, FaceAttributeType.Accessories, FaceAttributeType.Noise, FaceAttributeType.Exposure, FaceAttributeType.Blur });

                        MainWindow.Log("Response: Success. Detected {0} face(s) in {1}", faces.Length, pickedImagePath);

                        DetectedResultsInText = string.Format("{0} face(s) has been detected", faces.Length);


                        //Create Image type
                        Image renderingImage_img = Image.FromFile(dlg.FileName);
                        foreach (var face in faces)
                        {
                            // add Glasses to face

                            string.Format("GlassesType: {0}", face.FaceAttributes.FacialHair.Beard.ToString());


                            if (face.FaceAttributes.FacialHair.Beard >= 0 && face.FaceAttributes.FacialHair.Beard <= 0.4)
                            {
                                // Gan kinh len
                                renderingImage_img = Add_Beard(renderingImage_img, face);
                                //ImageGlassesDisplay.Source = (BitmapImage)renderingImage_bit;
                            }
                        }
                        renderingImage_img.Save("F:\\study\\Project\\New pj\\Cognitive-Face-Windows\\Images\\Beard\\" + saveImage_Count.ToString() + ".jpg");
                        BitmapImage DisplayImage = new BitmapImage(new Uri("F:\\study\\Project\\New pj\\Cognitive-Face-Windows\\Images\\Beard\\" + saveImage_Count.ToString() + ".jpg"));
                        ImageBeardDisplay.Source = DisplayImage;
                        saveImage_Count++;



                        // Convert detection result into UI binding object for rendering
                        foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSizes, imageInfo))
                        {
                            ResultCollection.Add(face);
                        }
                    }
                    catch (FaceAPIException ex)
                    {
                        MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                        GC.Collect();
                        return;
                    }
                    GC.Collect();
                }
            }
        }
示例#46
0
        private void BtnBrowseAttachment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((DgridSupportTickets.SelectedItem as Support_Ticket)._Status.Equals("CLOSED", StringComparison.OrdinalIgnoreCase))
                {
                    MessageBox.Show("Access Denied. Support Ticket is already CLOSED.", "CSF TICKETING");
                    return;
                }

                var ofd = new Microsoft.Win32.OpenFileDialog()
                {
                    Filter      = "All Files (*.*)|*.*",
                    Title       = "CSF TICKETING",
                    Multiselect = true
                };

                if (ofd.ShowDialog() == true)
                {
                    var X = new System.IO.FileInfo(ofd.FileName).Length;
                    X /= 1024; X /= 1024; // will return size in MB

                    /// CHECK FILE SIZE
                    if (X > Pub.MaxFileSize_Attachment())
                    {
                        throw new Exception(string.Format("Max File Size of Attachments is {0} MB", Pub.MaxFileSize_Attachment().ToString()));
                    }

                    List <string> _s = new List <string>();
                    foreach (string _path in ofd.FileNames)
                    {
                        var _filename = System.IO.Path.GetFileName(_path);
                        var x         = false;
                        foreach (ComboBoxItem cboitem in CboAttachments.Items)
                        {
                            if (_filename.Equals(cboitem.Content.ToString(), StringComparison.OrdinalIgnoreCase))
                            {
                                MessageBox.Show("Attachment already exists : " + _filename + Environment.NewLine + "Please remove the previous attachment first.", "CSF TICKETING", MessageBoxButton.OK, MessageBoxImage.Warning);
                                x = true;
                                break;
                            }
                            else
                            {
                                x = false;
                                break;
                            }
                        }

                        if (x == false)
                        {
                            _s.Add(_path);
                        }
                    }

                    foreach (string s in _s)
                    {
                        if (!System.IO.File.Exists(s))
                        {
                            throw new Exception(null);
                        }
                        ComboBoxItem cboitem = new ComboBoxItem()
                        {
                            Content = System.IO.Path.GetFileName(s), Tag = s, ToolTip = s
                        };
                        CboAttachments.Items.Add(cboitem);
                    }
                }
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    MessageBox.Show("Error : " + ex.Message, "CSF TICKETING", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                return;
            }
        }
示例#47
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == ButtonExport)
            {
                this.Result = this.ThisToPreset();
                ControlClosed?.Invoke();
            }

            if (sender == ButtonResize)
            {
                if (!int.TryParse("" + TextBoxNumRows.Text, out int irows) ||
                    !int.TryParse("" + TextBoxNumCols.Text, out int icols))
                {
                    return;
                }

                this.rows = Math.Max(1, irows);
                this.cols = Math.Max(1, icols);

                AdaptRowsCols(GridOuterHeader, textBoxesHeader, this.rows, this.cols);
                AdaptRowsCols(GridOuterElements, textBoxesElements, this.rows, this.cols);
            }

            if (sender == ButtonSavePreset)
            {
                // choose filename
                var dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName   = "new.json";
                dlg.DefaultExt = "*.json";
                dlg.Filter     = "Preset JSON file (*.json)|*.json|All files (*.*)|*.*";

                // save
                if (true == dlg.ShowDialog())
                {
                    try
                    {
                        var pr = this.ThisToPreset();
                        pr.SaveToFile(dlg.FileName);
                    }
                    catch (Exception ex)
                    {
                        AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex);
                    }
                }
            }

            if (sender == ButtonLoadPreset)
            {
                // choose filename
                var dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName   = "new.json";
                dlg.DefaultExt = "*.json";
                dlg.Filter     = "Preset JSON file (*.json)|*.json|All files (*.*)|*.*";

                // save
                if (true == dlg.ShowDialog())
                {
                    try
                    {
                        var pr = ExportTableRecord.LoadFromFile(dlg.FileName);
                        this.ThisFromPreset(pr);
                    }
                    catch (Exception ex)
                    {
                        AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex);
                    }
                }
            }
        }
        /// <summary>
        /// Pick image and call find similar with both two modes for each faces detected
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FindSimilar_Click(object sender, RoutedEventArgs e)
        {
            // Show file picker
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".jpg";
            dlg.Filter     = "Image files (*.jpg, *.png, *.bmp, *.gif) | *.jpg; *.png; *.bmp; *.gif";
            var filePicker = dlg.ShowDialog();

            if (filePicker.HasValue && filePicker.Value)
            {
                // User picked image
                // Clear previous detection and find similar results
                TargetFaces.Clear();
                FindSimilarMatchPersonCollection.Clear();
                FindSimilarMatchFaceCollection.Clear();
                var sw = Stopwatch.StartNew();

                var pickedImagePath = dlg.FileName;
                var renderingImage  = UIHelper.LoadImageAppliedOrientation(pickedImagePath);
                var imageInfo       = UIHelper.GetImageInfoForRendering(renderingImage);
                SelectedFile = renderingImage;

                // Detect all faces in the picked image
                using (var fStream = File.OpenRead(pickedImagePath))
                {
                    MainWindow.Log("Request: Detecting faces in {0}", SelectedFile);

                    MainWindow mainWindow        = Window.GetWindow(this) as MainWindow;
                    string     subscriptionKey   = mainWindow._scenariosControl.SubscriptionKey;
                    string     endpoint          = mainWindow._scenariosControl.SubscriptionEndpoint;
                    var        faceServiceClient = new FaceServiceClient(subscriptionKey, endpoint);
                    var        faces             = await faceServiceClient.DetectAsync(fStream);

                    // Update detected faces on UI
                    foreach (var face in UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo))
                    {
                        TargetFaces.Add(face);
                    }

                    MainWindow.Log("Response: Success. Detected {0} face(s) in {1}", faces.Length, SelectedFile);

                    // Find two modes similar faces for each face
                    foreach (var f in faces)
                    {
                        var faceId = f.FaceId;

                        MainWindow.Log("Request: Finding similar faces in Personal Match Mode for face {0}", faceId);

                        try
                        {
                            // Default mode, call find matchPerson similar REST API, the result contains all the face ids which is personal similar to the query face
                            const int requestCandidatesCount = 4;
                            var       result = await faceServiceClient.FindSimilarAsync(faceId, largeFaceListId : this._largeFaceListId, maxNumOfCandidatesReturned : requestCandidatesCount);

                            // Update find matchPerson similar results collection for rendering
                            var personSimilarResult = new FindSimilarResult();
                            personSimilarResult.Faces     = new ObservableCollection <Face>();
                            personSimilarResult.QueryFace = new Face()
                            {
                                ImageFile = SelectedFile,
                                Top       = f.FaceRectangle.Top,
                                Left      = f.FaceRectangle.Left,
                                Width     = f.FaceRectangle.Width,
                                Height    = f.FaceRectangle.Height,
                                FaceId    = faceId.ToString(),
                            };
                            foreach (var fr in result)
                            {
                                var  candidateFace = FacesCollection.First(ff => ff.FaceId == fr.PersistedFaceId.ToString());
                                Face newFace       = new Face();
                                newFace.ImageFile  = candidateFace.ImageFile;
                                newFace.Confidence = fr.Confidence;
                                newFace.FaceId     = candidateFace.FaceId;
                                personSimilarResult.Faces.Add(newFace);
                            }

                            MainWindow.Log("Response: Found {0} similar faces for face {1}", personSimilarResult.Faces.Count, faceId);

                            FindSimilarMatchPersonCollection.Add(personSimilarResult);
                        }
                        catch (FaceAPIException ex)
                        {
                            MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                        }

                        try
                        {
                            // Call find facial match similar REST API, the result faces the top N with the highest similar confidence
                            const int requestCandidatesCount = 4;
                            var       result = await faceServiceClient.FindSimilarAsync(faceId, largeFaceListId : this._largeFaceListId, mode : FindSimilarMatchMode.matchFace, maxNumOfCandidatesReturned : requestCandidatesCount);

                            // Update "matchFace" similar results collection for rendering
                            var faceSimilarResults = new FindSimilarResult();
                            faceSimilarResults.Faces     = new ObservableCollection <Face>();
                            faceSimilarResults.QueryFace = new Face()
                            {
                                ImageFile = SelectedFile,
                                Top       = f.FaceRectangle.Top,
                                Left      = f.FaceRectangle.Left,
                                Width     = f.FaceRectangle.Width,
                                Height    = f.FaceRectangle.Height,
                                FaceId    = faceId.ToString(),
                            };
                            foreach (var fr in result)
                            {
                                var  candidateFace = FacesCollection.First(ff => ff.FaceId == fr.PersistedFaceId.ToString());
                                Face newFace       = new Face();
                                newFace.ImageFile  = candidateFace.ImageFile;
                                newFace.Confidence = fr.Confidence;
                                newFace.FaceId     = candidateFace.FaceId;
                                faceSimilarResults.Faces.Add(newFace);
                            }

                            MainWindow.Log("Response: Found {0} similar faces for face {1}", faceSimilarResults.Faces.Count, faceId);

                            FindSimilarMatchFaceCollection.Add(faceSimilarResults);
                        }
                        catch (FaceAPIException ex)
                        {
                            MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                        }
                    }
                }
            }
            GC.Collect();
        }
示例#49
0
        private void UserMap()
        {
            using (LogBlock logblock = Log.NotTracing() ? null : new LogBlock(GetType() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name))
            {
                ScheduleViewModel scheduleViewModel = ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]);
                bool bCSV = false;

                Microsoft.Win32.OpenFileDialog fDialog = new Microsoft.Win32.OpenFileDialog();
                fDialog.Filter          = "User Map Files|*.csv";
                fDialog.CheckFileExists = true;
                fDialog.Multiselect     = false;

                // string delimiter = ",";
                // /
                // Domain information is stored in the xml and not in  the usermap.
                // will have to revisit

                System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(Config));
                if (File.Exists(scheduleViewModel.GetConfigFile()))
                {
                    System.IO.StreamReader fileRead = new System.IO.StreamReader(scheduleViewModel.GetConfigFile());

                    Config Z11 = new Config();
                    Z11 = (Config)reader.Deserialize(fileRead);
                    fileRead.Close();

                    CSVDelimiter = Z11.AdvancedImportOptions.CSVDelimiter;
                    if (CSVDelimiter == null)
                    {
                        CSVDelimiter = ",";
                    }

                    ZimbraDomain = Z11.UserProvision.DestinationDomain;
                    if (DomainList.Count > 0)
                    {
                        CurrentDomainSelection = (ZimbraDomain == null) ? 0 : DomainList.IndexOf(ZimbraDomain);
                    }
                    else
                    {
                        DomainList.Add(ZimbraDomain);
                    }
                }

                if (fDialog.ShowDialog() == true)
                {
                    int lastDot = fDialog.FileName.LastIndexOf(".");
                    if (lastDot != -1)
                    {
                        string substr = fDialog.FileName.Substring(lastDot, 4);
                        if (substr == ".csv")
                        {
                            bCSV = true;

                            /*try
                            * {
                            *  string names = File.ReadAllText(fDialog.FileName);
                            *  string[] nameTokens = names.Split(',');
                            *  foreach (string name in nameTokens)
                            *  {
                            *      UsersList.Add(name);
                            *      scheduleViewModel.SchedList.Add(name);
                            *  }
                            * }
                            * catch (IOException ex)
                            * {
                            *  MessageBox.Show(ex.Message, "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                            * }*/
                            List <string[]> parsedData = new List <string[]>();
                            try
                            {
                                if (File.Exists(fDialog.FileName))
                                {
                                    using (StreamReader readFile = new StreamReader(fDialog.FileName))
                                    {
                                        string line;

                                        string[] row;
                                        while ((line = readFile.ReadLine()) != null)
                                        {
                                            row = line.Split(CSVDelimiter.ToCharArray());
                                            //row = line.Split(',');
                                            parsedData.Add(row);
                                        }
                                        readFile.Close();
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("There is no user information stored.Please enter some user info", "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                            }
                            catch (Exception e)
                            {
                                string message = e.Message;
                            }

                            {
                                string[] strres = new string[parsedData.Count];

                                Users tempuser = new Users(); // Misnomer: This is actually a single user

                                try
                                {
                                    for (int j = 0; j < parsedData.Count; j++)
                                    {
                                        bool bFoundSharp = false;
                                        strres = parsedData[j];

                                        Log.info(strres);

                                        // Find header row (contains #)
                                        int num = strres.Count();
                                        for (int k = 0; k < num; k++)
                                        {
                                            if (strres[k].Contains("#"))
                                            {
                                                bFoundSharp = true;
                                                break;
                                            }
                                        }

                                        if (!bFoundSharp) // FBS bug 71933 -- 3/21/12
                                        {
                                            // This must be a non-header row

                                            tempuser.UserName   = strres[0];
                                            tempuser.MappedName = strres[1];
                                            tempuser.ChangePWD  = Convert.ToBoolean(strres[2]);
                                            // tempuser.PWDdefault = strres[3];

                                            // string result = tempuser.UserName + "," + tempuser.MappedName +"," + tempuser.ChangePWD + "," + tempuser.PWDdefault;
                                            string result = tempuser.Username + CSVDelimiter /*","*/ + tempuser.MappedName;

                                            Username   = strres[0];
                                            MappedName = strres[1];

                                            UsersViewModel uvm = new UsersViewModel(Username, MappedName);
                                            uvm.MustChangePassword = tempuser.ChangePWD;
                                            UsersList.Add(uvm);

                                            scheduleViewModel.SchedList.Add(new SchedUser(Username, false));
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("Incorrect .csv file format", "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }

                                EnableNext = (UsersList.Count > 0);
                            }

                            scheduleViewModel.EnableMigrate = (scheduleViewModel.SchedList.Count > 0);
                            scheduleViewModel.EnablePreview = scheduleViewModel.EnableMigrate;


                            // Domain information is stored in the xml and not in the usermap.
                            // will have to revisit

                            /* System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof (Config));
                             * if (File.Exists(scheduleViewModel.GetConfigFile()))
                             * {
                             *   System.IO.StreamReader fileRead = new System.IO.StreamReader( scheduleViewModel.GetConfigFile());
                             *
                             *   Config Z11 = new Config();
                             *                           Z11 = (Config)reader.Deserialize(fileRead);
                             *   fileRead.Close();
                             * }*/

                            /* {
                             *   ZimbraDomain = Z11.UserProvision.DestinationDomain;
                             *   if (DomainList.Count > 0)
                             *       CurrentDomainSelection = (ZimbraDomain == null) ? 0 : DomainList.IndexOf(ZimbraDomain);
                             *   else
                             *       DomainList.Add(ZimbraDomain);
                             * }*/

                            scheduleViewModel.SetUsermapFile(fDialog.FileName);
                        }
                    }
                    if (!bCSV)
                    {
                        MessageBox.Show("Only CSV files are supported", "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                }
            }
        }
示例#50
0
        private void WIZARD_PageChanged(object sender, RoutedEventArgs e)
        {
            if (WIZARD.CurrentPage == WIZARDPAGE_SettingsSummary)
            {
                string strEncryptionType = null;

                if (CHECK_ProtectPassword.IsChecked == true)
                {
                    strEncryptionType = "Password";
                }

                if (CHECK_ProtectWindows.IsChecked == true)
                {
                    if (strEncryptionType != null)
                    {
                        strEncryptionType += "\n";
                    }
                    else
                    {
                        strEncryptionType = "";
                    }

                    strEncryptionType += (RADIO_ProtectLocalMachine.IsChecked == true)
                        ? "Locked to local machine (" + TEXTBLOCK_LocalMachine.Text + ")" : "Locked to current user (" + TEXTBLOCK_CurrentUser.Text + ")";
                }

                if (strEncryptionType == null)
                {
                    LABEL_EncryptionType.IsEnabled = false;
                    LABEL_EncryptionType.Content   = "(None)";
                }
                else
                {
                    LABEL_EncryptionType.IsEnabled = true;
                    LABEL_EncryptionType.Content   = strEncryptionType;
                }

                if (String.IsNullOrWhiteSpace(TEXT_FriendlyName.Text))
                {
                    LABEL_FriendlyName.IsEnabled = false;
                    LABEL_FriendlyName.Content   = "(Serial will be used)";
                }
                else
                {
                    LABEL_FriendlyName.IsEnabled = true;
                    LABEL_FriendlyName.Content   = TEXT_FriendlyName.Text.Trim();
                }
            }
            else if (WIZARD.CurrentPage == WIZARDPAGE_Progress)
            {
                encryptionType = AuthAPI.Security.EncryptionProvider.EncryptionType.None;

                if (CHECK_ProtectPassword.IsChecked == true)
                {
                    userPassword    = TEXT_Password.Text;
                    encryptionType |= AuthAPI.Security.EncryptionProvider.EncryptionType.Password;
                }

                if (CHECK_ProtectWindows.IsChecked == true)
                {
                    encryptionType |= (RADIO_ProtectLocalMachine.IsChecked == true)
                        ? AuthAPI.Security.EncryptionProvider.EncryptionType.LocalMachine : AuthAPI.Security.EncryptionProvider.EncryptionType.LocalUser;
                }

                if (!String.IsNullOrWhiteSpace(TEXT_FriendlyName.Text))
                {
                    authenticatorName = TEXT_FriendlyName.Text.Trim();
                }

                bgWorker.RunWorkerAsync();
            }
            else if (WIZARD.CurrentPage == WIZARDPAGE_SelectFile)
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.CheckFileExists = true;

                dlg.Title      = "Select Authenticator";
                dlg.DefaultExt = ".bma";                                       // Default file extension
                dlg.Filter     = "WinBMA Exported Authenticator (.bma)|*.bma"; // Filter files by extension

                // Show open file dialog box
                Nullable <bool> result = dlg.ShowDialog();

                // Process open file dialog box results
                if (result == true)
                {
                    // Open document
                    string filename = dlg.FileName;

                    newAuthenticator = AuthAPI.Authenticator.FromFile(filename);

                    if (newAuthenticator == null)
                    {
                        this.Close();
                        return;
                    }

                    if (!this.DecryptAuthenticator())
                    {
                        this.Close();
                        return;
                    }

                    TEXT_FriendlyName.Text = newAuthenticator.Name;
                    WIZARD.CurrentPage     = WIZARDPAGE_Protect;
                }
                else
                {
                    this.Close();
                }
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file
            dlg.DefaultExt = ".txt";
            dlg.Filter     = "Text Files (*.txt)|*.txt";


            Nullable <bool> result = dlg.ShowDialog();


            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                searchBox.Text = filename;


                // Used to debug the sensor sensitivity
                int sensor_sensitivity;
                try
                {
                    // Range of 1 - 6
                    if (Int32.Parse(sensSensivity.Text) > 0 && Int32.Parse(sensSensivity.Text) <= 6)
                    {
                        sensor_sensitivity = Int32.Parse(sensSensivity.Text);
                    }
                    else
                    {
                        // Invalid
                        MessageBox.Show("Sensitivity range is 1 - 6, sensitivity has been set to 2 (default)", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation, MessageBoxResult.OK);
                        sensor_sensitivity = 2;
                        sensSensivity.Text = "2";
                    }
                }
                catch (System.FormatException)
                {
                    // Error
                    MessageBox.Show("Single number only, sensitivity has been set to 2 (default)", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation, MessageBoxResult.OK);
                    sensor_sensitivity = 2;
                    sensSensivity.Text = "2";
                }

                // Create object with all data given in parameters
                Sensor_Data dataSet = new Sensor_Data(Read_textData(filename), sensor_sensitivity);

                // Load in Ambient temperatures
                leftSensorAmbient.Text  = dataSet.Left_Sensor_Ambient.ToString() + "°C";
                rightSensorAmbient.Text = dataSet.Right_Sensor_Ambient.ToString() + "°C";

                // Clear datagrid if new text file is loaded
                leftSensorGrid.Items.Clear();
                rightSensorGrid.Items.Clear();

                id = 1;
                // Load in type data, highest and average temperatures (Left sensor)
                for (int i = 0; i < dataSet.CarData.Left_Wheel_Logs.Count; i++)
                {
                    Wheel_Data current = dataSet.CarData.Left_Wheel_Logs[i];
                    current.Id = GenerateId();
                    leftSensorGrid.Items.Add(current);
                }
                id = 1;
                // Load in type data, highest and average temperatures (right sensor)
                for (int i = 0; i < dataSet.CarData.Right_Wheel_Logs.Count; i++)
                {
                    Wheel_Data current = dataSet.CarData.Right_Wheel_Logs[i];
                    current.Id = GenerateId();
                    rightSensorGrid.Items.Add(current);
                }
            }
        }
示例#52
0
        private void LoadImagesAndSynthesis(object sender, RoutedEventArgs e)
        {
            if (titleTextList == null || titleTextList.Count <= 0)
            {
                MessageBox.Show("最初に、テキストをプレビューし、位置決めを確定してください", "メッセージ", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            string pictureFilePath = string.Empty;

            Microsoft.Win32.OpenFileDialog dlg = null;
            Nullable <bool> result             = false;

            // ファイルを開くダイアログ
            dlg = new Microsoft.Win32.OpenFileDialog();
            //dlg.DefaultExt = ".jpg";
            dlg.Filter      = "画像ファイル(jpg;gif;png)|*.jpg;*.jpeg;*.gif;*.png|すべてのファイル(*.*)|*.*";
            dlg.Multiselect = true;
            result          = dlg.ShowDialog();
            if (result == null || result == false)
            {
                MessageBox.Show("ファイルが選択されていません", "メッセージ", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            string outputDirectory = Path.GetDirectoryName(dlg.FileNames[0]) + "\\output";

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            foreach (var fileName in dlg.FileNames)
            {
                // Get output file name
                string outputFileName = outputDirectory + "\\" + Path.GetFileName(fileName);

                // Load targeted image
                BitmapImage bitmapImageTarget = new BitmapImage();
                bitmapImageTarget.BeginInit();
                bitmapImageTarget.CacheOption = BitmapCacheOption.OnLoad;
                FileStream stream = File.OpenRead(fileName);
                bitmapImageTarget.StreamSource = stream;
                bitmapImageTarget.EndInit();
                stream.Close();

                // Load base image
                Uri fileUri = new Uri(cImageUri, UriKind.Relative);
                var info    = Application.GetResourceStream(fileUri);

                BitmapImage bitmapImageBase = new BitmapImage();
                bitmapImageBase.BeginInit();
                bitmapImageBase.CacheOption  = BitmapCacheOption.OnLoad;
                bitmapImageBase.StreamSource = info.Stream;
                bitmapImageBase.EndInit();

                // Combine target and base images
                var drawingVisual  = new DrawingVisual();
                var drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawImage(bitmapImageBase,
                                         new Rect(0, 0, bitmapImageBase.PixelWidth, bitmapImageBase.PixelHeight));

                double       scale = (double)bitmapImageBase.PixelWidth / (double)bitmapImageTarget.PixelWidth;
                BitmapSource scaledBitmapSource = new TransformedBitmap(bitmapImageTarget, new ScaleTransform(scale, scale));

                drawingContext.DrawImage(scaledBitmapSource,
                                         new Rect(0, 0, scaledBitmapSource.PixelWidth, scaledBitmapSource.PixelHeight));

                // Adjust height of text area
                double adjustedYPos = (scaledBitmapSource.PixelHeight - heightOfImage) / 2;

                // Draw all texts.
                foreach (var titleText in titleTextList)
                {
                    drawingContext.DrawText(
                        new FormattedText(
                            titleText.Text,
                            CultureInfo.CurrentCulture,
                            FlowDirection.LeftToRight,
                            new Typeface(new FontFamily(titleText.FontName), FontStyles.Normal, titleText.FontWeight, FontStretches.Normal),
                            titleText.FontSize,
                            Brushes.Black
                            ),
                        new Point(titleText.XPos, titleText.YPos + adjustedYPos)
                        );
                }

                drawingContext.Close();
                var rtb = new RenderTargetBitmap((int)bitmapImageBase.PixelWidth, (int)bitmapImageBase.PixelHeight, 96, 96, PixelFormats.Pbgra32);
                rtb.Render(drawingVisual);

                // Output image files
                using (var fs = new FileStream(outputFileName, FileMode.Create))
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(rtb));
                    encoder.Save(fs);
                }
            }

            MessageBox.Show("画像合成が終了しました" + Environment.NewLine
                            + $"出力先:{outputDirectory}", "メッセージ", MessageBoxButton.OK, MessageBoxImage.Information);
        }
示例#53
0
        private void InputSplitFileButtonClick(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog()
            {
                Filter          = "CSV Files (*.csv)|*.csv|Text Files (*.txt)|*.txt",
                CheckFileExists = true,
                DefaultExt      = "*.csv",
                Multiselect     = false,
                ShowReadOnly    = true,
                Title           = "Open input CSV file"
            };

            bool?result = ofd.ShowDialog();

            if (!(result ?? false))
            {
                return;
            }
            fileInfo   = new FileInfo(ofd.FileName);
            totalLines = 0;

            StringBuilder sb = new StringBuilder();

            using (StreamReader readed = new StreamReader(fileInfo.FullName))
            {
                string line = null;

                while ((line = readed.ReadLine()) != null)
                {
                    if (totalLines <= 50)
                    {
                        sb.AppendLine(line);
                    }
                    totalLines++;
                }
            }
            FileName.Content         = fileInfo.FullName;
            FileSizeText.Text        = $"{fileInfo.Length}";
            LinesCountText.Text      = $"{totalLines}";
            OutputFolderName.Content = fileInfo.DirectoryName;
            if (totalLines > 1)
            {
                SplitEvery.Text       = (totalLines / 2).ToString();
                SplitButton.IsEnabled = true;
            }
            else
            {
                SplitEvery.Text       = "0";
                SplitButton.IsEnabled = false;
            }
            if (totalLines > 0)
            {
                TextPreview.Text             = sb.ToString();
                FilesSplitNumber.Text        = (totalLines > 2 ? 2 : 1).ToString();
                ExtractRequiredRowsFrom.Text = "1";
                ExtractRequiredRowsTo.Text   = totalLines.ToString();
            }
            else
            {
                TextPreview.Text             = string.Empty;
                FilesSplitNumber.Text        = "0";
                ExtractRequiredRowsFrom.Text = "0";
                ExtractRequiredRowsTo.Text   = "0";
            }
            Log($"File {fileInfo.FullName} is selected");
        }
        private void btnValidar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string mensajeFinal     = string.Empty;
                string directorioActual = Directory.GetCurrentDirectory();

                XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
                //xmlSchemaSet.Add(null, "..\\..\\..\\Common\\Validation\\UBL-Invoice-2.1.xsd");
                xmlSchemaSet.Add(null, "..\\..\\..\\Common\\Validation\\UBL-CreditNote-2.1.xsd");

                Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
                openFileDialog.Multiselect = false;
                openFileDialog.Filter      = "XML de documentos|*.xml|Todos los archivos|*.*";
                openFileDialog.DefaultExt  = "*.xml";
                openFileDialog.Title       = "Selección de XML de documentos electrónicos";

                Nullable <bool> dialogOk = openFileDialog.ShowDialog();
                string          ruta     = string.Empty;

                if (dialogOk == true)
                {
                    ruta = openFileDialog.FileName;
                }

                XDocument document         = XDocument.Load(@ruta);
                bool      validationErrors = false;
                document.Validate(xmlSchemaSet, (s, ev) => { mensajeFinal = ev.Message; validationErrors = true; });

                if (validationErrors)
                {
                    mensajeFinal += mensajeFinal + "errores";
                }
                else
                {
                    mensajeFinal += mensajeFinal + "sin errores";
                }

                CustomDialogWindow customDialogWindow = new CustomDialogWindow();
                customDialogWindow.Buttons            = CustomDialogButtons.OK;
                customDialogWindow.Caption            = "Detalle";
                customDialogWindow.DefaultButton      = CustomDialogResults.OK;
                customDialogWindow.InstructionHeading = "Resultados de la descarga del documento(s)";
                customDialogWindow.InstructionIcon    = CustomDialogIcons.Information;
                customDialogWindow.InstructionText    = mensajeFinal;
                CustomDialogResults customDialogResults = customDialogWindow.Show();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"No se ha podido realizar la inspección del documento mediante XSD, detalle del error{ex}",
                                               "Error inesperado", MessageBoxButton.OK, MessageBoxImage.Error);
                var msg = string.Concat(ex.InnerException?.Message, ex.Message);
                data_Log = new Data_Log()
                {
                    DetalleError   = $"Detalle del error: {msg}",
                    Comentario     = "Error al enviar el documento a sunat desde la interfaz",
                    IdUser_Empresa = data_Usuario.IdUser_Empresa
                };
                data_Log.Create_Log();
            }
        }
        private async void LoadImageButton_Click(object sender, RoutedEventArgs e)
        {
            MainWindow window = (MainWindow)Application.Current.MainWindow;

            Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(window);

            if (!(bool)result)
            {
                return;
            }

            string imageFilePath = openDlg.FileName;
            Uri    fileUri       = new Uri(imageFilePath);

            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            _emotionDetectionUserControl.ImageUri = fileUri;
            _emotionDetectionUserControl.Image    = bitmapSource;

            //
            // Create EmotionServiceClient and detect the emotion with URL
            //
            window.ScenarioControl.ClearLog();
            _detectionStatus.Text = "Detecting...";

            Emotion[] emotionResult = await UploadAndDetectEmotions(imageFilePath);

            _detectionStatus.Text = "Detection Done";

            //
            // Log detection result in the log window
            //
            window.Log("");
            window.Log("Detection Result:");
            window.LogEmotionResult(emotionResult);

            _emotionDetectionUserControl.Emotions = emotionResult;
            //            var success = await System.Windows.Launcher.LaunchUriAsync(uri);

            //resultDisplay[0] = new EmotionResultDisplay { EmotionString = "Anger", Score = emotion.Scores.Anger };
            //resultDisplay[1] = new EmotionResultDisplay { EmotionString = "Contempt", Score = emotion.Scores.Contempt };
            //resultDisplay[2] = new EmotionResultDisplay { EmotionString = "Disgust", Score = emotion.Scores.Disgust };
            //resultDisplay[3] = new EmotionResultDisplay { EmotionString = "Fear", Score = emotion.Scores.Fear };
            //resultDisplay[4] = new EmotionResultDisplay { EmotionString = "Happiness", Score = emotion.Scores.Happiness };
            //resultDisplay[5] = new EmotionResultDisplay { EmotionString = "Neutral", Score = emotion.Scores.Neutral };
            //resultDisplay[6] = new EmotionResultDisplay { EmotionString = "Sadness", Score = emotion.Scores.Sadness };
            //resultDisplay[7] = new EmotionResultDisplay { EmotionString = "Surprise", Score = emotion.Scores.Surprise };

            float  fAnger     = emotionResult[0].Scores.Anger;
            float  fSadness   = emotionResult[0].Scores.Sadness;
            float  fHappiness = emotionResult[0].Scores.Happiness;
            string sSongURL   = "";

            if (fAnger > 0.5)
            {
                // 許如芸 生氣
                sSongURL = "kkbox://play_song_849314";
            }
            if (fSadness > 0.5)
            {
                // 陳珊妮 如同悲傷被下載了兩次
                sSongURL = "kkbox://play_song_77706479";
            }
            if (fHappiness > 0.5)
            {
                // Happy Birthday	寶兒 (BoA)	千顏兒語 (THE FACE)
                sSongURL = "kkbox://play_song_1601466";
            }
            //            var uri = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
            var uri = "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";

            System.Diagnostics.Process.Start(uri, sSongURL);
        }
        private async void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            string personGroupId = "mykids";
            var    openDlg       = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            if (!(bool)result)
            {
                return;
            }

            string filePath = openDlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            FacePhoto.Source = bitmapSource;

            Title = "Identifying...";

            using (Stream s = File.OpenRead(filePath)) {
                var faces = await faceServiceClient.DetectAsync(s);

                var faceIds         = faces.OrderBy(f => f.FaceId).Select(face => face.FaceId).ToArray();
                var identifyResults = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);

                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi          = bitmapSource.DpiX;
                double resizeFactor = 96 / dpi;

                foreach (var face in faces)
                {
                    DrawRectangle(drawingContext, face.FaceRectangle, resizeFactor);

                    if (identifyResults.Any(f => f.FaceId == face.FaceId))
                    {
                        var identifyResult = identifyResults.FirstOrDefault(f => f.FaceId == face.FaceId);
                        var name           = "UNKNOWN";
                        if (identifyResult.Candidates.Any())
                        {
                            var candidateId = identifyResult.Candidates[0].PersonId;
                            var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                            name = person.Name;
                        }
                        drawingContext.DrawText(new FormattedText(name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 32, Brushes.Black),
                                                new Point(face.FaceRectangle.Left * resizeFactor, face.FaceRectangle.Top * resizeFactor));
                    }
                }

                drawingContext.Close();
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96, 96, PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                FacePhoto.Source = faceWithRectBitmap;
            }
            Title = "Identifying... Done";
        }
示例#57
0
        //Open save json and parsing
        private void Button_JSON_open_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
            {
                DefaultExt       = ".json",
                Filter           = "JSON (*.json)|*.json",
                Title            = "Open TTS save",
                InitialDirectory = TB_JSON_path.Text
            };

            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                string filename = dlg.FileName;
                TB_JSON_path.Text = filename;
                using (StreamReader jsonSave = File.OpenText(TB_JSON_path.Text))
                    using (JsonTextReader reader = new JsonTextReader(jsonSave))
                    {
                        string[] FindURL(JArray Objects)
                        {
                            SortedSet <string> urls = new SortedSet <string>();

                            if (Objects == null)
                            {
                                return(urls.ToArray());
                            }
                            foreach (JObject ob in Objects)
                            {
                                if (ob["Name"].ToString().Equals("Custom_Tile") ||
                                    ob["Name"].ToString().Equals("Custom_Token") ||
                                    ob["Name"].ToString().Equals("Figurine_Custom"))
                                {
                                    JObject tmp = (JObject)ob["CustomImage"];
                                    if (!urls.Add(tmp["ImageURL"].ToString()).Equals(""))
                                    {
                                        urls.Add(tmp["ImageURL"].ToString());
                                    }
                                    if (!tmp["ImageSecondaryURL"].ToString().Equals(""))
                                    {
                                        urls.Add(tmp["ImageSecondaryURL"].ToString());
                                    }
                                    if (ob.ContainsKey("States"))
                                    {
                                        JObject tmpO = (JObject)ob["States"];
                                        JArray  tmpA = new JArray();
                                        foreach (JProperty t in tmpO.Properties())
                                        {
                                            tmpA.Add(t.First);
                                        }
                                        string[] tmp1 = FindURL(tmpA);
                                        foreach (string s in tmp1)
                                        {
                                            urls.Add(s);
                                        }
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Custom_Model"))
                                {
                                    JObject tmp = (JObject)ob["CustomMesh"];
                                    if (!tmp["DiffuseURL"].ToString().Equals(""))
                                    {
                                        urls.Add(tmp["DiffuseURL"].ToString());
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Deck") ||
                                         ob["Name"].ToString().Equals("DeckCustom") ||
                                         ob["Name"].ToString().Equals("Card") ||
                                         ob["Name"].ToString().Equals("CardCustom"))
                                {
                                    foreach (var x in (JObject)ob["CustomDeck"])
                                    {
                                        string  name = x.Key;
                                        JObject tmp  = (JObject)x.Value;
                                        urls.Add(tmp["FaceURL"].ToString());
                                        urls.Add(tmp["BackURL"].ToString());
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Custom_Model_Infinite_Bag") ||
                                         ob["Name"].ToString().Equals("Custom_Model_Bag"))
                                {
                                    JObject tmpo = (JObject)ob["CustomMesh"];
                                    if (!tmpo["DiffuseURL"].ToString().Equals(""))
                                    {
                                        urls.Add(tmpo["DiffuseURL"].ToString());
                                    }
                                    string[] tmp = FindURL((JArray)ob["ContainedObjects"]);
                                    foreach (string s in tmp)
                                    {
                                        urls.Add(s);
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Bag") ||
                                         ob["Name"].ToString().Equals("Infinite_Bag"))
                                {
                                    string[] tmp = FindURL((JArray)ob["ContainedObjects"]);
                                    foreach (string s in tmp)
                                    {
                                        urls.Add(s);
                                    }
                                }
                            }
                            return(urls.ToArray());
                        }

                        JObject jsonO = (JObject)JToken.ReadFrom(reader);

                        //System.Console.WriteLine(string.Join("\n", urls.ToArray()));
                        DataTable dt = new DataTable();

                        dt.Columns.Add("#", typeof(int));
                        dt.Columns.Add("Original", typeof(string));
                        dt.Columns.Add("New", typeof(string));
                        string[] ua = FindURL((JArray)jsonO["ObjectStates"]);
                        for (int idx = 0; idx < ua.Count(); idx++)
                        {
                            dt.Rows.Add(new string[] { idx.ToString(), ua[idx], "" });
                        }
                        URLtable.ItemsSource         = dt.DefaultView;
                        URLtable.IsReadOnly          = true;
                        URLtable.SelectionMode       = DataGridSelectionMode.Single;
                        URLtable.Columns[0].Width    = DataGridLength.SizeToCells;
                        URLtable.Columns[1].MaxWidth = 380;
                        saveOpened = true;
                    }
            }
        }
示例#58
0
        private void buttonClkAndVolts_Load_Click(object sender, System.EventArgs e)
        {
            try
            {
                string[] fileEntries = Directory.GetFiles(@"/");
                foreach (string fileName in fileEntries)
                {
                    Console.WriteLine(fileName);
                }

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.Title  = "Open ngOD File";                // Default file name
                dlg.Filter = "Next Gen OD files only|*.ngOD"; // Filter files by extension
                Nullable <bool> FOresult = dlg.ShowDialog();
                if (FOresult == true)
                {
                    System.Collections.Generic.IEnumerable <String> lines = File.ReadLines(dlg.FileName);
                    foreach (string lineItem in lines)
                    {
                        //get bus number
                        string confirmBusNumber      = deviceComboBox.Text;
                        var    confirmBusNumber2     = confirmBusNumber.IndexOf("Bus ID: ");
                        var    confirmBusNumberPre   = confirmBusNumber.Substring(confirmBusNumber2 + 8, 4);
                        var    confirmBusNumberFinal = Regex.Replace(confirmBusNumberPre, "[^0-9.]", "");
                        //start
                        Process p2 = new Process();
                        p2.StartInfo.UseShellExecute        = false;
                        p2.StartInfo.RedirectStandardOutput = true;
                        p2.StartInfo.CreateNoWindow         = true;
                        p2.StartInfo.FileName  = @"ecs87NextGearOD.exe";
                        p2.StartInfo.Arguments = lineItem + " " + confirmBusNumberFinal;
                        p2.Start();
                        Thread.Sleep(100); //give it time to...breathe
                        p2.Close();
                    }
                    //refresh the stuff
                    string CurrentItem = (string)deviceComboBox.SelectedItem;
                    button_refreshDeviceCombobox_Click(this, null);
                    deviceComboBox.SelectedIndex = deviceComboBox.Items.IndexOf(CurrentItem);
                    var result      = string.Join(" ", list.ToArray());
                    var stringList2 = Regex.Split(result, "Bus ID:").ToList();
                    foreach (var stringlistitem in stringList2)
                    {
                        var stringlistitemfinal = " Bus ID:" + stringlistitem;
                        try
                        {
                            if (stringlistitemfinal.Contains(CurrentItem) && stringlistitemfinal.Contains("Assigned Target Temperature :"))
                            {
                                fansAndTemps(stringlistitem);
                            }
                            if (stringlistitemfinal.Contains(CurrentItem))
                            {
                                loopClocksAndVoltages(stringlistitem, 0);
                                loopClocksAndVoltages(stringlistitem, 1);
                                loopClocksAndVoltages(stringlistitem, 2);
                                loopClocksAndVoltages(stringlistitem, 3);
                                loopClocksAndVoltages(stringlistitem, 4);
                                loopClocksAndVoltages(stringlistitem, 5);
                                loopClocksAndVoltages(stringlistitem, 6);
                                loopClocksAndVoltages(stringlistitem, 7);
                            }
                        }
                        catch { }
                    }
                }
            }
            catch { }
        }
        private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            string lastAssemblyPath        = string.Empty;
            IEnumerable <string> lastPaths = Enumerable.Empty <string>();

            if (!string.IsNullOrEmpty(this.PluginAssembly.Name))
            {
                lastAssemblyPath = _service.ConnectionData.GetLastAssemblyPath(this.PluginAssembly.Name);
                var tempList = _service.ConnectionData.GetAssemblyPaths(this.PluginAssembly.Name).ToList();

                if (!string.IsNullOrEmpty(_defaultOutputFilePath) &&
                    !tempList.Contains(_defaultOutputFilePath, StringComparer.InvariantCultureIgnoreCase)
                    )
                {
                    tempList.Insert(0, _defaultOutputFilePath);
                }

                lastPaths = tempList;
            }

            bool   isSuccess    = false;
            string assemblyPath = string.Empty;

            try
            {
                var openFileDialog1 = new Microsoft.Win32.OpenFileDialog
                {
                    Filter           = "Plugin Assebmly (.dll)|*.dll",
                    FilterIndex      = 1,
                    RestoreDirectory = true
                };

                if (!string.IsNullOrEmpty(lastAssemblyPath))
                {
                    openFileDialog1.InitialDirectory = Path.GetDirectoryName(lastAssemblyPath);
                    openFileDialog1.FileName         = Path.GetFileName(lastAssemblyPath);
                }
                else if (!string.IsNullOrEmpty(_defaultOutputFilePath))
                {
                    openFileDialog1.InitialDirectory = Path.GetDirectoryName(_defaultOutputFilePath);
                    openFileDialog1.FileName         = Path.GetFileName(_defaultOutputFilePath);
                }

                if (lastPaths.Any())
                {
                    openFileDialog1.CustomPlaces = new List <Microsoft.Win32.FileDialogCustomPlace>(lastPaths.Select(p => new Microsoft.Win32.FileDialogCustomPlace(Path.GetDirectoryName(p))));
                }

                if (openFileDialog1.ShowDialog().GetValueOrDefault())
                {
                    isSuccess    = true;
                    assemblyPath = openFileDialog1.FileName;
                }
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }

            if (!isSuccess)
            {
                return;
            }

            LoadLocalAssemblyAsync(assemblyPath);
        }
示例#60
-1
        public PowerPointControl()
        {
            // OpenFileDialog Instanz erzeugen
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Dateiendungs-Filter setzen
            dlg.DefaultExt = ".pptx";
            dlg.Filter = "Powerpoint|*.ppt;*.pptx|All files|*.*";

            // OpenFileDialog anzeigen
            Nullable<bool> result = dlg.ShowDialog();

            // PowerPoint Instanz erzeugen
            oPPT = new Microsoft.Office.Interop.PowerPoint.Application();
            // PowerPoint anzeigen
            oPPT.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            objPresSet = oPPT.Presentations;

            // Wenn der Benutzer im OpenFileDialog eine Datei ausgewählt + auf OK geklickt hat
            if (result == true)
            {
                // Ausgewählte Datei (Präsentation) öffnen
                objPres = objPresSet.Open(dlg.FileName, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);

                // Präsentationsansicht öffnen
                objPres.SlideShowSettings.ShowPresenterView = MsoTriState.msoFalse;
                System.Diagnostics.Debug.WriteLine(objPres.SlideShowSettings.ShowWithAnimation);
                objPres.SlideShowSettings.Run();

                oSlideShowView = objPres.SlideShowWindow.View;
            }
        }