예제 #1
0
 public static void RegisterErrorHandler(RegisterErrorMethodKind methodKind, Exception exception)
 {
     MessageBox.Show("An register error occurend in " + methodKind.ToString(), "CDP4-CE.Addin");
 }
예제 #2
0
 private void InfluxDb_OnQueryException(object sender, DataBase.QueryExceptionEventArgs e)
 {
     Dispatcher?.Invoke(() => { MessageBox.Show(e.Exception.Message); });
 }
예제 #3
0
        public Result ExecuteCommand(DynamoRevitCommandData commandData)
        {
            var startupTimer = Stopwatch.StartNew();

            if (ModelState == RevitDynamoModelState.StartedUIless)
            {
                if (CheckJournalForKey(commandData, JournalKeys.ShowUiKey, true) ||
                    CheckJournalForKey(commandData, JournalKeys.ModelShutDownKey))
                {
                    //When we move from UIless to UI we prefer to start with a fresh revitDynamoModel
                    //in order to benefit from a startup sequence similar to Dynamo Revit UI launch.
                    //Also there might be other situations which demand a new revitDynamoModel.
                    //In order to be able to address them we process ModelShutDownKey.
                    //An example of this situation is when you have a revitDynamoModel already started and you switch
                    //the document in Revit. Since revitDynamoModel is well connected to the previous document we need to
                    //shut it down and start a new one in order to able to run a graph in the new document.
                    revitDynamoModel.ShutDown(false);
                    ModelState = RevitDynamoModelState.NotStarted;
                }
                else
                {
                    TryOpenAndExecuteWorkspaceInCommandData(commandData);
                    return(Result.Succeeded);
                }
            }

            if (ModelState == RevitDynamoModelState.StartedUI)
            {
                TryOpenAndExecuteWorkspaceInCommandData(commandData);
                return(Result.Succeeded);
            }

            HandleDebug(commandData);

            InitializeCore(commandData);
            //subscribe to the assembly load
            AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoad;

            try
            {
                extCommandData = commandData;

                UpdateSystemPathForProcess();

                // create core data models
                revitDynamoModel = InitializeCoreModel(extCommandData);
                revitDynamoModel.UpdateManager.RegisterExternalApplicationProcessId(Process.GetCurrentProcess().Id);
                revitDynamoModel.Logger.Log("SYSTEM", string.Format("Environment Path:{0}", Environment.GetEnvironmentVariable("PATH")));

                // handle initialization steps after RevitDynamoModel is created.
                revitDynamoModel.HandlePostInitialization();
                ModelState = RevitDynamoModelState.StartedUIless;

                // show the window
                if (CheckJournalForKey(extCommandData, JournalKeys.ShowUiKey, true))
                {
                    dynamoViewModel = InitializeCoreViewModel(revitDynamoModel);

                    // Let the host (e.g. Revit) control the rendering mode
                    var save = RenderOptions.ProcessRenderMode;
                    InitializeCoreView().Show();
                    RenderOptions.ProcessRenderMode = save;
                    revitDynamoModel.Logger.Log(Dynamo.Applications.Properties.Resources.WPFRenderMode + RenderOptions.ProcessRenderMode.ToString());

                    ModelState = RevitDynamoModelState.StartedUI;
                    // Disable the Dynamo button to prevent a re-run
                    DynamoRevitApp.DynamoButtonEnabled = false;
                }

                //foreach preloaded exception send a notification to the Dynamo Logger
                //these are messages we want the user to notice.
                preLoadExceptions.ForEach(x => revitDynamoModel.Logger.LogNotification
                                              (revitDynamoModel.GetType().ToString(),
                                              x.GetType().ToString(),
                                              DynamoApplications.Properties.Resources.MismatchedAssemblyVersionShortMessage,
                                              x.Message));

                TryOpenAndExecuteWorkspaceInCommandData(extCommandData);

                //unsubscribe to the assembly load
                AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoad;
                Analytics.TrackStartupTime("DynamoRevit", startupTimer.Elapsed, ModelState.ToString());
            }
            catch (Exception ex)
            {
                // notify instrumentation
                Analytics.TrackException(ex, true);

                MessageBox.Show(ex.ToString());

                DynamoRevitApp.DynamoButtonEnabled = true;

                //If for some reason Dynamo has crashed while startup make sure the Dynamo Model is properly shutdown.
                if (revitDynamoModel != null)
                {
                    revitDynamoModel.ShutDown(false);
                    revitDynamoModel = null;
                }

                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
예제 #4
0
        internal static void Deploy(DTE2 dte, Project project, Configuration conf)
        {
            ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            OutputsWindow.outputPane.OutputString("Hello world");
            // текущий путь
            string      str         = conf.Properties.Item("OutputPath").Value.ToString();
            var         path        = Path.Combine(Path.GetDirectoryName(project.FullName), str, @"Appx\AppxManifest.xml");
            XmlDocument xmlDocument = new XmlDocument();

            string command = "\"" + Path.GetDirectoryName(dte.FullName) + "\\devenv\" " +
                             "\"" + dte.Solution.FullName + "\" " +
                             "/deploy \"" + conf.ConfigurationName + "|" + conf.PlatformName + "\" /project " + "\"" +
                             project.FullName + "\" " + "/projectconfig \"" + conf.ConfigurationName + "|" + conf.PlatformName + "\"";

            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    FileName               = "cmd.exe",
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true
                }
            };

            //process.OutputDataReceived += Process_OutputDataReceived1;
            process.OutputDataReceived += new DataReceivedEventHandler((sender1, e1) =>
            {
                ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                OutputsWindow.outputPane.OutputString(e1.Data + Environment.NewLine);
            });

            process.Start();
            process.BeginOutputReadLine();
            //StreamReader reader = process.StandardOutput;
            using (StreamWriter pWriter = process.StandardInput)
            {
                if (pWriter.BaseStream.CanWrite)
                {
                    pWriter.WriteLine(command);
                }
            }

            process.WaitForExit();

            xmlDocument.Load(path);
            /*}*/

            XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("Package");

            foreach (XmlNode xmlNode in xmlNodes.Item(0).ChildNodes)
            {
                if (xmlNode.Name.Equals("Applications"))
                {
                    bool manifested = false;
                    if (xmlNode.ChildNodes.Count == 1)
                    {
                        // change manifest
                        var app = xmlNode.FirstChild as XmlElement;
                        var id  = app?.GetAttribute("id") as string;
                        for (int i = 0; i < 9; i++)
                        {
                            XmlNode copyApp = app.Clone();
                            ///todo change id
                            string val = app.Attributes["Id"].Value + i.ToString();
                            copyApp.Attributes["Id"].Value = val;
                            xmlNode.AppendChild(copyApp);
                        }
                        manifested = true;
                    }
                    // version up
                    foreach (XmlNode item in xmlNodes.Item(0).ChildNodes)
                    {
                        if (item.Name.Equals("Identity"))
                        {
                            var version = Version.Parse(item.Attributes["Version"].Value.ToString());
                            item.Attributes["Version"].Value = new Version(version.Major, version.Minor, version.Build, version.Revision + 1).ToString();
                        }
                    }

                    xmlDocument.Save(path);
                    // custom deploy
                    using (PowerShell PowerShellInstance = PowerShell.Create())
                    {
                        PowerShellInstance.AddCommand("Add-AppxPackage").AddParameter("register").AddArgument(path);
                        var result = PowerShellInstance.Invoke();
                        //OutputsWindow.outputPane.OutputString(PowerShellInstance.Streams.Verbose.ToString());
                        //Debug.Write(PowerShellInstance.Streams.Verbose.ToString());
                    }
                    if (manifested)
                    {
                        MessageBox.Show("Success deployed");
                    }
                    else
                    {
                        MessageBox.Show("Success version update");
                    }
                    break;
                }
            }
        }
예제 #5
0
        private void ButConnect_OnClick(object sender, RoutedEventArgs e)
        {
            var mqttFactory = new MqttFactory();

            if (string.IsNullOrWhiteSpace(server))
            {
                MessageBox.Show("Invalid Mqtt Server");
                return;
            }

            if (port < 1024 || port > 65535)
            {
                MessageBox.Show("Invalid Mqtt Port");
                return;
            }

            client = new MqttClient(ClientSub, server, port, log);

            if (UseAuth)
            {
                client.UseAuthentication(Username, pwBox.Password);
            }

            if (UseTls)
            {
                try
                {
                    client.UseTls(GetCerts());
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Invalid certificate {ex.Message}");
                    return;
                }
            }

            client.MessageReceived += (o, args) =>
            {
                if (CompareTopics(SearchTopic, args.Topic))
                {
                    UpdateTopicTags(args.Topic, args.Payload);
                }

                UpdateData(args.Topic, args.Payload);
            };

            try
            {
                client.Start();
            }
            catch (InvalidOperationException)
            {
                log.Add($"{DateTime.Now}: Unable to start client {ClientSub}");
                return;
            }

            IsConnected = true;

            Properties.Settings.Default.Port     = Port;
            Properties.Settings.Default.Server   = Server;
            Properties.Settings.Default.UseAuth  = UseAuth;
            Properties.Settings.Default.Username = Username;
            Properties.Settings.Default.UseTls   = UseTls;
            Properties.Settings.Default.CertPath = CertPath;
            Properties.Settings.Default.Save();
        }
예제 #6
0
        private void CreateBinaryTree()
        {
            try
            {
                //BinaryTree<int> tree = new BinaryTree<int>(new BinaryTreeNode<int>(1));
                //tree.Root.Left = new BinaryTreeNode<int>(2);
                //tree.Root.Right = new BinaryTreeNode<int>(3);
                //tree.Root.Left.Left = new BinaryTreeNode<int>(4);
                //tree.Root.Right.Right = new BinaryTreeNode<int>(5);
                //tree.Root.Left.Left.Right = new BinaryTreeNode<int>(6);
                //tree.Root.Right.Right.Right = new BinaryTreeNode<int>(7);
                //tree.Root.Right.Right.Right.Right = new BinaryTreeNode<int>(8);

                /*
                 *              1
                 *            2   3
                 *           4      5
                 *             6     7
                 *                    8
                 */

                //tree.Print(tree.Root, Enumerations.PrintTreeMode.BinaryInfix);

                //BinarySearchTree<int> tree = new BinarySearchTree<int>(new BinaryTreeNode<int>(5));
                //tree.Add(4);
                //tree.Add(2);
                //tree.Add(3);
                //tree.Add(1);
                //tree.Add(7);
                //tree.Add(6);
                //tree.Add(8);
                ///*
                //                5
                //              4   7
                //             2   6 8
                //            1 3
                //*/

                //tree.Print(tree.Root, Enumerations.PrintTreeMode.BinaryInfix);

                //BinarySearchTree<int> tree = new BinarySearchTree<int>();
                //for (int i = 0; i < 100; i++)
                //    tree.Add(i);
                //tree.Print(tree.Root, Enumerations.PrintTreeMode.BinaryInfix);

                //BinarySearchTree<int> tree = new BinarySearchTree<int>(new BinaryTreeNode<int>(5));
                //tree.Add(4);
                //tree.Add(2);
                //tree.Add(3);
                //tree.Add(1);
                //tree.Add(6);
                //tree.Add(7);
                //tree.Add(8);
                ///*
                //                5
                //              4   6
                //             2     7
                //            1 3     8
                //*/

                //tree.Print(tree.Root, Enumerations.PrintTreeMode.ZigZagStartLeft);
                //tree.Print(tree.Root, Enumerations.PrintTreeMode.ZigZagStartRight);


                //AVLTree<int> tree = new AVLTree<int>(new BinaryTreeNode<int>(10));
                //tree.Add(30);
                ///*
                //                10
                //                  30
                //*/
                //tree.Print(tree.Root, Enumerations.PrintTreeMode.LeftToRight);
                //Console.WriteLine();
                //tree.Add(20);
                ///*
                //                20
                //             10    30
                //*/
                //tree.Print(tree.Root, Enumerations.PrintTreeMode.LeftToRight);
                //Console.WriteLine();
                //tree.Add(40);
                ///*
                //                20
                //             10    30
                //                      40
                //*/
                //tree.Print(tree.Root, Enumerations.PrintTreeMode.LeftToRight);
                //Console.WriteLine();
                //tree.Add(50);
                ///*
                //                 20
                //             10      40
                //                  30    50
                //*/

                //tree.Print(tree.Root, Enumerations.PrintTreeMode.LeftToRight);

                AVLTree <double> tree = new AVLTree <double>();
                for (int i = 1; i <= 15; i++)
                {
                    tree.Add(i);
                }
                for (int i = 0; i <= 15; i++)
                {
                    tree.Add(0.5 + i);
                }
                Console.WriteLine(tree.Print(tree.Root, Enumerations.PrintTreeMode.BinaryPrefix));


                // see how much faster iterative print is..

                //System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
                //for (int i = 0; i < 100; i++)
                //{
                //    System.Collections.Generic.Stack<TreeNode<double>> s = new System.Collections.Generic.Stack<TreeNode<double>>();
                //    s.Push(tree.Root);
                //    tree.PrintZigZagToString(s, new System.Collections.Generic.Stack<TreeNode<double>>(), 0);
                //}
                //sw.Stop();
                //Console.WriteLine(string.Format("Time: {0}", sw.ElapsedTicks));

                //sw = System.Diagnostics.Stopwatch.StartNew();
                //for (int i = 0; i < 100; i++)
                //    tree.PrintZigZag_Iterative(Enumerations.PrintTreeMode.ZigZagStartLeft);
                //sw.Stop();
                //Console.WriteLine(string.Format("Time: {0}", sw.ElapsedTicks));
            }
            catch (Exception ex) { MsgBox.Show(ex.Message); }
        }
예제 #7
0
        private void OnRcvConvertFromFileDataParamMessage(MessageBase msg)
        {
            if (msg is ConvertFromFileDataParamMessage)
            {
                var dataParam = msg as ConvertFromFileDataParamMessage;
                if (dataParam.FileList.Count() == 0)
                {
                    Messenger.Default.Send(new ShowAppMessage {
                        MessageTitle = "Information", AppMessage = "Nothing to convert."
                    });
                    return;
                }

                var t = new Thread(ConvertFromFileHelper.ConvertFromFiles);
                t.IsBackground = false;

                var param = new ConvertFromFilesParam();
                param.FileList       = dataParam.FileList;
                param.OutputSettings = OutputSettings;
                param.threadObject   = t;

                IsBusy = true;
                ShowCloseProgressDialogDelegate showProgressDelegate = () =>
                {
                    Messenger.Default.Send(new CloseWindowMessage());
                    Messenger.Default.Send(new ShowProgressDialogMessage());
                };

                ShowCloseProgressDialogDelegate closeProgressDelegate = () =>
                {
                    IsBusy = false;
                    Messenger.Default.Send <ShowAppMessage, ProgressDialogViewModel>(
                        new ShowAppMessage {
                        MessageTitle = "Done!", AppMessage = "Done."
                    });
                };

                param.OnStartProcess = () => { Application.Current.Dispatcher.Invoke(showProgressDelegate, null); };

                param.BeforeConvertCallback = reportFilename =>
                {
                    SendAppMessageDelegate appMessage = () =>
                    {
                        Messenger.Default.Send <ShowAppMessage, ProgressDialogViewModel>(
                            new ShowAppMessage {
                            MessageTitle = "Converting " + Path.GetFileName(reportFilename) + "..."
                        }
                            );
                    };
                    Application.Current.Dispatcher.Invoke(appMessage, null);
                };

                param.ProgressCallback = (reportFilename, pseDocument) =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        var dataService = ServiceLocator.Current.GetInstance <IPSEGetDataService>(); //new PSEGetDataService();
                        dataService.SaveTradeData(pseDocument);

                        Messenger.Default.Send <ShowAppMessage, ProgressDialogViewModel>(
                            new ShowAppMessage
                        {
                            MessageTitle = "Done.",
                            AppMessage   = "Converted " + Path.GetFileName(reportFilename)
                        }
                            );
                    });
                };

                param.ExceptionCallback = e =>
                {
                    //errorList.Add(e);
                    //System.Windows.Forms.MessageBox.Show(e.Message);
                    if (e is SQLiteException)
                    {
                        MessageBox.Show("The conversion was successful but PSEGet was unable to update the database.");
                    }
                    else
                    {
                        MessageBox.Show(e.Message);
                    }
                    IsBusy = false;
                    Application.Current.Dispatcher.Invoke(closeProgressDelegate, null);
                };
                param.CompletedCallback = pseDocument =>
                {
                    Application.Current.Dispatcher.Invoke(closeProgressDelegate, null);
                    ShowExchangeNotice(pseDocument);
                };


                t.Start(param);
            }
        }
예제 #8
0
        public int AddNewMessage(string conversationId, ConversationMessageModel message)
        {
            try
            {
                Stream previewImageData = null;

                if (message.PreviewImage != null)
                {
                    PngBitmapEncoder pngFile = new PngBitmapEncoder();

                    pngFile.Frames.Add((BitmapFrame)message.PreviewImage);

                    MemoryStream stream = new MemoryStream();
                    pngFile.Save(stream);

                    previewImageData = stream;
                }

                _writer.Write(MessageDictionary.NewMessage);
                if (_reader.Read() == MessageDictionary.OK)
                {
                    _writer.Write(conversationId);
                    _writer.Write(message.AuthorId);

                    _writer.Write(message.Attachments.Count);
                    foreach (FileModel attachment in message.Attachments)
                    {
                        _writer.Write(attachment.Id);
                    }

                    if (message is ConversationEmailMessageModel)
                    {
                        ConversationEmailMessageModel emailMessage = (ConversationEmailMessageModel)message;
                        _writer.Write(MessageDictionary.MessageTypeEmail);
                        if (_reader.Read() == MessageDictionary.OK)
                        {
                            _writer.Write(emailMessage.AuthorEmailaddress.Id);
                            _writer.Write(emailMessage.InitialDate.Value.ToString("yyyy-MM-dd HH:mm"));
                            _writer.Write(emailMessage.MessageSubject);
                            _writer.Write(emailMessage.MessageContent);

                            SendFile(previewImageData);


                            if (_reader.Read() != MessageDictionary.OK)
                            {
                                throw new Exception("Connection unsynced");
                            }
                            return(1);
                        }
                        throw new Exception("Connection unsynced");
                    }

                    if (message is ConversationPhoneMessageModel)
                    {
                        ConversationPhoneMessageModel phoneMessage = (ConversationPhoneMessageModel)message;
                        _writer.Write(MessageDictionary.MessageTypePhoneCall);

                        _writer.Write(phoneMessage.AuthorPhoneNumber.Id);
                        _writer.Write(phoneMessage.RecipientPhoneNumber.Id);
                        _writer.Write(phoneMessage.InitialDate.Value.ToString("yyyy-MM-dd HH:mm"));
                        _writer.Write(phoneMessage.CallDescription);
                        _writer.Write(phoneMessage.CallAnswered);

                        SendFile(previewImageData);

                        if (_reader.Read() != MessageDictionary.OK)
                        {
                            throw new Exception("Connection unsynced");
                        }
                        return(1);
                    }
                    throw new Exception("Connection unsynced");
                }
                throw new Exception("Connection unsynced");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                ErrorHelper.LogError(ex);
                Logout();
                return(0);
            }
        }
예제 #9
0
        public List <PersonModel> GetAllContacts()
        {
            try
            {
                _writer.Write(MessageDictionary.GetAllContacts);
                if (_reader.Read() == MessageDictionary.OK)
                {
                    List <PersonModel> contacts = new List <PersonModel>();
                    int personCount             = _reader.ReadInt32();

                    for (int i = 0; i < personCount; i++)
                    {
                        string PersonId         = _reader.ReadString();
                        string PersonFirstName  = _reader.ReadString();
                        string PersonLastName   = _reader.ReadString();
                        string PersonGenderCode = _reader.ReadString();
                        string PersonCompanyId  = _reader.ReadString();
                        bool   IsInternalUser   = _reader.ReadBoolean();

                        Gender PersonGender = (Gender)Convert.ToInt32(PersonGenderCode);

                        PersonModel contactPerson = new PersonModel(PersonId, PersonFirstName, PersonLastName, PersonGender,
                                                                    PersonCompanyId, IsInternalUser);

                        int emailAddressCount = _reader.ReadInt32();

                        for (int j = 0; j < emailAddressCount; j++)
                        {
                            string emailId      = _reader.ReadString();
                            string emailName    = _reader.ReadString();
                            string emailAddress = _reader.ReadString();

                            EmailAddressModel emailAddressModel = new EmailAddressModel(emailId, emailAddress, emailName);
                            contactPerson.EmailAddresses.Add(emailAddressModel);
                        }

                        if (_reader.Read() == MessageDictionary.EndOfMessage)
                        {
                            int phoneNumberCount = _reader.ReadInt32();

                            for (int j = 0; j < phoneNumberCount; j++)
                            {
                                string phoneNumberId = _reader.ReadString();
                                string phoneName     = _reader.ReadString();
                                string phoneNumber   = _reader.ReadString();

                                PhoneNumberModel phoneNumberModel = new PhoneNumberModel(phoneNumberId, phoneNumber, phoneName);
                                contactPerson.PhoneNumbers.Add(phoneNumberModel);
                            }
                        }
                        if (_reader.Read() != MessageDictionary.EndOfMessage)
                        {
                            throw new Exception("Connection unsynced");
                        }

                        contacts.Add(contactPerson);
                    }
                    if (_reader.Read() == MessageDictionary.EndOfMessage)
                    {
                        return(contacts);
                    }
                    throw new Exception("Connection unsynced");
                }
                throw new Exception("Connection unsynced");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                ErrorHelper.LogError(ex);
                Logout();
                return(null);
            }
        }
예제 #10
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            int?   nullable;
            string numberSerial;
            string numberSAP;
            string numberSection;
            int?   nullable1;
            string numberActivity;
            double num = double.Parse(txtHours.Text);
            string text;
            string code;
            string str;

            if (cbxTimeCode.SelectedItem != null)
            {
                code = ((TimesheetCode)cbxTimeCode.SelectedItem).Code;
                if (cbxTaskType.SelectedItem != null)
                {
                    if (!(cbxTaskType.SelectedValue.ToString() == "(N/A)"))
                    {
                        str = cbxTaskType.SelectedValue.ToString();
                        if (cbxJob.SelectedValue != null)
                        {
                            Project selectedItem = (Project)cbxJob.SelectedItem;
                            numberSerial = selectedItem.Number_Serial;
                            numberSAP    = selectedItem.Number_SAP;
                            if (cbxSection.SelectedValue == null)
                            {
                                MessageBox.Show("You must select a section");
                                return;
                            }
                            Section section = cbxSection.SelectedItem as Section;
                            numberSection  = section.Number_Section;
                            nullable       = new int?(section.Id);
                            nullable1      = new int?(int.Parse(section.Number_ProjectNetwork));
                            numberActivity = section.Number_Activity;
                        }
                        else
                        {
                            MessageBox.Show("You must select a project");
                            return;
                        }
                    }
                    else
                    {
                        str            = cbxTaskType.SelectedValue.ToString();
                        numberSerial   = "";
                        numberSAP      = "";
                        numberSection  = "";
                        nullable       = null;
                        nullable1      = null;
                        numberActivity = "";
                    }
                    if (dtpDate.SelectedDate.HasValue)
                    {
                        DateTime value = dtpDate.SelectedDate.Value;
                        int      month = value.Month;
                        int      year  = value.Year;
                        if (!queries.Period_Open(month, year))
                        {
                            MessageBox.Show("Date Must Be Within The Period");
                            return;
                        }

                        if (!string.IsNullOrEmpty(txtDescription.Text))
                        {
                            text                  = txtDescription.Text;
                            entry.section_id      = nullable;
                            entry.project_serial  = numberSerial;
                            entry.project_sap     = numberSAP;
                            entry.number_section  = numberSection;
                            entry.number_network  = nullable1;
                            entry.number_activity = numberActivity;
                            entry.date            = value;
                            entry.period          = month;
                            entry.year            = year;
                            entry.hours           = num;
                            entry.description     = text;
                            entry.timesheet_code  = code;
                            entry.task_type       = str;
                            DialogResult          = new bool?(true);
                        }
                        else
                        {
                            MessageBox.Show("You must enter a description");
                        }
                    }
                    else
                    {
                        MessageBox.Show("You must select a date");
                    }
                }
                else
                {
                    MessageBox.Show("You must select a task type");
                }
            }
            else
            {
                MessageBox.Show("You must select a timecode");
            }
        }
예제 #11
0
        public List <ConversationMessageModel> GetConversationMessages(string conversationId)
        {
            try
            {
                List <ConversationMessageModel> messages = new List <ConversationMessageModel>();

                _writer.Write(MessageDictionary.GetConversationMessages);
                if (_reader.Read() == MessageDictionary.OK)
                {
                    _writer.Write(conversationId);
                    if (_reader.Read() == MessageDictionary.OK)
                    {
                        int messageCount = _reader.ReadInt32();
                        for (int i = 0; i < messageCount; i++)
                        {
                            string  id                = _reader.ReadString();
                            string  authorId          = _reader.ReadString();
                            string  authorFrom        = _reader.ReadString();
                            string  initialDateString = _reader.ReadString();
                            Boolean received          = _reader.ReadBoolean();

                            byte[] previewData = ReceiveFile();

                            List <string> attachmentIds = new List <string>();

                            int attachmentCount = _reader.ReadInt32();

                            for (int j = 0; j < attachmentCount; j++)
                            {
                                attachmentIds.Add(_reader.ReadString());
                            }

                            MemoryStream stream       = new MemoryStream(previewData);
                            BitmapImage  previewImage = new BitmapImage();
                            previewImage.BeginInit();
                            previewImage.StreamSource = stream;
                            previewImage.EndInit();

                            previewImage.Freeze();

                            DateTime initialDate             = DateTime.ParseExact(initialDateString, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                            ConversationMessageModel message = new ConversationMessageModel(id, conversationId, authorId,
                                                                                            authorFrom, initialDate, received, previewImage, false, attachmentIds);

                            byte type = _reader.ReadByte();

                            if (type == MessageDictionary.MessageTypeEmail)
                            {
                                string subject = _reader.ReadString();
                                string content = _reader.ReadString();

                                ConversationEmailMessageModel emailMessage = new ConversationEmailMessageModel(message,
                                                                                                               subject, content);
                                message = emailMessage;
                            }
                            else if (type == MessageDictionary.MessageTypePhoneCall)
                            {
                                string recipientPhoneNumberId = _reader.ReadString();
                                string callDescription        = _reader.ReadString();
                                bool   callAnswered           = _reader.ReadBoolean();
                                ConversationPhoneMessageModel phoneMessage = new ConversationPhoneMessageModel(message, recipientPhoneNumberId,
                                                                                                               callDescription, callAnswered);
                                message = phoneMessage;
                            }

                            if (message != null)
                            {
                                messages.Add(message);
                            }
                        }
                        if (_reader.Read() == MessageDictionary.EndOfMessage)
                        {
                            return(messages);
                        }
                        throw new Exception("Connection unsynced");
                    }
                    throw new Exception("Connection unsynced");
                }
                throw new Exception("Connection unsynced");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                ErrorHelper.LogError(ex);
                Logout();
                return(null);
            }
        }
        public void Execute(IDataContext context, DelegateExecute nextExecute)
        {
            if (!File.Exists(SimianOptions.Instance.PathToSimian))
            {
                MessageBox.Show("You need to configure the path to the Simian executable.  Configuration is located at Resharper->Options->Agent Ralph->Simian Explorer.");
                // TODO: Launch the R# config here.
                return;
            }

            // Get solution from context in which action is executed
            ISolution solution = context.GetData(IDE.DataConstants.SOLUTION);

            if (solution == null)
            {
                return;
            }

            List <FileSystemPath> files_to_analyze = CollectAllFilesToAnalyze(solution);

            if (files_to_analyze.Count == 0)
            {
                SimianResultsDescriptor d2 = new SimianResultsDescriptor(solution, new List <ISet>(), "Simian Explorer");

                // Show the results in the gui.
                TreeModelBrowser.GetInstance(solution).Show("SearchResultsWindow", d2,
                                                            new TreeModelBrowserPanel(d2));
                return;
            }

            string simian_xml_file = SimianUtil.RunSimianToXml(files_to_analyze, SimianOptions.Instance);

            try
            {
                SimianResultsParser parser   = new SimianResultsParser(solution);
                IEnumerable <Set>   sim_sets = parser.GetSimianResults2(simian_xml_file);

                // Get the initial explorer.
                SimianResultsDescriptor d2 = new SimianResultsDescriptor(solution, ToIListOfISet(sim_sets), "Simian Explorer");

                // Show the results in the gui.
                TreeModelBrowser.GetInstance(solution).Show("SearchResultsWindow", d2,
                                                            new TreeModelBrowserPanel(d2));

                // And the examiner produces the content of the 'Refactoring Candidates' explorer.
                Examiner     examiner = new Examiner(solution);
                IList <ISet> l        = examiner.Examine(sim_sets);

                if (l.Count == 0)
                {
                    return;
                }

                d2 = new SimianResultsDescriptor(solution, l, "The Inbetweens");

                // Show the results in the gui.
                TreeModelBrowser.GetInstance(solution).Show("SearchResultsWindow", d2,
                                                            new TreeModelBrowserPanel(d2));


                if (parser.FilesInError.Count > 0)
                {
                    using (SimianErrorFilesForm f = new SimianErrorFilesForm())
                    {
                        f.FilesInError = parser.FilesInError;
                        f.ShowDialog();
                    }
                }
            }
            finally
            {
                if (File.Exists(simian_xml_file))
                {
                    File.Delete(simian_xml_file);
                }
            }
        }
예제 #13
0
 public static void CopyRecordingLocationToClipboard(AIR_API.Recording item)
 {
     Clipboard.SetText(item.FilePath);
     MessageBox.Show(Program.LanguageResource.GetString("RecordingPathCopiedToClipboard"));
 }
예제 #14
0
        private void testButton_Click(object sender, RoutedEventArgs e)
        {
            string result = (this.getDriver().Test(this.GetServer(), this.GetAuth(), this.GetUsername(), this.GetPassword(), this.GetParam())) ? "Connection OK!" : "Connection Failed ...";

            MessageBox.Show(result, "Test Result");
        }
        public static void ImportMod(string file, bool updateUI = true)
        {
            try
            {
                if (Path.GetExtension(file) == ".rar")
                {
                    Management.FileManagement.ExtractRar(file, Management.ProgramPaths.Sonic3AIR_MM_TempModsFolder);
                }
                else if (Path.GetExtension(file) == ".zip")
                {
                    Management.FileManagement.ExtractZip(file, Management.ProgramPaths.Sonic3AIR_MM_TempModsFolder);
                }
                else if (Path.GetExtension(file) == ".7z")
                {
                    Management.FileManagement.Extract7Zip(file, Management.ProgramPaths.Sonic3AIR_MM_TempModsFolder);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Something Went Wrong:" + Environment.NewLine + ex.Message);
                return;
            }

            ModSearchLoop();
            while (FindModRoot(0) != "")
            {
                ModSearchLoop();
            }
            CleanUpTempModsFolder();
            if (updateUI)
            {
                new Action(ModManager.UpdateUIFromInvoke).Invoke();
            }

            void ModSearchLoop()
            {
                try
                {
                    string meta = FindModRoot(0);
                    if (meta != "")
                    {
                        AddToModsFolder(meta, System.IO.Path.GetDirectoryName(meta));
                    }
                    else
                    {
                        PrepModAttempt2();
                    }

                    void PrepModAttempt2()
                    {
                        meta = FindModRoot(1);
                        if (meta != "")
                        {
                            AddToModsFolder(meta, System.IO.Path.GetDirectoryName(meta));
                        }
                        else
                        {
                            BadModMessage();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Something Went Wrong:" + Environment.NewLine + ex.Message);
                }
            }
        }
        public static void Initialize()
        {
            var currentDirectory = Path.GetDirectoryName(typeof(MainWindow).Assembly.Location) ??
                                   Environment.CurrentDirectory;

            GameRootDirectory = currentDirectory + "\\";

            Directory.CreateDirectory(GameRootDirectory + _mCustomDir);

            BepinPluginsDir = $"{GameRootDirectory}\\BepInEx\\Plugins\\";

            // Framework test
            IsIpa   = File.Exists($"{GameRootDirectory}\\IPA.exe");
            IsBepIn = Directory.Exists($"{GameRootDirectory}\\BepInEx");

            if (IsIpa && IsBepIn)
            {
                MessageBox.Show(
                    "Both BepInEx and IPA is detected in the game folder!\n\nApplying both frameworks may lead to problems when running the game!",
                    "Warning!");
            }


            // Updater stuffs

            KKmanExist       = File.Exists(GameRootDirectory + _mCustomDir + _kkmdir);
            _updatelocExists = File.Exists(GameRootDirectory + _mCustomDir + _updateLoc);
            if (KKmanExist)
            {
                var kkmanFileStream = new FileStream(GameRootDirectory + _mCustomDir + _kkmdir, FileMode.Open,
                                                     FileAccess.Read);
                using (var streamReader = new StreamReader(kkmanFileStream, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        _kkman = line;
                    }
                }

                kkmanFileStream.Close();
                if (_updatelocExists)
                {
                    var updFileStream = new FileStream(GameRootDirectory + _mCustomDir + _updateLoc, FileMode.Open,
                                                       FileAccess.Read);
                    using (var streamReader = new StreamReader(updFileStream, Encoding.UTF8))
                    {
                        string line;
                        while ((line = streamReader.ReadLine()) != null)
                        {
                            _updateSources = line;
                        }
                    }

                    updFileStream.Close();
                }
                else
                {
                    _updateSources = "";
                }
            }

            _langExists = File.Exists(GameRootDirectory + _mCustomDir + _decideLang);
            if (_langExists)
            {
                var verFileStream = new FileStream(GameRootDirectory + _mCustomDir + _decideLang, FileMode.Open,
                                                   FileAccess.Read);
                using (var streamReader = new StreamReader(verFileStream, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        Language = line;
                    }
                }

                verFileStream.Close();
            }

            if (GameRootDirectory.Length >= 75)
            {
                MessageBox.Show(
                    "The game is installed deep in the file system!\n\nThis can cause a variety of errors, so it's recommended that you move it to a shorter path, something like:\n\nC:\\Illusion\\AI.Shoujo",
                    "Critical warning!");
            }

            // Customization options

            var versionPath = Path.GetFullPath(GameRootDirectory + _versioningLoc);

            if (File.Exists(versionPath))
            {
                var verFileStream = new FileStream(versionPath, FileMode.Open, FileAccess.Read);
                using (var streamReader = new StreamReader(verFileStream, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        VersionString = line;
                    }
                }

                verFileStream.Close();
            }

            var warningExists = File.Exists(GameRootDirectory + _mCustomDir + _warningLoc);

            if (warningExists)
            {
                try
                {
                    using (var sr = new StreamReader(GameRootDirectory + _mCustomDir + _warningLoc))
                    {
                        var line = sr.ReadToEnd();
                        WarningString = line;
                    }
                }
                catch (IOException e)
                {
                    WarningString = e.Message;
                }
            }

            var charExists = File.Exists(GameRootDirectory + _mCustomDir + _charLoc);

            if (charExists)
            {
                var urich = new Uri(GameRootDirectory + _mCustomDir + _charLoc, UriKind.RelativeOrAbsolute);
                CustomCharacterImage = BitmapFrame.Create(urich);
            }

            var backgExists = File.Exists(GameRootDirectory + _mCustomDir + _backgLoc);

            if (backgExists)
            {
                var uribg = new Uri(GameRootDirectory + _mCustomDir + _backgLoc, UriKind.RelativeOrAbsolute);
                CustomBgImage = BitmapFrame.Create(uribg);
            }

            var patreonExists = File.Exists(GameRootDirectory + _mCustomDir + _patreonLoc);

            if (patreonExists)
            {
                var verFileStream = new FileStream(GameRootDirectory + _mCustomDir + _patreonLoc, FileMode.Open,
                                                   FileAccess.Read);
                using (var streamReader = new StreamReader(verFileStream, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        PatreonUrl = line;
                    }
                }

                verFileStream.Close();
            }
        }
        public static void PraseMods()
        {
            IList <Tuple <ModViewerItem, int> > ActiveMods = new List <Tuple <ModViewerItem, int> >();

            ModSearch(new DirectoryInfo(Management.ProgramPaths.Sonic3AIRModsFolder));
            AddActiveMods();

            void ModSearch(DirectoryInfo d, bool isSubFolder = false)
            {
                DirectoryInfo[] folders = d.GetDirectories();
                foreach (DirectoryInfo folder in folders)
                {
                    DirectoryInfo f    = new DirectoryInfo(folder.FullName);
                    var           root = f.GetFiles("mod.json").FirstOrDefault();
                    if (root != null)
                    {
                        PraseMod(root, folder, isSubFolder, d.Name);
                    }
                    else
                    {
                        if (!isSubFolder)
                        {
                            ModSearch(new DirectoryInfo(folder.FullName), true);
                        }
                    }
                }
            }

            void AddActiveMods()
            {
                foreach (var enabledMod in ActiveMods.OrderBy(x => x.Item2).ToList())
                {
                    ActiveModsList.Insert(0, enabledMod.Item1);
                }
            }

            void PraseMod(FileInfo root, DirectoryInfo folder, bool isSubFolder = false, string subFolderName = "")
            {
                try
                {
                    var    mod     = new AIR_API.Mod(root);
                    string modPath = mod.FolderName;
                    if (isSubFolder)
                    {
                        modPath = string.Format("{0}/{1}", subFolderName, mod.FolderName);
                    }
                    if (S3AIRActiveMods.ActiveMods.Contains(modPath))
                    {
                        mod.IsEnabled    = true;
                        mod.EnabledLocal = true;
                        ActiveMods.Add(new Tuple <ModViewerItem, int>(new ModViewerItem(mod, !isSubFolder), S3AIRActiveMods.ActiveMods.IndexOf(modPath)));
                    }
                    else
                    {
                        mod.IsEnabled    = false;
                        mod.EnabledLocal = false;
                        ModsList.Add(new ModViewerItem(mod, !isSubFolder));
                    }
                }
                catch (Newtonsoft.Json.JsonReaderException ex)
                {
                    MessageBox.Show(Management.UserLanguage.LegacyModError1(folder.Name, ex.Message));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Management.UserLanguage.LegacyModError2(folder.Name, ex.Message));
                }
            }
        }
예제 #18
0
 public static void ShowMessageBox(this string str, string title = "Test")
 {
     MessageBox.Show(str, title);
 }
예제 #19
0
        private void StartL()
        {
            if (IsRunning)
            {
                return;
            }
            try
            {
                // construct a scheduler factory
                ISchedulerFactory schedFact = new StdSchedulerFactory();

                // get a scheduler, start the schedular before triggers or anything else
                if (sched == null)
                {
                    sched = schedFact.GetScheduler().Result;
                }

                // create job
                IJobDetail job = JobBuilder.Create <SimpleJob>()
                                 .WithIdentity("job1", "group1")
                                 .Build();

                // create trigger

                var triggerB = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1");

                if (StartIn)
                {
                    triggerB =
                        triggerB.StartAt(DateBuilder.FutureDate(
                                             (StartHour * 60 * 60) + (StartMinute * 60) + StartSecond,
                                             IntervalUnit.Second));
                }

                if (StartAt)
                {
                    triggerB =
                        triggerB.StartAt(DateBuilder.DateOf(StartHour, StartMinute, StartSecond, StartDate.Day,
                                                            StartDate.Month, StartDate.Year));
                }
                if (StartDaily)
                {
                    ISet <DayOfWeek> days = new HashSet <DayOfWeek>();
                    if (StartDay0)
                    {
                        days.Add(DayOfWeek.Sunday);
                    }
                    if (StartDay1)
                    {
                        days.Add(DayOfWeek.Monday);
                    }
                    if (StartDay2)
                    {
                        days.Add(DayOfWeek.Tuesday);
                    }
                    if (StartDay3)
                    {
                        days.Add(DayOfWeek.Wednesday);
                    }
                    if (StartDay4)
                    {
                        days.Add(DayOfWeek.Thursday);
                    }
                    if (StartDay5)
                    {
                        days.Add(DayOfWeek.Friday);
                    }
                    if (StartDay6)
                    {
                        days.Add(DayOfWeek.Saturday);
                    }

                    triggerB =
                        triggerB.WithDailyTimeIntervalSchedule(
                            x =>
                            x.WithIntervalInSeconds(TimeBetweenShots)
                            .WithMisfireHandlingInstructionFireAndProceed()
                            .StartingDailyAt(new TimeOfDay(StartHour, StartMinute, StartSecond))
                            .EndingDailyAt(new TimeOfDay(StopHour, StopMinute, StopSecond))
                            .OnDaysOfTheWeek(days)
                            );
                }
                else
                {
                    if (StopAtPhotos)
                    {
                        triggerB =
                            triggerB.WithSimpleSchedule(
                                x =>
                                x.WithIntervalInSeconds(TimeBetweenShots)
                                .WithRepeatCount(StopCaptureCount)
                                .WithMisfireHandlingInstructionNowWithExistingCount());
                    }
                    else if (StopIn)
                    {
                        triggerB =
                            triggerB.WithSimpleSchedule(
                                x =>
                                x.WithIntervalInSeconds(TimeBetweenShots)
                                .WithMisfireHandlingInstructionNowWithExistingCount()
                                .WithRepeatCount(((StopHour * 60 * 60) + (StopMinute * 60) + StopSecond) /
                                                 TimeBetweenShots));
                    }
                    else
                    {
                        triggerB =
                            triggerB.WithSimpleSchedule(
                                x =>
                                x.WithIntervalInSeconds(TimeBetweenShots)
                                .WithMisfireHandlingInstructionNowWithExistingCount()
                                .RepeatForever());
                    }

                    if (StopAt)
                    {
                        triggerB =
                            triggerB.EndAt(DateBuilder.DateOf(StopHour, StopMinute, StopSecond, StopDate.Day,
                                                              StopDate.Month,
                                                              StopDate.Year));
                    }
                }

                trigger = triggerB.Build();


                // Schedule the job using the job and trigger
                sched.ScheduleJob(job, trigger);
                sched.Start();

                if (_bracketingViewModel != null)
                {
                    _bracketingViewModel.Stop();
                }
                _bracketingViewModel = null;
                IsRunning            = true;
                _timeLapseStartTime  = DateTime.Now;
                _lastCaptureTime     = DateTime.Now;
                Log.Debug("Timelapse start");
                _totalCaptures  = 0;
                _timer.Interval = 1000;
                _timer.Start();
                _lastTime = DateTime.Now;
                TimeLapseSettings.Started = true;
                ServiceProvider.Settings.Save(ServiceProvider.Settings.DefaultSession);
            }
            catch (Exception e)
            {
                MessageBox.Show("Unable to start timelapse " + e.Message);
                Log.Debug("Unable to start timelapse ", e);
            }
        }
예제 #20
0
        public void testClass11()
        {
            Configuration config  = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string        connStr = config.AppSettings.Settings["crazykartConnectionString"].Value;

            string[] connstStrings = connStr.Trim().Split(';');
            string   connNew       = "";

            if (connstStrings.Length == 4)
            {
                connNew = String.Format("{0};{1};", connstStrings[0], connstStrings[2]);
            }
            SqlConnection myConnection = new SqlConnection(connNew);
            string        dbname       = myConnection.Database;

            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            var dblist = myConnection.GetSchema("Databases");

            string[] sysdbs = new[] { "master", "model", "msdb", "tempdb" };
            foreach (DataRow database in dblist.Rows)
            {
                String databaseName = database.Field <String>("database_name");
                if (!sysdbs.Contains(databaseName))
                {
                    //comboBox6.
                }
                short    dbID         = database.Field <short>("dbid");
                DateTime creationDate = database.Field <DateTime>("create_date");
            }



            ProkardModel form = new ProkardModel();

            Hashtable sett = form.LoadSettings();
            //Console.WriteLine(sett["decoder"]);
            // настройки транспондеров
            string path = "transetts.xml";

            if (File.Exists(path))
            {
                DataSet ds = new DataSet();

                ds.ReadXml(path);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (row.ItemArray[0].ToString().Trim() == sett["decoder"].ToString().Trim())
                    {
                        decoderSetts = row.ItemArray;
                    }
                }
            }
            // 0 - name protokol
            // 1 - bytes (32)
            // 2 - hours 1
            // 3 - minutes 1
            // 4 - seconds 1
            // 5 - transponder
            // 6 - mseconds
            // 7 - hits
            // 8 - port speed
            // 9 - bits
            // 10 - StopBits
            int portSpeed = Convert.ToInt32(decoderSetts[8]);
            int bits      = Convert.ToInt32(decoderSetts[9]);

            // var stopBits = null;
            //if (Convert.ToInt32(decoderSetts[9]) == 1)
            // {
            //    stopBits = StopBits.One;
            //  }
            //  string stopBits = decoderSetts[10].ToString();

            RS232 = new SerialPort(Convert.ToString("COM4"), portSpeed, Parity.None, bits, StopBits.One);
            // RS232.ReadBufferSize = 32;
            //  RS232.RtsEnable = true;
            RS232.DataReceived += new SerialDataReceivedEventHandler(RS232_DataReceived);
            RS232.Open();
        }
예제 #21
0
        public List <Result> LoadContextMenus(Result selectedResult)
        {
            var contextMenus = new List <Result>();

            if (selectedResult.ContextData is SearchResult record)
            {
                if (record.Type == ResultType.File)
                {
                    contextMenus.Add(CreateOpenWithEditorResult(record));
                }

                if (record.Type == ResultType.Folder && record.WindowsIndexed)
                {
                    contextMenus.Add(CreateAddToIndexSearchExclusionListResult(record));
                }

                contextMenus.Add(CreateOpenContainingFolderResult(record));

                contextMenus.Add(CreateOpenWindowsIndexingOptions());

                if (record.ShowIndexState)
                {
                    contextMenus.Add(new Result {
                        Title    = "From index search: " + (record.WindowsIndexed ? "Yes" : "No"),
                        SubTitle = "Location: " + record.FullPath,
                        Score    = 501, IcoPath = Constants.IndexImagePath
                    });
                }

                var icoPath      = (record.Type == ResultType.File) ? Constants.FileImagePath : Constants.FolderImagePath;
                var fileOrFolder = (record.Type == ResultType.File) ? "file" : "folder";

                if (!Settings.QuickAccessLinks.Any(x => x.Path == record.FullPath))
                {
                    contextMenus.Add(new Result
                    {
                        Title    = Context.API.GetTranslation("plugin_explorer_add_to_quickaccess_title"),
                        SubTitle = string.Format(Context.API.GetTranslation("plugin_explorer_add_to_quickaccess_subtitle"), fileOrFolder),
                        Action   = (context) =>
                        {
                            Settings.QuickAccessLinks.Add(new AccessLink {
                                Path = record.FullPath, Type = record.Type
                            });

                            Context.API.ShowMsg(Context.API.GetTranslation("plugin_explorer_addfilefoldersuccess"),
                                                string.Format(
                                                    Context.API.GetTranslation("plugin_explorer_addfilefoldersuccess_detail"),
                                                    fileOrFolder),
                                                Constants.ExplorerIconImageFullPath);

                            ViewModel.Save();

                            return(true);
                        },
                        SubTitleToolTip = Context.API.GetTranslation("plugin_explorer_contextmenu_titletooltip"),
                        TitleToolTip    = Context.API.GetTranslation("plugin_explorer_contextmenu_titletooltip"),
                        IcoPath         = Constants.QuickAccessImagePath
                    });
                }
                else
                {
                    contextMenus.Add(new Result
                    {
                        Title    = Context.API.GetTranslation("plugin_explorer_remove_from_quickaccess_title"),
                        SubTitle = string.Format(Context.API.GetTranslation("plugin_explorer_remove_from_quickaccess_subtitle"), fileOrFolder),
                        Action   = (context) =>
                        {
                            Settings.QuickAccessLinks.Remove(Settings.QuickAccessLinks.FirstOrDefault(x => x.Path == record.FullPath));

                            Context.API.ShowMsg(Context.API.GetTranslation("plugin_explorer_removefilefoldersuccess"),
                                                string.Format(
                                                    Context.API.GetTranslation("plugin_explorer_removefilefoldersuccess_detail"),
                                                    fileOrFolder),
                                                Constants.ExplorerIconImageFullPath);

                            ViewModel.Save();

                            return(true);
                        },
                        SubTitleToolTip = Context.API.GetTranslation("plugin_explorer_contextmenu_remove_titletooltip"),
                        TitleToolTip    = Context.API.GetTranslation("plugin_explorer_contextmenu_remove_titletooltip"),
                        IcoPath         = Constants.RemoveQuickAccessImagePath
                    });
                }

                contextMenus.Add(new Result
                {
                    Title    = Context.API.GetTranslation("plugin_explorer_copypath"),
                    SubTitle = $"Copy the current {fileOrFolder} path to clipboard",
                    Action   = (context) =>
                    {
                        try
                        {
                            Clipboard.SetText(record.FullPath);
                            return(true);
                        }
                        catch (Exception e)
                        {
                            var message = "Fail to set text in clipboard";
                            LogException(message, e);
                            Context.API.ShowMsg(message);
                            return(false);
                        }
                    },
                    IcoPath = Constants.CopyImagePath
                });

                contextMenus.Add(new Result
                {
                    Title    = Context.API.GetTranslation("plugin_explorer_copyfilefolder") + $" {fileOrFolder}",
                    SubTitle = $"Copy the {fileOrFolder} to clipboard",
                    Action   = (context) =>
                    {
                        try
                        {
                            Clipboard.SetFileDropList(new System.Collections.Specialized.StringCollection {
                                record.FullPath
                            });
                            return(true);
                        }
                        catch (Exception e)
                        {
                            var message = $"Fail to set {fileOrFolder} in clipboard";
                            LogException(message, e);
                            Context.API.ShowMsg(message);
                            return(false);
                        }
                    },
                    IcoPath = icoPath
                });

                if (record.Type == ResultType.File || record.Type == ResultType.Folder)
                {
                    contextMenus.Add(new Result
                    {
                        Title    = Context.API.GetTranslation("plugin_explorer_deletefilefolder") + $" {fileOrFolder}",
                        SubTitle = Context.API.GetTranslation("plugin_explorer_deletefilefolder_subtitle") + $" {fileOrFolder}",
                        Action   = (context) =>
                        {
                            try
                            {
                                if (MessageBox.Show(
                                        string.Format(Context.API.GetTranslation("plugin_explorer_deletefilefolderconfirm"), fileOrFolder),
                                        string.Empty,
                                        MessageBoxButton.YesNo,
                                        MessageBoxIcon.Warning)
                                    == DialogResult.No)
                                {
                                    return(false);
                                }

                                if (record.Type == ResultType.File)
                                {
                                    File.Delete(record.FullPath);
                                }
                                else
                                {
                                    Directory.Delete(record.FullPath, true);
                                }

                                Task.Run(() =>
                                {
                                    Context.API.ShowMsg(Context.API.GetTranslation("plugin_explorer_deletefilefoldersuccess"),
                                                        string.Format(Context.API.GetTranslation("plugin_explorer_deletefilefoldersuccess_detail"), fileOrFolder),
                                                        Constants.ExplorerIconImageFullPath);
                                });
                            }
                            catch (Exception e)
                            {
                                var message = $"Fail to delete {fileOrFolder} at {record.FullPath}";
                                LogException(message, e);
                                Context.API.ShowMsg(message);
                                return(false);
                            }

                            return(true);
                        },
                        IcoPath = Constants.DeleteFileFolderImagePath
                    });
                }

                if (record.Type == ResultType.File && CanRunAsDifferentUser(record.FullPath))
                {
                    contextMenus.Add(new Result
                    {
                        Title    = Context.API.GetTranslation("plugin_explorer_runasdifferentuser"),
                        SubTitle = Context.API.GetTranslation("plugin_explorer_runasdifferentuser_subtitle"),
                        Action   = (context) =>
                        {
                            try
                            {
                                Task.Run(() => ShellCommand.RunAsDifferentUser(record.FullPath.SetProcessStartInfo()));
                            }
                            catch (FileNotFoundException e)
                            {
                                var name    = "Plugin: Folder";
                                var message = $"File not found: {e.Message}";
                                Context.API.ShowMsg(name, message);
                            }

                            return(true);
                        },
                        IcoPath = Constants.DifferentUserIconImagePath
                    });
                }
            }

            return(contextMenus);
        }
예제 #22
0
        /// <summary>
        /// Loads the bar for the given session. If the user is a member of several, either the last one is used,
        /// or a selection dialog is presented.
        /// </summary>
        /// <param name="session">The current session.</param>
        /// <param name="showCommunityId">Force this community to show.</param>
        public async void LoadSessionBar(CommunitySession session, string?showCommunityId = null)
        {
            if (this.firstBar && AppOptions.Current.Launch.BarFile != null)
            {
                this.LoadFromBarJson(AppOptions.Current.Launch.BarFile);
                return;
            }

            this.Logger.LogInformation($"Loading a bar ({session.Communities.Length} communities)");

            UserBar?bar;

            string[] lastCommunities = AppOptions.Current.Communities.ToArray();
            string?  lastCommunityId = showCommunityId ?? AppOptions.Current.LastCommunity;

            if (string.IsNullOrWhiteSpace(lastCommunityId))
            {
                lastCommunityId = null;
            }

            UserCommunity?community = null;
            UserBar?      userBar   = null;

            if (session.Communities.Length == 0)
            {
                MessageBox.Show("You are not part of a Morphic community yet.", "Morphic");
            }
            else if (session.Communities.Length == 1)
            {
                community = session.Communities.First();
            }
            else
            {
                // The user is a member of multiple communities.

                // See if any membership has changed
                bool changed = showCommunityId != null && session.Communities.Length != lastCommunities.Length ||
                               !session.Communities.Select(c => c.Id).OrderBy(id => id)
                               .SequenceEqual(lastCommunities.OrderBy(id => id));

                if (!changed && lastCommunityId != null)
                {
                    community = session.Communities.FirstOrDefault(c => c.Id == lastCommunityId);
                }

                if (community == null)
                {
                    this.Logger.LogInformation("Showing community picker");

                    // Load the bars while the picker is shown
                    Dictionary <string, Task <UserBar> > bars =
                        session.Communities.ToDictionary(c => c.Id, c => session.GetBar(c.Id));

                    // Show the picker
                    CommunityPickerWindow picker = new CommunityPickerWindow(session.Communities);
                    bool gotCommunity            = picker.ShowDialog() == true;
                    community = gotCommunity ? picker.SelectedCommunity : null;

                    if (community != null)
                    {
                        userBar = await bars[community.Id];
                    }
                }
            }

            if (community != null)
            {
                userBar ??= await session.GetBar(community.Id);

                this.Logger.LogInformation($"Showing bar for community {community.Id} {community.Name}");
                string  barJson = this.GetUserBarJson(userBar);
                BarData?barData = this.LoadFromBarJson(userBar.Id, barJson);
                if (barData != null)
                {
                    barData.CommunityId = community.Id;
                }
            }

            AppOptions.Current.Communities   = session.Communities.Select(c => c.Id).ToArray();
            AppOptions.Current.LastCommunity = community?.Id;
        }
예제 #23
0
        public void Receiver()
        {
            try
            {
                string conversationId       = "";
                string id                   = "";
                bool   notifyContactPersons = false;
                string emailId              = "";
                string emailAddress         = "";
                while (_client.Connected)
                {
                    byte response = _reader.ReadByte();
                    switch (response)
                    {
                    case MessageDictionary.NewNotification:
                        _writer.Write(MessageDictionary.OK);

                        List <string> referenceFields = new List <string>();

                        string   notificationId   = _reader.ReadString();
                        string   notificationText = _reader.ReadString();
                        DateTime notificationDate = DateTime.ParseExact(_reader.ReadString(), "dd-MM-yyyy HH:mm:ss",
                                                                        CultureInfo.InvariantCulture);
                        int referenceFieldCount = _reader.ReadInt32();

                        for (int i = 0; i < referenceFieldCount; i++)
                        {
                            referenceFields.Add(_reader.ReadString());
                        }

                        if (_reader.Read() == MessageDictionary.EndOfMessage)
                        {
                            switch (_reader.ReadByte())
                            {
                                #region NewMessage

                            case MessageDictionary.NewMessage:
                                id             = _reader.ReadString();
                                conversationId = _reader.ReadString();
                                string authorId          = _reader.ReadString();
                                string authorFrom        = _reader.ReadString();
                                string initialDateString = _reader.ReadString();

                                byte[] previewData = ReceiveFile();

                                List <string> attachmentIds = new List <string>();

                                int attachmentCount = _reader.ReadInt32();

                                for (int j = 0; j < attachmentCount; j++)
                                {
                                    attachmentIds.Add(_reader.ReadString());
                                }

                                MemoryStream stream = new MemoryStream(previewData);

                                BitmapImage previewImage = new BitmapImage();
                                previewImage.BeginInit();
                                previewImage.StreamSource = stream;
                                previewImage.EndInit();
                                previewImage.Freeze();

                                byte type = _reader.ReadByte();

                                DateTime initialDate = DateTime.ParseExact(initialDateString,
                                                                           "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                                ConversationMessageModel message = new ConversationMessageModel(id,
                                                                                                conversationId,
                                                                                                authorId,
                                                                                                authorFrom, initialDate, true, previewImage, false, attachmentIds);

                                switch (type)
                                {
                                case MessageDictionary.MessageTypeEmail:
                                    string subject = _reader.ReadString();
                                    string content = _reader.ReadString();

                                    ConversationEmailMessageModel emailMessage =
                                        new ConversationEmailMessageModel(message,
                                                                          subject, content);
                                    message = emailMessage;
                                    break;

                                case MessageDictionary.MessageTypePhoneCall:
                                    string recipientPhoneNumber = _reader.ReadString();
                                    string description          = _reader.ReadString();
                                    bool   answered             = _reader.ReadBoolean();

                                    ConversationPhoneMessageModel phoneMessage =
                                        new ConversationPhoneMessageModel(message, recipientPhoneNumber,
                                                                          description, answered);
                                    message = phoneMessage;
                                    break;
                                }

                                NewConversationMessageArrived?.Invoke(this,
                                                                      new NewConversationMessageArrivedEventArgs()
                                {
                                    Message      = message,
                                    Notification =
                                        new NotificationModel(notificationId, notificationText,
                                                              referenceFields,
                                                              notificationDate, false)
                                });
                                break;

                                #endregion

                                #region RenameConversation

                            case MessageDictionary.RenameConversation:
                                conversationId = _reader.ReadString();
                                string oldName = _reader.ReadString();
                                string newName = _reader.ReadString();

                                ConversationRenamed?.Invoke(this, new ConversationRenamedEventArgs()
                                {
                                    ConversationId = conversationId,
                                    OldName        = oldName,
                                    NewName        = newName,
                                    Notification   = new NotificationModel(notificationId, notificationText,
                                                                           referenceFields,
                                                                           notificationDate, false)
                                });
                                break;

                                #endregion

                                #region RenameFile

                            case MessageDictionary.RenameFile:
                                conversationId = _reader.ReadString();
                                oldName        = _reader.ReadString();
                                newName        = _reader.ReadString();

                                FileRenamed?.Invoke(this, new FileRenamedEventArgs()
                                {
                                    FileId       = conversationId,
                                    OldName      = oldName,
                                    NewName      = newName,
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;

                                #endregion

                                #region AddConversationMembers

                            case MessageDictionary.AddConversationMembers:
                                conversationId = _reader.ReadString();
                                string personId    = _reader.ReadString();
                                string personColor = _reader.ReadString();

                                ConversationMembersAdded?.Invoke(this,
                                                                 new ConversationMembersAddedEventArgs()
                                {
                                    ConversationId = conversationId,
                                    PersonId       = personId,
                                    PersonColor    = personColor,
                                    Notification   = new NotificationModel(notificationId, notificationText,
                                                                           referenceFields,
                                                                           notificationDate, false)
                                });
                                break;

                                #endregion

                                #region RemoveConversationMember

                            case MessageDictionary.RemoveConversationMember:
                                conversationId = _reader.ReadString();
                                personId       = _reader.ReadString();

                                ConversationMemberRemoved?.Invoke(this,
                                                                  new ConversationMemberRemovedEventArgs()
                                {
                                    ConversationId = conversationId,
                                    PersonId       = personId,
                                    Notification   = new NotificationModel(notificationId, notificationText,
                                                                           referenceFields,
                                                                           notificationDate, false)
                                });
                                break;

                                #endregion

                                #region ConversationSettingsChanged

                            case MessageDictionary.ChangeConversationSettings:
                                conversationId       = _reader.ReadString();
                                notifyContactPersons = _reader.ReadBoolean();
                                ConversationSettingsChanged?.Invoke(this,
                                                                    new ConversationSettingsChangedEventArgs()
                                {
                                    ConversationId       = conversationId,
                                    NotifyContactPersons = notifyContactPersons,
                                    Notification         = new NotificationModel(notificationId, notificationText,
                                                                                 referenceFields,
                                                                                 notificationDate, false)
                                });
                                break;

                                #endregion

                                #region NewCompany

                            case MessageDictionary.NewCompany:
                                string companyId   = _reader.ReadString();
                                string companyName = _reader.ReadString();

                                NewCompanyArrived?.Invoke(this, new NewCompanyEventArgs()
                                {
                                    Company      = new CompanyModel(companyId, companyName),
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;

                                #endregion

                                #region RenameCompany

                            case MessageDictionary.RenameCompany:
                                companyId = _reader.ReadString();
                                newName   = _reader.ReadString();

                                CompanyRenamed?.Invoke(this, new CompanyRenamedEventArgs()
                                {
                                    CompanyId    = companyId,
                                    NewName      = newName,
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;

                                #endregion

                                #region RemoveCompanyEvent

                            case MessageDictionary.RemoveCompany:
                                companyId = _reader.ReadString();

                                CompanyRemoved?.Invoke(this, new CompanyRemovedEventArgs()
                                {
                                    CompanyId    = companyId,
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;

                                #endregion

                                #region UpdatePersonDetails

                            case MessageDictionary.UpdatePersonDetails:

                                string PersonId         = _reader.ReadString();
                                string PersonFirstName  = _reader.ReadString();
                                string PersonLastName   = _reader.ReadString();
                                string PersonGenderCode = _reader.ReadString();
                                string PersonCompanyId  = _reader.ReadString();

                                Gender PersonGender = (Gender)Convert.ToInt32(PersonGenderCode);

                                PersonModel contactPerson = new PersonModel(PersonId, PersonFirstName, PersonLastName,
                                                                            PersonGender,
                                                                            PersonCompanyId, true);

                                int emailAddressCount = _reader.ReadInt32();

                                for (int j = 0; j < emailAddressCount; j++)
                                {
                                    emailId = _reader.ReadString();
                                    string emailName = _reader.ReadString();
                                    emailAddress = _reader.ReadString();

                                    EmailAddressModel emailAddressModel = new EmailAddressModel(emailId,
                                                                                                emailAddress,
                                                                                                emailName);
                                    contactPerson.EmailAddresses.Add(emailAddressModel);
                                }

                                int phoneNumberCount = _reader.ReadInt32();

                                for (int j = 0; j < phoneNumberCount; j++)
                                {
                                    string phoneNumberId = _reader.ReadString();
                                    string phoneName     = _reader.ReadString();
                                    string phoneNumber   = _reader.ReadString();

                                    PhoneNumberModel phoneNumberModel = new PhoneNumberModel(phoneNumberId, phoneNumber,
                                                                                             phoneName);
                                    contactPerson.PhoneNumbers.Add(phoneNumberModel);
                                }

                                ContactDetailsUpdated?.Invoke(this, new ContactDetailsUpdatedEventArgs()
                                {
                                    NewData      = contactPerson,
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;

                                #endregion

                                #region NewExternalContact

                            case MessageDictionary.NewExternalContact:
                                _writer.Write(MessageDictionary.OK);

                                PersonId         = _reader.ReadString();
                                PersonFirstName  = _reader.ReadString();
                                PersonLastName   = _reader.ReadString();
                                PersonGenderCode = _reader.ReadString();
                                PersonCompanyId  = _reader.ReadString();

                                PersonGender = (Gender)Convert.ToInt32(PersonGenderCode);

                                contactPerson = new PersonModel(PersonId, PersonFirstName, PersonLastName,
                                                                PersonGender,
                                                                PersonCompanyId, true);

                                emailAddressCount = _reader.ReadInt32();

                                for (int j = 0; j < emailAddressCount; j++)
                                {
                                    emailId = _reader.ReadString();
                                    string emailName = _reader.ReadString();
                                    emailAddress = _reader.ReadString();

                                    EmailAddressModel emailAddressModel = new EmailAddressModel(emailId, emailAddress,
                                                                                                emailName);
                                    contactPerson.EmailAddresses.Add(emailAddressModel);
                                }

                                phoneNumberCount = _reader.ReadInt32();

                                for (int j = 0; j < phoneNumberCount; j++)
                                {
                                    string phoneNumberId = _reader.ReadString();
                                    string phoneName     = _reader.ReadString();
                                    string phoneNumber   = _reader.ReadString();

                                    PhoneNumberModel phoneNumberModel = new PhoneNumberModel(phoneNumberId, phoneNumber,
                                                                                             phoneName);
                                    contactPerson.PhoneNumbers.Add(phoneNumberModel);
                                }

                                NewExternalContact?.Invoke(this, new NewExternalContactEventArgs()
                                {
                                    NewData      = contactPerson,
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;

                                #endregion

                                #region NewExternalContact

                            case MessageDictionary.RemoveExternalContact:

                                personId = _reader.ReadString();

                                ExternalContactRemoved?.Invoke(this, new ExternalContactRemovedEventArgs()
                                {
                                    PersonId     = personId,
                                    Notification = new NotificationModel(notificationId, notificationText,
                                                                         referenceFields,
                                                                         notificationDate, false)
                                });
                                break;
                                #endregion

                                #region RemoveConversation
                            case MessageDictionary.RemoveConversation:
                                _writer.Write(MessageDictionary.OK);
                                conversationId = _reader.ReadString();

                                ConversationRemoved?.Invoke(this, new ConversationRemovedEventArgs()
                                {
                                    ConversationId = conversationId,
                                    Notification   = new NotificationModel(notificationId, notificationText,
                                                                           referenceFields,
                                                                           notificationDate, false)
                                });
                                break;
                                #endregion
                            }
                        }
                        break;

                        #region NewFiles

                    case MessageDictionary.NewFiles:
                        List <FileModel> files = new List <FileModel>();
                        files.Clear();
                        _writer.Write(MessageDictionary.OK);
                        int fileCount = _reader.ReadInt32();

                        for (int i = 0; i < fileCount; i++)
                        {
                            conversationId = _reader.ReadString();
                            id             = _reader.ReadString();
                            string    name        = _reader.ReadString();
                            string    contentType = _reader.ReadString();
                            long      size        = _reader.ReadInt64();
                            string    dateAdded   = _reader.ReadString();
                            FileModel file        = new FileModel(id, name, new ContentType(contentType), size,
                                                                  DateTime.ParseExact(dateAdded, "dd-MM-yyyy", CultureInfo.InvariantCulture))
                            {
                                ConversationId = conversationId
                            };

                            files.Add(file);
                        }

                        NewFilesArrived?.Invoke(this, new NewFilesArrivedEventArgs()
                        {
                            Files = files
                        });
                        break;

                        #endregion

                        #region NewConversation

                    case MessageDictionary.NewConversation:
                        _writer.Write(MessageDictionary.OK);

                        conversationId = _reader.ReadString();
                        string conversationName  = _reader.ReadString();
                        string visibleId         = _reader.ReadString();
                        string dateCreatedString = _reader.ReadString();
                        notifyContactPersons = _reader.ReadBoolean();


                        DateTime dateCreated = DateTime.ParseExact(dateCreatedString, "dd-MM-yyyy HH:mm:ss",
                                                                   CultureInfo.InvariantCulture);

                        int memberCount = _reader.ReadInt32();

                        List <string> memberIds    = new List <string>();
                        List <string> memberColors = new List <string>();
                        for (int j = 0; j < memberCount; j++)
                        {
                            string memberId    = _reader.ReadString();
                            string memberColor = _reader.ReadString();

                            memberIds.Add(memberId);
                            memberColors.Add(memberColor);
                        }

                        List <ConversationMessageModel> messages = new List <ConversationMessageModel>();

                        if (_reader.Read() == MessageDictionary.OK)
                        {
                            int messageCount = _reader.ReadInt32();
                            for (int i = 0; i < messageCount; i++)
                            {
                                id = _reader.ReadString();
                                string  authorId          = _reader.ReadString();
                                string  authorFrom        = _reader.ReadString();
                                string  initialDateString = _reader.ReadString();
                                Boolean received          = _reader.ReadBoolean();

                                byte[] previewData = ReceiveFile();

                                List <string> attachmentIds = new List <string>();

                                int attachmentCount = _reader.ReadInt32();

                                for (int j = 0; j < attachmentCount; j++)
                                {
                                    attachmentIds.Add(_reader.ReadString());
                                }

                                MemoryStream stream       = new MemoryStream(previewData);
                                BitmapImage  previewImage = new BitmapImage();
                                previewImage.BeginInit();
                                previewImage.StreamSource = stream;
                                previewImage.EndInit();

                                previewImage.Freeze();

                                DateTime initialDate = DateTime.ParseExact(initialDateString, "dd-MM-yyyy HH:mm:ss",
                                                                           CultureInfo.InvariantCulture);
                                ConversationMessageModel message = new ConversationMessageModel(id, conversationId,
                                                                                                authorId,
                                                                                                authorFrom, initialDate, received, previewImage, false, attachmentIds);

                                byte type = _reader.ReadByte();

                                if (type == MessageDictionary.MessageTypeEmail)
                                {
                                    string subject = _reader.ReadString();
                                    string content = _reader.ReadString();

                                    ConversationEmailMessageModel emailMessage =
                                        new ConversationEmailMessageModel(message,
                                                                          subject, content);
                                    message = emailMessage;
                                }
                                else if (type == MessageDictionary.MessageTypePhoneCall)
                                {
                                    string recipientPhoneNumber = _reader.ReadString();
                                    string callDescription      = _reader.ReadString();
                                    bool   callAnswered         = _reader.ReadBoolean();
                                    ConversationPhoneMessageModel phoneMessage =
                                        new ConversationPhoneMessageModel(message, recipientPhoneNumber,
                                                                          callDescription, callAnswered);
                                    message = phoneMessage;
                                }

                                if (message != null)
                                {
                                    messages.Add(message);
                                }
                            }

                            if (_reader.Read() == MessageDictionary.EndOfMessage)
                            {
                                ConversationModel conversation = new ConversationModel(conversationId,
                                                                                       conversationName, visibleId, dateCreated,
                                                                                       memberIds, memberColors, notifyContactPersons);
                                messages.ForEach(obj => conversation.AddMessage(obj));
                                NewConversationArrived?.Invoke(this,
                                                               new NewConversationArrivedEventArgs()
                                {
                                    Conversation = conversation
                                });
                            }
                        }
                        break;

                        #endregion

                        #region RemoveConversation

                    case MessageDictionary.RemoveConversation:
                        _writer.Write(MessageDictionary.OK);
                        conversationId = _reader.ReadString();
                        ConversationRemoved?.Invoke(this,
                                                    new ConversationRemovedEventArgs()
                        {
                            ConversationId = conversationId
                        });
                        break;

                        #endregion

                        #region NewEmailAddress

                    case MessageDictionary.AddEmailAddress:
                        _writer.Write(MessageDictionary.OK);

                        emailId      = _reader.ReadString();
                        emailAddress = _reader.ReadString();
                        string login       = _reader.ReadString();
                        string imapHost    = _reader.ReadString();
                        int    imapPort    = _reader.ReadInt32();
                        bool   imapUseSel  = _reader.ReadBoolean();
                        string smtpHost    = _reader.ReadString();
                        int    smtpPort    = _reader.ReadInt32();
                        bool   smtpUseSsl  = _reader.ReadBoolean();
                        string addressName = _reader.ReadString();

                        NewEmailAddress?.Invoke(this, new NewEmailAddressEventArgs()
                        {
                            Id         = emailId,
                            Login      = login,
                            Address    = emailAddress,
                            ImapHost   = imapHost,
                            ImapPort   = imapPort,
                            ImapUseSsl = imapUseSel,
                            SmtpHost   = smtpHost,
                            SmtpPort   = smtpPort,
                            SmtpUseSsl = smtpUseSsl,
                            Name       = addressName
                        });

                        break;

                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
                ErrorHelper.LogError(ex);
                Logout();
            }
        }
예제 #24
0
        static PluginToggleManager()
        {
            PluginToggle aighs2, aig, aig2, hs2, dhh = null;

            aig = new PluginToggle("AI_Graphics", Localizable.ToggleAiGraphics, Localizable.TooltipGraphicsMod, "AI_Graphics", delegate(bool b)
            {
                if (b)
                {
                    dhh.SetIsChecked(false);
                    MessageBox.Show("To use this mod, Press F5 during the game.", "Usage");
                }
            }, false);
            aig2 = new PluginToggle("AIGraphics", Localizable.ToggleGraphicsMod, Localizable.TooltipGraphicsMod, "AIGraphics", delegate(bool b)
            {
                if (b)
                {
                    dhh.SetIsChecked(false);
                    MessageBox.Show("To use this mod, Press F5 during the game.", "Usage");
                }
            }, false);
            hs2 = new PluginToggle("HS2Graphics", Localizable.ToggleGraphicsMod, Localizable.TooltipGraphicsMod, "HS2Graphics", delegate(bool b)
            {
                if (b)
                {
                    dhh.SetIsChecked(false);
                    MessageBox.Show("To use this mod, Press F5 during the game.", "Usage");
                }
            }, false);
            aighs2 = new PluginToggle("Graphics", Localizable.ToggleGraphicsMod, Localizable.TooltipGraphicsMod, "Graphics", delegate(bool b)
            {
                if (b)
                {
                    dhh.SetIsChecked(false);
                    MessageBox.Show("To use this mod, Press F5 during the game.", "Usage");
                }
            }, false);
            dhh = new PluginToggle("DHH", Localizable.ToggleDhh, Localizable.TooltipDhh, "DHH_AI4", delegate(bool b)
            {
                if (b)
                {
                    aig.SetIsChecked(false);
                    aig2.SetIsChecked(false);
                    hs2.SetIsChecked(false);
                    aighs2.SetIsChecked(false);
                    MessageBox.Show("To use this mod, Press P during the game.", "Usage");
                }
            }, false);

            _toggleList = new List <PluginToggle>
            {
                aig,
                aig2,
                hs2,
                aighs2,
                dhh,
                new PluginToggle("DHHPH", Localizable.ToggleDhh, Localizable.TooltipDhhPH, "ProjectHighHeel", null, true),
                new PluginToggle("GgmodForPlayClub", Localizable.ToggleGGmod, Localizable.TooltipGGmod, "GgmodForPlayClub", null, true),
                new PluginToggle("GgmodForPlayClubStudio", Localizable.ToggleGGmodstudioPC, Localizable.TooltipGGmod, "GgmodForPlayClubStudio", null, true),
                new PluginToggle("TouchyFeely", Localizable.ToggleTouchyFeely, Localizable.TooltipTouchyFeely, "TouchyFeely", null, true),
                new PluginToggle("GGmod", Localizable.ToggleGGmod, Localizable.TooltipGGmod, "GgmodForHS", null, true),
                new PluginToggle("GGmodstudio", Localizable.ToggleGGmodstudio, Localizable.TooltipGGmod, "GgmodForHS_Studio", null, true),
                new PluginToggle("GGmodneo", Localizable.ToggleGGmodneo, Localizable.TooltipGGmod, "GgmodForHS_NEO", null, true),
                new PluginToggle("HoneyPot", Localizable.ToggleHoneyPot, Localizable.TooltipHoneyPot, "HoneyPot", delegate(bool b)
                {
                    if (b)
                    {
                        MessageBox.Show("When HoneyPot is enabled, the game will use a bit longer to load in some scenes due to checking for HoneySelect assets, making it appear to be freezing for a few seconds. This is completely normal.\n\nJust disable this option again if you would rather not have that freeze.", "Usage");
                    }
                }, true),
                new PluginToggle("PHIBL", Localizable.TogglePHIBL, Localizable.TooltipPHIBL, "PHIBL", delegate(bool b)
                {
                    if (b)
                    {
                        MessageBox.Show("To use this mod, Press F5 during the game.", "Usage");
                        DisableHelper("PH_PHIBL_PresetLoad_Nyaacho", true, false);
                        DisableHelper("PH_PHIBL_PresetLoad_Original", true, false);
                    }
                    else
                    {
                        DisableHelper("PH_PHIBL_PresetLoad_Nyaacho", true, true);
                        DisableHelper("PH_PHIBL_PresetLoad_Original", true, true);
                    }
                }, true),
                new PluginToggle("RimRemover", Localizable.ToggleRimRemover, "", "*RimRemover", null, false),
                new PluginToggle("AutoSave", Localizable.ActivateAutosave, "", "*AutoSave", null, false),
                new PluginToggle("ShortcutPlugin", Localizable.ToggleShortcutHS, "", "ShortcutHSParty", null, true),
                new PluginToggle("BetterAA", "Activate BetterAA", "", "HS2_BetterAA", null, false),
                new PluginToggle("Stiletto", Localizable.ToggleStiletto, Localizable.TooltipGGmod, "Stiletto", null, false),
                new PluginToggle("VRMod", Localizable.ToggleVRMod, Localizable.TooltipVRMod, "PlayHomeVR", delegate(bool b)
                {
                    if (b)
                    {
                        MessageBox.Show("To use this mod, open SteamVR before opening either the main game or studio.", "Usage");
                    }
                }, true),
                new PluginToggle("PCVRMod", Localizable.ToggleVRMod, Localizable.TooltipVRMod, "PlayClubVR", delegate(bool b)
                {
                    if (b)
                    {
                        DisableHelper("LeapCSharp.NET3.5", true, false);
                        DisableHelper("GamePadClub", true, false);
                        DisableHelper("PlayClubStudioVR", true, false);
                        DisableHelper("SpeechTransport", true, false);
                        DisableHelper("VRGIN.U46", true, false);
                        DisableHelper("WindowsInput", true, false);
                        DisableHelper("XInputDotNetPure", true, false);
                    }
                    else
                    {
                        DisableHelper("LeapCSharp.NET3.5", true, true);
                        DisableHelper("GamePadClub", true, true);
                        DisableHelper("PlayClubStudioVR", true, true);
                        DisableHelper("SpeechTransport", true, true);
                        DisableHelper("VRGIN.U46", true, true);
                        DisableHelper("WindowsInput", true, true);
                        DisableHelper("XInputDotNetPure", true, true);
                    }
                }, true),
            };
        }
예제 #25
0
 private void InfluxDb_OnQuerySuccess(object sender, DataBase.QuerySuccessEventArgs e)
 {
     Dispatcher?.Invoke(() => { MessageBox.Show("Query Successful!"); });
 }
예제 #26
0
        /// <summary>
        /// Action lors du clic sur le menuItem sélectionné du contextMenu du label "lbl_sendOffer".
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void lbl_MenuItemSelected_MouseLeftButtonUp(object sender, RoutedEventArgs e)
        {
            MenuItem clickedMenuItem         = sender as MenuItem;
            string   serviceName             = clickedMenuItem.Header.ToString();
            string   temporaryTitle          = InterimDatabase.GetTemporaryTitle(TemporaryID);
            string   temporaryName           = InterimDatabase.GetTemporaryName(TemporaryID);
            bool     isCorrectServiceName    = (!string.IsNullOrEmpty(serviceName));
            bool     isCorrectTemporaryTitle = (!string.IsNullOrEmpty(temporaryTitle));
            bool     isCorrectTemporaryName  = (!string.IsNullOrEmpty(temporaryName));

            // Vérifie le contenu des informations de l'intérimaire.
            if (isCorrectTemporaryTitle && isCorrectTemporaryName && isCorrectServiceName)
            {
                string messageBox = Results_Val.Default.ConfirmSendEmail + temporaryTitle + " " + temporaryName + Results_Val.Default.ForServiceOf + serviceName + Results_Val.Default.Ask;

                // Message de confirmation.
                DialogResult dialogResult = MessageBox.Show(messageBox, Results_Val.Default.TitleConfirmSendEmail, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                // Vérifie la réponse au message de confirmation.
                if (dialogResult == DialogResult.Yes)
                {
                    string temporaryEmailAdress = InterimDatabase.GetTemporaryEmailAdress(TemporaryID);
                    bool   isCorrectEmailAdress = (!string.IsNullOrEmpty(temporaryEmailAdress));

                    // Vérifie le contenu de l'adresse email récupérée.
                    if (isCorrectEmailAdress)
                    {
                        string dayName            = InterimDatabase.DayName();
                        string dayNumber          = InterimDatabase.DayNumber();
                        string month              = InterimDatabase.MonthName();
                        string workTimetableStart = InterimDatabase.ReturnWorkTimetableStart();
                        string workTimetableEnd   = InterimDatabase.ReturnWorkTimetableEnd();

                        List <string> offerInformations = new List <string>();

                        offerInformations.Add(temporaryEmailAdress);
                        offerInformations.Add(temporaryTitle);
                        offerInformations.Add(temporaryName);
                        offerInformations.Add(dayName);
                        offerInformations.Add(dayNumber);
                        offerInformations.Add(month);
                        offerInformations.Add(workTimetableStart);
                        offerInformations.Add(workTimetableEnd);
                        offerInformations.Add(serviceName);

                        // Crée un message de proposition de mission.
                        List <string> bodyMessageInformations = CreateBodyMessage(Results_Code.Default.TemplateOfferPath, offerInformations);
                        _MailItem     message = CreateMessage(bodyMessageInformations);

                        // Vérifie la création du message, l'envoi de l'email de proposition de mission, l'enregistrement de la date d'envoi et du service de la proposition de mission.
                        if (IsCreateMessage(message) && IsSentEmail(message) && InterimDatabase.SetSendDateAndService(TemporaryID, serviceName))
                        {
                            // Affiche un message de réussite de l'envoi de l'email.
                            MessageBox.Show(Results_Val.Default.EmailSent, Results_Val.Default.InformationTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // Rafraichit l'interface des résultats.
                            usc_results refreshResults = new usc_results();
                            Switcher.Switch(refreshResults);
                        }
                        else
                        {
                            // Affiche un message d'échec de l'envoi de l'email de proposition de mission.
                            MessageBox.Show(Results_Val.Default.NullSendEmail, Results_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        // Affiche un message d'erreur.
                        MessageBox.Show(Results_Val.Default.NullEmailAdress, Results_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                // Affiche un message d'erreur.
                MessageBox.Show(Results_Val.Default.NullInformations, Results_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #27
0
 private void InfluxDb_OnQueryComplete(object sender, DataBase.QueryCompleteEventArgs e)
 {
     Dispatcher?.Invoke(() => { MessageBox.Show(e.Result.ToString()); });
 }
 public static void BadModMessage()
 {
     MessageBox.Show("This is not a valid Sonic 3 A.I.R. Mod. A valid mod requires a mod.json, and either this isn't a mod or it's a legacy mod. If you know for sure that this is a mod, then it's probably a legacy mod. You can't use legacy mods that work without them going forward.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
예제 #29
0
        public Result OnStartup(UIControlledApplication application)
        {
            // Revit2015+ has disabled hardware acceleration for WPF to
            // avoid issues with rendering certain elements in the Revit UI.
            // Here we get it back, by setting the ProcessRenderMode to Default,
            // signifying that we want to use hardware rendering if it's
            // available.

            RenderOptions.ProcessRenderMode = RenderMode.Default;

            try
            {
                if (false == TryResolveDynamoCore())
                {
                    return(Result.Failed);
                }

                UIControlledApplication = application;
                ControlledApplication   = application.ControlledApplication;

                SubscribeAssemblyResolvingEvent();
                SubscribeApplicationEvents();

                TransactionManager.SetupManager(new AutomaticTransactionStrategy());
                ElementBinder.IsEnabled = true;

                // Create new ribbon panel
                var panels      = application.GetRibbonPanels();
                var ribbonPanel = panels.FirstOrDefault(p => p.Name.Contains(Resources.App_Description));
                if (null == ribbonPanel)
                {
                    ribbonPanel = application.CreateRibbonPanel(Resources.App_Description);
                }

                var fvi        = FileVersionInfo.GetVersionInfo(assemblyName);
                var dynVersion = String.Format(Resources.App_Name, fvi.FileMajorPart, fvi.FileMinorPart);

                DynamoButton =
                    (PushButton)
                    ribbonPanel.AddItem(
                        new PushButtonData(
                            dynVersion,
                            dynVersion,
                            assemblyName,
                            "Dynamo.Applications.DynamoRevit"));

                Bitmap dynamoIcon = Resources.logo_square_32x32;

                BitmapSource bitmapSource =
                    Imaging.CreateBitmapSourceFromHBitmap(
                        dynamoIcon.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());

                DynamoButton.LargeImage = bitmapSource;
                DynamoButton.Image      = bitmapSource;

                RegisterAdditionalUpdaters(application);

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(Result.Failed);
            }
        }
예제 #30
0
        public void DoIt()
        {
            bool genChangeEvent = false;

            try
            {
                string result;
                int    textLine = textDoc.Selection.TopLine;
                if (textLine != textDoc.Selection.BottomLine)
                {
                    return;
                }
                textDoc.Selection.SelectLine();
                string original = textDoc.Selection.Text;
                textDoc.Selection.LineUp(false, 1);
                textDoc.Selection.SelectLine();
                string attrtext = textDoc.Selection.Text;
                textDoc.Selection.CharRight(false, 1);
                textDoc.Selection.LineDown(false, 1);

                int    i  = 0;
                string bl = string.Empty;
                while (char.IsWhiteSpace(original[i]))
                {
                    bl += original[i++];
                }
                string selLine = original.Trim();
                Regex  regex   = new Regex(@"(private[\s]*|)([^\s]+(\s*<[^\s]+|))\s+([^\s^;^=]+)\s*(=|;)");
                Match  match   = regex.Match(selLine);
                if (!match.Success)
                {
                    MessageBox.Show("Please select a private member variable declaration");
                    return;
                }
                string typeStr = match.Groups[2].Value;
                string bigname;
                string name = match.Groups[4].Value;
                if (name.StartsWith("_"))
                {
                    bigname = name.Substring(1);
                }
                else if (name.StartsWith("m_"))
                {
                    bigname = name.Substring(2);
                }
                else
                {
                    bigname = name;
                }
                bigname = bigname.Substring(0, 1).ToUpper() + bigname.Substring(1);

                string genericTypeStr      = string.Empty;
                string genericArgumentType = string.Empty;
                string genericParameter    = string.Empty;
                regex = new Regex(@"([^\s]+)\s*<([^>]+)>");
                match = regex.Match(typeStr);
                if (match.Success)
                {
                    genericTypeStr      = match.Groups[1].Value;
                    genericArgumentType = match.Groups[2].Value;
                    genericParameter    = "<" + genericArgumentType + '>';
                }

                bool isContainer = (typeStr == "IList" || typeStr == "ArrayList");
                if (genericTypeStr != string.Empty)
                {
                    isContainer = isContainer || (genericTypeStr == "IList" || genericTypeStr == "List");
                }

                bool isGenericList = genericTypeStr != string.Empty && isContainer;

//				bool isIList = (typeStr == "IList" || genericTypeStr == "IList");

                if (isContainer)
                {
                    attrtext = attrtext.Trim();
                    string elementTyp = null;
                    if (!isGenericList)
                    {
                        elementTyp = GetElementTyp(attrtext);
                    }
                    else
                    {
                        elementTyp = genericArgumentType;
                    }

                    string relationName = GetRelationName(attrtext);

                    if (elementTyp == null)
                    {
                        isContainer = false;
                    }
                    else
                    {
                        if (relationName == null)
                        {
                            int p = elementTyp.LastIndexOf(".");
                            relationName = elementTyp.Substring(p + 1);
                        }

                        bool   isComposite = (attrtext.IndexOf("RelationInfo.Composite") > -1);
                        string parameter   = elementTyp.Substring(0, 1).ToLower();
                        result = string.Empty;
                        if (isComposite)
                        {
                            result += bl + "public " + elementTyp + " New" + relationName + "()\n";
                            result += bl + "{\n";
                            result += bl + "\t" + elementTyp + " " + parameter + " = new " + elementTyp + "();\n";
                            result += bl + "\tthis." + name + ".Add(" + parameter + ");\n";
                            result += bl + "\t" + "return " + parameter + ";\n";
                            result += bl + "}\n";
                        }
                        else
                        {
                            result += bl + "public void Add" + relationName + "(" + elementTyp + " " + parameter + ")\n";
                            result += bl + "{\n";
                            result += bl + "\tthis." + name + ".Add(" + parameter + ");\n";
                            result += bl + "}\n";
                        }
                        result += bl + "public void Remove" + relationName + "(" + elementTyp + " " + parameter + ")\n";
                        result += bl + "{\n";
                        result += bl + "\tif (this." + name + ".Contains(" + parameter + "))\n";
                        result += bl + "\t\tthis." + name + ".Remove(" + parameter + ");\n";
                        result += bl + "}\n";
                        textDoc.Selection.Insert(result, (int)vsInsertFlags.vsInsertFlagsInsertAtStart);
                    }
                }
                if (!isContainer)                 // isContainer may change in the if case, so we test it again
                {
                    ConfigurationOptions options = new ConfigurationOptions(document.ProjectItem.ContainingProject);
                    if (options.GenerateChangeEvents)
                    {
                        genChangeEvent = true;
                        result         = bl + "public event EventHandler " + bigname + "Changed;\n";
                        textDoc.Selection.Insert(result, (int)vsInsertFlags.vsInsertFlagsInsertAtStart);
                    }
                }

                result = string.Empty;

                string ilistType = null;
                if (isGenericList)
                {
                    ilistType = "IEnumerable" + genericParameter;
                }
                else
                {
                    ilistType = "IEnumerable";
                }

                if (isContainer)
                {
                    result += bl + "public " + ilistType + " " + bigname + '\n';
                }
                else
                {
                    result += bl + "public " + typeStr + " " + bigname + '\n';
                }
                result += bl + "{\n";

                result += bl + "\tget => this." + name + "; \n";

                if (genChangeEvent)                  // Set Accessor in mehreren Zeilen
                {
                    result += bl + "\tset\n";
                    result += bl + "\t{\n";
                    if (isContainer)
                    {
                        if (!isGenericList)
                        {
                            result += bl + "\t\tthis." + name + " = new ArrayList( (ICollection)value );\n";
                        }
                        else
                        {
                            result += bl + "\t\tthis." + name + " = value.ToList();\n";
                        }
                    }
                    else
                    {
                        result += bl + "\t\tthis." + name + " = value;\n";
                    }
                    result += bl + "\t\tif (" + bigname + "Changed != null)\n";
                    result += bl + "\t\t\t" + bigname + "Changed(this, EventArgs.Empty);\n";
                    result += bl + "\t}\n";
                }
                else                  // Accessor in einer Zeile
                {
                    if (isContainer)
                    {
                        if (!isGenericList)
                        {
                            result += bl + "\tset => this." + name + " = new ArrayList( (ICollection)value );\n";
                        }
                        else
                        {
                            result += bl + "\tset => this." + name + " = value.ToList();\n";
                        }
                    }
                    else
                    {
                        result += bl + "\tset => this." + name + " = value;\n";
                    }
                }

                result += bl + "}\n";
                TabProperty tp = TabProperties.Instance.CSharp;
                if (tp.UseSpaces)
                {
                    result = result.Replace("\t", tp.Indent);
                }
                textDoc.Selection.Insert(result, (int)vsInsertFlags.vsInsertFlagsInsertAtStart);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Add Accessor Add-in");
            }
        }