示例#1
0
文件: Program.cs 项目: stewmc/vixen
		private static void Main()
		{

			try
			{
				AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
				Application.ThreadException += Application_ThreadException;
			 
				bool result;
				var mutex = new Mutex(true, "Vixen3RunningInstance", out result);

				if (!result)
				{
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
					var messageBox = new MessageBoxForm("Another instance is already running; please close that one before trying to start another.",
									"Vixen 3 already active", false, false);
					messageBox.ShowDialog();
					return;
				}

				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new VixenApplication());

				// mutex shouldn't be released - important line
				GC.KeepAlive(mutex);
			}
			catch (Exception ex)
			{
				Logging.Fatal(ErrorMsg, ex);
				Environment.Exit(1);
			}
		}
示例#2
0
 public void Run()
 {
     using (StubLogging logging = new StubLogging())
     //using (ModuleLoader loader = new ModuleLoader(logging))
     {
         try
         {
             ConfiguratorConfiguration config = new ConfiguratorConfiguration(logging);
             Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU", false);
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             using (_mainForm = new MainForm(config))
                 Application.Run(_mainForm);
         }
         catch (Exception ex)
         {
             logging.WriteError(ex.ToString());
             using (MessageBoxForm dlg = new MessageBoxForm())
             {
                 dlg.ShowForm(null, ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error,
                              new[] {"OK"});
             }
         }
     }
 }
示例#3
0
		private void buttonOK_Click(object sender, EventArgs e)
		{
			if (dateStart.Value > dateStop.Value)
			{
				//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
				MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
				var messageBox = new MessageBoxForm("The end date of a show must fall after the start date.", "Date Error", false, true);
				messageBox.ShowDialog();
				return;
			}
			_scheduleItem.StartDate = dateStart.Value;
			_scheduleItem.EndDate = dateStop.Value;
			_scheduleItem.Sunday = checkSunday.Checked;
			_scheduleItem.Monday = checkMonday.Checked;
			_scheduleItem.Tuesday = checkTuesday.Checked;
			_scheduleItem.Wednesday = checkWednesday.Checked;
			_scheduleItem.Thursday = checkThursday.Checked;
			_scheduleItem.Friday = checkFriday.Checked;
			_scheduleItem.Saturday = checkSaturday.Checked;
			_scheduleItem.StartTime = dateStartTime.Value;
			_scheduleItem.EndTime = dateEndTime.Value;
			_scheduleItem.Enabled = checkEnabled.Checked;

			if (comboBoxShow.SelectedIndex >= 0)
			{
				Shows.Show show = ((comboBoxShow.SelectedItem as Common.Controls.ComboBoxItem).Value) as Shows.Show;
				_scheduleItem.ShowID = show.ID;
			}
			DialogResult = System.Windows.Forms.DialogResult.OK;
			Close();
		}
示例#4
0
 public DialogResult Show(IWin32Window parent, string message, string caption, MessageBoxButton button, MessageBoxIcon icon)
 {
     using(var msgbox = new MessageBoxForm(button, icon, message, caption))
     {
         return msgbox.ShowDialog(parent);
     }
 }
示例#5
0
		public override bool Setup()
		{
			//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
			MessageBoxForm.msgIcon = SystemIcons.Information; //this is used if you want to add a system icon to the message form.
			var messageBox = new MessageBoxForm("Nothing to Setup", "", false, false);
			messageBox.ShowDialog();
			return base.Setup();
		}
示例#6
0
 public static DialogResult Show(
     IWin32Window owner, string text, string caption, MessageBoxButtons buttons,
     Bitmap icon, MessageBoxDefaultButton defaultButton, MessageBoxIcon beepType)
 {
     NativeMethods.MessageBeep((int)beepType);
     MessageBoxForm form = new MessageBoxForm();
     return form.ShowMessageBoxDialog(new MessageBoxArgs(
         owner, text, caption, buttons, icon, defaultButton));
 }
		/// <summary>
		/// Scan for games
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ScanButton_Click(object sender, EventArgs e)
		{
			MessageBoxForm form = new MessageBoxForm();
			form.StartPosition = FormStartPosition.CenterParent;
			var result = form.ShowForm("Scan for games on your computer?", "Scan", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
			if (result == DialogResult.OK)
			{
				var success = System.Threading.ThreadPool.QueueUserWorkItem(ScanGames);
				if (!success) ScanProgressLabel.Text = "Scan failed!";
			}
		}
示例#8
0
 private void buttonOK_Click(object sender, EventArgs e)
 {
     if (_PortAddress == 0)
     {
         //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
         MessageBoxForm.msgIcon = SystemIcons.Hand; //this is used if you want to add a system icon to the message form.
         var messageBox = new MessageBoxForm("The port address is 0.", "595 Setup", false, false);
         messageBox.ShowDialog();
         messageBox.DialogResult = DialogResult.None;
     }
     else {
         _data.Port = _PortAddress;
     }
 }
示例#9
0
 private void buttonOK_Click(object sender, EventArgs e)
 {
     if (TemplateName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) {
         //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
         MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
         var messageBox = new MessageBoxForm("The template name must be a valid file name. Please ensure there are no invalid characters in the template name.",
             "Invalid Template Name", false, true);
         messageBox.ShowDialog();
         DialogResult = messageBox.DialogResult;
     }
     else {
         DialogResult = DialogResult.OK;
         Close();
     }
 }
示例#10
0
        private void buttonAddColorSet_Click(object sender, EventArgs e)
        {
            using (TextDialog textDialog = new TextDialog("New Color Set name?", "New Color Set")) {
                if (textDialog.ShowDialog() == DialogResult.OK) {
                    string newName = textDialog.Response;

                    if (_data.ContainsColorSet(newName)) {
                        //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                        MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
                        var messageBox = new MessageBoxForm("Color Set already exists.", "Error", false, false);
                        messageBox.ShowDialog();
                        return;
                    }

                    ColorSet newcs = new ColorSet();
                    _data.SetColorSet(newName, newcs);
                    UpdateGroupBoxWithColorSet(newName, newcs);
                    UpdateColorSetsList();
                }
            }
        }
示例#11
0
        private void buttonAddProfile_Click(object sender, EventArgs e)
        {
            SaveCurrentItem();

            TextDialog dialog = new TextDialog("Enter a name for the new profile","Profile Name","New Profile");

            while (dialog.ShowDialog() == DialogResult.OK)
            {
                if (dialog.Response == string.Empty)
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("Profile name can not be blank.",
                        "Error", false, false);
                    messageBox.ShowDialog();
                }

                if (comboBoxProfiles.Items.Cast<ProfileItem>().Any(items => items.Name == dialog.Response))
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("A profile with the name " + dialog.Response + @" already exists.", "", false, false);
                    messageBox.ShowDialog();
                }

                if (dialog.Response != string.Empty && comboBoxProfiles.Items.Cast<ProfileItem>().All(items => items.Name != dialog.Response))
                {
                    break;
                }

            }

            if (dialog.DialogResult == DialogResult.Cancel)
                return;

            ProfileItem item = new ProfileItem { Name = dialog.Response, DataFolder = _defaultFolder + " " + dialog.Response };
            comboBoxProfiles.Items.Add(item);
            comboBoxProfiles.SelectedIndex = comboBoxProfiles.Items.Count - 1;
            PopulateLoadProfileSection(false);
        }
示例#12
0
        public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, string[] buttonText, bool useCancelButton)
        {
            //int n = Application.OpenForms.Count - 1;
            //Form owner = null;
            //if (n > -1)
            //    owner = Application.OpenForms[n];

            //if (owner != null)
            //    owner.BringToFront();

            IntPtr zero = IntPtr.Zero;
            if (owner == null)
            {
                zero = Process.GetCurrentProcess().MainWindowHandle; 
                //zero = NativeMethod.GetActiveWindow();
                owner = Form.FromHandle(zero);
            }
            else
            {
                zero = owner.Handle;
            }

            DialogResult result;
            using (MessageBoxForm frm = new MessageBoxForm())
            {
                if (!useCancelButton)
                {
                    frm.ControlBox = false;
                    frm.CancelButton = new Button(); // Иначе по Esc закрывается форма.
                }
                result = frm.ShowForm(owner, text, caption, buttons, icon, buttonText, useCancelButton);
            }

            //if (zero != IntPtr.Zero)
            //{
            //    NativeMethod.SendMessage(zero, 7, 0, 0);
            //}

            return result;
        }
示例#13
0
		private void OkButton_Click(object sender, EventArgs e)
		{
			if (portComboBox.SelectedIndex == _OtherAddressIndex) {
				if (PortAddress != 0) {
					try {
						Convert.ToUInt16(portTextBox.Text, 0x10);
					}
					catch {
						//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
						MessageBoxForm.msgIcon = SystemIcons.Hand; //this is used if you want to add a system icon to the message form.
						var messageBox = new MessageBoxForm("The port number is not a valid hexadecimal number.", "Parallel Port Setup", false, false);
						messageBox.ShowDialog();
						base.DialogResult = DialogResult.None;
					}
				}
				else {
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					MessageBoxForm.msgIcon = SystemIcons.Hand; //this is used if you want to add a system icon to the message form.
					var messageBox = new MessageBoxForm("The port address is 0.", "Parallel Port Setup", false, false);
					messageBox.ShowDialog();
					DialogResult = DialogResult.None;
				}
			}
		}
        public TimedSequenceEditorEffectEditor(IEnumerable<EffectNode> effectNodes)
            : this(effectNodes.First())
        {
            if (effectNodes != null && effectNodes.Count() > 1) {
                _effectNodes = effectNodes;
                Text = "Edit Multiple Effects";

                // show a warning if multiple effect types are selected
                EffectNode displayedEffect = effectNodes.First();
                if (displayedEffect != null) {
                    foreach (EffectNode node in effectNodes) {
                        if (node.Effect.TypeId != displayedEffect.Effect.TypeId)
                        {
                            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                            MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
                            var messageBox = new MessageBoxForm("The selected effects contain multiple types. Once you finish editing, these values will " +
                                            "only be applied to the effects of type '" + displayedEffect.Effect.Descriptor.TypeName + "'.", "Warning", false, false);
                            messageBox.ShowDialog();
                            break;
                        }
                    }
                }
            }
        }
示例#15
0
		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			IWindowsFormsEditorService svc = (IWindowsFormsEditorService)
			                                 provider.GetService(typeof (IWindowsFormsEditorService));
			if (svc != null) {
				List<PreviewBaseShape> shapes = value as List<PreviewBaseShape>;
				if (shapes.Count < 1)
				{
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
					var messageBox = new MessageBoxForm("Elements must have at least one shape. Remove the selected element.", "Error", false, false);
					messageBox.ShowDialog();
					if (value != null) return value;
				}
				PreviewSetElements elementsDialog = new PreviewSetElements(shapes);
				svc.ShowDialog(elementsDialog);
				// update etc
                if (shapes[0].Parent != null)
                {
                    shapes[0].Parent.Layout();
                }
			}
			return value;
		}
示例#16
0
        private void buttonDoPatching_Click(object sender, EventArgs e)
        {
            if (_selectedPatchSources == null || _selectedPatchDestinations == null) {
                Logging.Error("null patch sources or destinations!");
                return;
            }

            int max = Math.Min(_selectedPatchSources.Count, _selectedPatchDestinations.Count);

            // reverse things if needed
            _UpdateEverything(_cachedElementNodes, _cachedControllersAndOutputs, _reverseElementOrder);

            for (int i = 0; i < max; i++) {
                VixenSystem.DataFlow.SetComponentSource(_selectedPatchDestinations[i].Item, _selectedPatchSources[i].Item);
            }

            OnPatchingUpdated();
            _UpdateEverything(_cachedElementNodes, _cachedControllersAndOutputs, false);

            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
            MessageBoxForm.msgIcon = SystemIcons.Information; //this is used if you want to add a system icon to the message form.
            var messageBox = new MessageBoxForm("Patched " + max + " element patch points to controllers.", "Patching Complete", false, false);
            messageBox.ShowDialog();
        }
示例#17
0
		private void toolStripButtonDeleteGradient_Click(object sender, EventArgs e)
		{
			if (listViewGradients.SelectedItems.Count == 0)
				return;

			//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
			MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
			var messageBox = new MessageBoxForm("If you delete this library gradient, ALL places it is used will be unlinked and will" +
								@" become independent gradients. Are you sure you want to continue?", "Delete library gradient?", true, true);
			messageBox.ShowDialog();

			if (messageBox.DialogResult == DialogResult.OK)
			{
				_colorGradientLibrary.RemoveColorGradient(listViewGradients.SelectedItems[0].Name);
			}
		}
示例#18
0
        public void Load()
        {
            bool settingsLoaded = false;
            var  settingsFi     = new FileInfo(XmlFile.FullName);

            // If configuration file exists then...
            if (settingsFi.Exists)
            {
                // Try to read file until success.
                while (true)
                {
                    SettingsData <T> data;
                    // Deserialize and load data.
                    lock (saveReadFileLock)
                    {
                        try
                        {
                            data = Serializer.DeserializeFromXmlFile <SettingsData <T> >(XmlFile.FullName);
                            if (data != null && data.IsValidVersion())
                            {
                                Items.Clear();
                                if (data != null)
                                {
                                    var m     = FilterList;
                                    var items = (m == null)
                                                                                ? data.Items
                                                                                : m(data.Items);
                                    if (items != null)
                                    {
                                        for (int i = 0; i < items.Count; i++)
                                        {
                                            Items.Add(items[i]);
                                        }
                                    }
                                }
                                settingsLoaded = true;
                            }
                            break;
                        }
                        catch (Exception)
                        {
                            var form       = new MessageBoxForm();
                            var backupFile = XmlFile.FullName + ".bak";
                            form.StartPosition = FormStartPosition.CenterParent;
                            var text = string.Format("{0} file has become corrupted.\r\n" +
                                                     "Program must reset {0} file in order to continue.\r\n\r\n" +
                                                     "   Click [Yes] to reset and continue.\r\n" +
                                                     "   Click [No] if you wish to attempt manual repair.\r\n\r\n" +
                                                     " File: {1}", _CollectionName, XmlFile.FullName);
                            var caption = string.Format("Corrupt {0} of {1}", _CollectionName, Application.ProductName);
                            var result  = form.ShowForm(text, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                            if (result == DialogResult.Yes)
                            {
                                if (File.Exists(backupFile))
                                {
                                    File.Copy(backupFile, XmlFile.FullName, true);
                                    settingsFi.Refresh();
                                }
                                else
                                {
                                    File.Delete(XmlFile.FullName);
                                    break;
                                }
                            }
                            else
                            {
                                // Avoid the inevitable crash by killing application first.
                                Process.GetCurrentProcess().Kill();
                                return;
                            }
                        }
                    }
                }
            }
            // If settings failed to load then...
            if (!settingsLoaded)
            {
                // Get internal resources.
                var resource = EngineHelper.GetResource(_FileName + ".gz");
                // If internal preset was found.
                if (resource != null)
                {
                    var sr = new StreamReader(resource);
                    var compressedBytes = default(byte[]);
                    using (var memstream = new MemoryStream())
                    {
                        sr.BaseStream.CopyTo(memstream);
                        compressedBytes = memstream.ToArray();
                    }
                    var bytes = EngineHelper.Decompress(compressedBytes);
                    var xml   = Encoding.UTF8.GetString(bytes);
                    var data  = Serializer.DeserializeFromXmlString <SettingsData <T> >(xml);
                    Items.Clear();
                    for (int i = 0; i < data.Items.Count; i++)
                    {
                        Items.Add(data.Items[i]);
                    }
                }
            }
            if (!settingsLoaded)
            {
                Save();
            }
        }
示例#19
0
		private void AddCurveToLibrary(Curve c, bool edit=true)
		{
			Common.Controls.TextDialog dialog = new Common.Controls.TextDialog("Curve name?");

			while (dialog.ShowDialog() == DialogResult.OK)
			{
				if (dialog.Response == string.Empty)
				{
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					var messageBox = new MessageBoxForm("Please enter a name.", "Curve Name", false, false);
					messageBox.ShowDialog();
					continue;
				}

				if (_curveLibrary.Contains(dialog.Response))
				{
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					MessageBoxForm.msgIcon = SystemIcons.Question; //this is used if you want to add a system icon to the message form.
					var messageBox = new MessageBoxForm("There is already a curve with that name. Do you want to overwrite it?", "Overwrite curve?", true, true);
					messageBox.ShowDialog();
					if (messageBox.DialogResult == DialogResult.OK)
					{
						_curveLibrary.AddCurve(dialog.Response, c);
						if (edit)
						{
							_curveLibrary.EditLibraryCurve(dialog.Response);	
						}
						break;
					}

					if (messageBox.DialogResult == DialogResult.Cancel)
					{
						break;
					}
				}
				else
				{
					_curveLibrary.AddCurve(dialog.Response, c);
					if (edit)
					{
						_curveLibrary.EditLibraryCurve(dialog.Response);	
					}
					
					break;
				}
			}
		}
示例#20
0
        private void convertButton_Click(object sender, EventArgs e)
        {
            int mcIndex = startOffsetCombo.SelectedIndex;
            Tuple <TimeSpan, TimeSpan> timing      = Tuple.Create(new TimeSpan(), new TimeSpan());
            List <LipSyncConvertData>  convertData = new List <LipSyncConvertData>();

            if (LipSyncTextConvert.StandardDictExists() == false)
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Error;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("Unable to find Standard Phoneme Dictionary", "Error", false, false);
                messageBox.ShowDialog();
                return;
            }

            LipSyncTextConvert.InitDictionary();

            if (NewTranslation != null)
            {
                var           selectedMarkCollection = (markCollectionCombo.SelectedItem as ComboBoxItem)?.Value as MarkCollection;
                List <string> subStrings             = CreateSubstringList();

                var  selMC          = selectedMarkCollection?.Marks.Select(x => x.StartTime).ToList();
                bool doPhonemeAlign =
                    (alignCombo.SelectedIndex != -1) && (alignCombo.SelectedItem.Equals("Phoneme"));

                if (mcIndex == -1)
                {
                    selMC   = null;
                    mcIndex = 0;
                }

                foreach (string strElem in subStrings)
                {
                    if (string.IsNullOrWhiteSpace(strElem))
                    {
                        continue;
                    }

                    int phonemeIndex = 0;
                    List <PhonemeType> phonemeList = LipSyncTextConvert.TryConvert(strElem.Trim());
                    if (phonemeList.Count == 0)
                    {
                        EventHandler <TranslateFailureEventArgs> failHandler = TranslateFailure;
                        TranslateFailureEventArgs failArgs = new TranslateFailureEventArgs();
                        failArgs.FailedWord = strElem;
                        failHandler(this, failArgs);

                        //At this point, we should have it corrected, if not, then ignore
                        phonemeList = LipSyncTextConvert.TryConvert(strElem);
                    }

                    if (phonemeList.Count == 0)
                    {
                        //User has bailed on one of the conversions
                        return;
                    }

                    if (doPhonemeAlign == false)
                    {
                        timing = CalcPhonemeTimespans(selMC, mcIndex++, phonemeList.Count);
                    }

                    foreach (PhonemeType phoneme in phonemeList)
                    {
                        if (doPhonemeAlign == true)
                        {
                            timing       = CalcPhonemeTimespans(selMC, mcIndex++, 1);
                            phonemeIndex = 0;
                        }

                        long startTicks = timing.Item1.Ticks + (timing.Item2.Ticks * phonemeIndex++);
                        convertData.Add(new LipSyncConvertData(startTicks, timing.Item2.Ticks, phoneme, strElem));
                    }
                    if (checkBoxClearText.Checked)
                    {
                        textBox.Text = "";
                    }
                }

                EventHandler <NewTranslationEventArgs> handler = NewTranslation;
                NewTranslationEventArgs args = new NewTranslationEventArgs();
                args.PhonemeData = convertData;
                if (markCollectionRadio.Checked)
                {
                    args.Placement = TranslatePlacement.Mark;
                }
                else if (cursorRadio.Checked)
                {
                    args.Placement = TranslatePlacement.Cursor;
                }
                else
                {
                    args.Placement = TranslatePlacement.Clipboard;
                }

                if (startOffsetCombo.SelectedItem != null)
                {
                    args.FirstMark = (TimeSpan)startOffsetCombo.SelectedItem;
                }

                handler(this, args);

                if (markCollectionRadio.Checked)
                {
                    int markIncrement = 0;
                    switch (alignCombo.Text)
                    {
                    case "Phoneme":
                        markIncrement = convertData.Count;
                        break;

                    case "Word":
                        markIncrement = subStrings.Count;
                        break;

                    case "Phrase":
                        markIncrement = 1;
                        break;
                    }
                    if (startOffsetCombo.SelectedIndex + markIncrement < startOffsetCombo.Items.Count)
                    {
                        startOffsetCombo.SelectedIndex = startOffsetCombo.SelectedIndex + markIncrement;
                    }
                }
            }
        }
示例#21
0
        private XElement _Version_0_to_1(XElement content)
        {
            var messageBox = new MessageBoxForm(string.Format("Migrating sequence from version 0 to version 1. Changes include moving Nutcracker and Audio files to the common media folder.{0}{0}" +
                                                              "These changes are not backward compatible", Environment.NewLine), "Sequence Upgrade", MessageBoxButtons.OK, SystemIcons.Information);

            messageBox.StartPosition = FormStartPosition.CenterScreen;
            messageBox.ShowDialog();
            //  3/14/2015
            //Migrate full path name of the background image to just the filename. Code will now look
            //relative to the profile for the module path to the filenames
            //This is the first introduction of versioning for sequences so not versioned files are considered version 0
            //new files and migrated ones will have a version atribute in the root element
            var        namespaces = new XmlNamespaceManager(new NameTable());
            XNamespace ns         = "http://schemas.datacontract.org/2004/07/VixenModules.Sequence.Timed";

            namespaces.AddNamespace("", ns.NamespaceName);
            XNamespace d2p1 = "http://schemas.datacontract.org/2004/07/VixenModules.Effect.Nutcracker";

            namespaces.AddNamespace("d2p1", d2p1.NamespaceName);
            XNamespace d1p1 = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";

            namespaces.AddNamespace("d1p1", d1p1.NamespaceName);

            //Fix the paths on the Nutcracker Picture filenames so they are now relative to the profile instead of full paths
            IEnumerable <XElement> fileNameElements =
                content.XPathSelectElements(
                    "_dataModels/d1p1:anyType/d2p1:NutcrackerData/d2p1:Picture_FileName",
                    namespaces);

            foreach (var fileNameElement in fileNameElements)
            {
                string fileName = Path.GetFileName(fileNameElement.Value);
                fileNameElement.SetValue(fileName);
            }

            //Fix the paths on the Nutcracker Picture filenames  so they are now relative to the profile instead of full paths
            fileNameElements =
                content.XPathSelectElements(
                    "_dataModels/d1p1:anyType/d2p1:NutcrackerData/d2p1:PictureTile_FileName",
                    namespaces);

            foreach (var fileNameElement in fileNameElements)
            {
                if (!IsNutcrackerResource(fileNameElement.Value))
                {
                    string fileName = Path.GetFileName(fileNameElement.Value);
                    fileNameElement.SetValue(fileName);
                }
            }

            //Fix the paths on the Nutcracker Glediator filenames so they are now relative to the profile instead of full paths
            fileNameElements =
                content.XPathSelectElements(
                    "_dataModels/d1p1:anyType/d2p1:NutcrackerData/d2p1:Glediator_FileName",
                    namespaces);

            foreach (var fileNameElement in fileNameElements)
            {
                string fileName = Path.GetFileName(fileNameElement.Value);
                fileNameElement.SetValue(fileName);
            }


            //Fix the audio paths on Media so they are now relative to the profile instead of full paths
            fileNameElements =
                content.XPathSelectElements(
                    "_mediaSurrogates/MediaSurrogate/FilePath",
                    namespaces);

            foreach (var fileNameElement in fileNameElements)
            {
                string filePath = fileNameElement.Value;
                string fileName = Path.GetFileName(filePath);
                fileNameElement.SetValue(fileName);
                fileNameElement.Name = "FileName";
                string newPath = Path.Combine(MediaService.MediaDirectory, fileName);
                if (File.Exists(filePath) && !File.Exists(newPath))
                {
                    File.Copy(filePath, newPath);
                }
            }

            //Fix the provider source name
            IEnumerable <XElement> timingElements =
                content.XPathSelectElements(
                    "_selectedTimingProviderSurrogate",
                    namespaces);

            foreach (var timingElement in timingElements)
            {
                XElement type = timingElement.Element("ProviderType");
                if (type != null && type.Value.Equals("Media"))
                {
                    XElement source = timingElement.Element("SourceName");
                    if (source != null)
                    {
                        string fileName = Path.GetFileName(source.Value);
                        source.SetValue(fileName);
                    }
                }
            }

            return(content);
        }
示例#22
0
        // -------------------------------------------------------------
        //
        // 	Startup() - called when the plugin is loaded
        //
        //
        // 	todo:
        //
        // 		1) probably add error checking on all 'new' operations
        // 		and system calls
        //
        // 		2) better error reporting and logging
        //
        //      3) Sequence # should be per universe
        //
        // -------------------------------------------------------------
        public override void Start()
        {
            bool cleanStart = true;

            base.Start();

            if(!PluginInstances.Contains(this))
                PluginInstances.Add(this);

            // working copy of networkinterface object
            NetworkInterface networkInterface;

            // a single socket to use for unicast (if needed)
            Socket unicastSocket = null;

            // working ipaddress object
            IPAddress ipAddress = null;

            // a sortedlist containing the multicast sockets we've already done
            var nicSockets = new SortedList<string, Socket>();

            // load all of our xml into working objects
            this.LoadSetupNodeInfo();

            // initialize plugin wide stats
            this._eventCnt = 0;
            this._totalTicks = 0;

            if (_data.Unicast == null && _data.Multicast == null)
                if (_data.Universes[0] != null && (_data.Universes[0].Multicast != null || _data.Universes[0].Unicast != null))
                {
                    _data.Unicast = _data.Universes[0].Unicast;
                    _data.Multicast = _data.Universes[0].Multicast;
                    if(!_updateWarn){
                        //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                        MessageBoxForm.msgIcon = SystemIcons.Information; //this is used if you want to add a system icon to the message form.
                        var messageBox = new MessageBoxForm("The E1.31 plugin is importing data from an older version of the plugin. Please verify the new Streaming ACN (E1.31) configuration.", "Vixen 3 Streaming ACN (E1.31) plugin", false, false);
                        messageBox.ShowDialog();
                        _updateWarn = true;
                    }
                }

            // find all of the network interfaces & build a sorted list indexed by Id
            this._nicTable = new SortedList<string, NetworkInterface>();

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var nic in nics)
            {
                if (nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                {
                    this._nicTable.Add(nic.Id, nic);
                }
            }

            if (_data.Unicast != null)
            {
                if (!unicasts.ContainsKey(_data.Unicast))
                {
                    unicasts.Add(_data.Unicast, 0);
                }
            }

            // initialize messageTexts stringbuilder to hold all warnings/errors
            this._messageTexts = new StringBuilder();

            // now we need to scan the universeTable
            foreach (var uE in _data.Universes)
            {
                // if it's still active we'll look into making a socket for it
                if (cleanStart && uE.Active)
                {
                    // if it's unicast it's fairly easy to do
                    if (_data.Unicast != null)
                    {
                        // is this the first unicast universe?
                        if (unicastSocket == null)
                        {
                            // yes - make a new socket to use for ALL unicasts
                            unicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        }

                        // use the common unicastsocket
                        uE.Socket = unicastSocket;

                        IPAddress[] ips = null;

                        try
                        {
                            ips = Dns.GetHostAddresses(_data.Unicast);
                        }
                        catch
                        {
                            //Probably couldn't find the host name
                            NLog.LogManager.GetCurrentClassLogger().Warn("Couldn't connect to host "+_data.Unicast+".");
                            cleanStart = false;
                        }

                        if (ips != null)
                        {
                            IPAddress ip = null;
                            foreach (IPAddress i in ips)
                                if (i.AddressFamily == AddressFamily.InterNetwork)
                                    ip = i;

                            // try to parse our ip address
                            if (ip == null)
                            {
                                // oops - bad ip, fuss and deactivate
                                NLog.LogManager.GetCurrentClassLogger().Warn("Couldn't connect to host " + _data.Unicast + ".");
                                cleanStart = false;
                                uE.Socket = null;
                            }
                            else
                            {
                                // if good, make our destination endpoint
                                uE.DestIpEndPoint = new IPEndPoint(ip, 5568);
                            }
                        }
                    }

                    // if it's multicast roll up your sleeves we've got work to do
                    else if (_data.Multicast != null)
                    {
                        // create an ipaddress object based on multicast universe ip rules
                        var multicastIpAddress =
                            new IPAddress(new byte[] { 239, 255, (byte)(uE.Universe >> 8), (byte)(uE.Universe & 0xff) });

                        // create an ipendpoint object based on multicast universe ip/port rules
                        var multicastIpEndPoint = new IPEndPoint(multicastIpAddress, 5568);

                        // first check for multicast id in nictable
                        if (!this._nicTable.ContainsKey(_data.Multicast))
                        {
                            // no - deactivate and scream & yell!!
                            NLog.LogManager.GetCurrentClassLogger().Warn("Couldn't connect to use nic " + _data.Multicast + " for multicasting.");
                            if (!_missingInterfaceWarning)
                            {
                                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                                MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
                                var messageBox = new MessageBoxForm("The Streaming ACN (E1.31) plugin could not find one or more of the multicast interfaces specified. Please verify your network and plugin configuration.", "Vixen 3 Streaming ACN (E1.31) plugin", false, false);
                                messageBox.ShowDialog();
                                _missingInterfaceWarning = true;
                            }
                            cleanStart = false;
                        }
                        else
                        {
                            // yes - let's get a working networkinterface object
                            networkInterface = this._nicTable[_data.Multicast];

                            // have we done this multicast id before?
                            if (nicSockets.ContainsKey(_data.Multicast))
                            {
                                // yes - easy to do - use existing socket
                                uE.Socket = nicSockets[_data.Multicast];

                                // setup destipendpoint based on multicast universe ip rules
                                uE.DestIpEndPoint = multicastIpEndPoint;
                            }
                            // is the interface up?
                            else if (networkInterface.OperationalStatus != OperationalStatus.Up)
                            {
                                // no - deactivate and scream & yell!!
                                NLog.LogManager.GetCurrentClassLogger().Warn("Nic " + _data.Multicast + " is available for multicasting bur currently down.");
                                cleanStart = false;
                            }
                            else
                            {
                                // new interface in 'up' status - let's make a new udp socket
                                uE.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                                // get a working copy of ipproperties
                                IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();

                                // get a working copy of all unicasts
                                UnicastIPAddressInformationCollection unicasts = ipProperties.UnicastAddresses;

                                ipAddress = null;

                                foreach (var unicast in unicasts)
                                {
                                    if (unicast.Address.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        ipAddress = unicast.Address;
                                    }
                                }

                                if (ipAddress == null)
                                {
                                    this._messageTexts.AppendLine(string.Format("No IP On Multicast Interface: {0} - {1}" , networkInterface.Name , uE.InfoToText));
                                }
                                else
                                {
                                    // set the multicastinterface option
                                    uE.Socket.SetSocketOption(
                                        SocketOptionLevel.IP,
                                        SocketOptionName.MulticastInterface,
                                        ipAddress.GetAddressBytes());

                                    // set the multicasttimetolive option
                                    uE.Socket.SetSocketOption(
                                        SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 64);

                                    // setup destipendpoint based on multicast universe ip rules
                                    uE.DestIpEndPoint = multicastIpEndPoint;

                                    // add this socket to the socket table for reuse
                                    nicSockets.Add(_data.Multicast, uE.Socket);
                                }
                            }
                        }
                    }
                    else
                    {
                        NLog.LogManager.GetCurrentClassLogger().Warn("E1.31 plugin failed to start due to unassigned destinations. This can happen with newly created plugin instances that have yet to be configured.");
                        cleanStart = false;
                    }

                    // if still active we need to create an empty packet
                    if (cleanStart)
                    {
                        var zeroBfr = new byte[uE.Size];
                        var e131Packet = new E131Packet(_data.ModuleInstanceId, "Vixen 3", 0, (ushort)uE.Universe, zeroBfr, 0, uE.Size, _data.Priority, _data.Blind);
                        uE.PhyBuffer = e131Packet.PhyBuffer;
                    }
                }
                if(cleanStart)
                    running = true;
            }

            // any warnings/errors recorded?
            if (this._messageTexts.Length > 0)
            {
                // should we display them
                if (_data.Warnings)
                {
                    // show our warnings/errors
                    J1MsgBox.ShowMsg(
                        "The following warnings and errors were detected during startup:",
                        this._messageTexts.ToString(),
                        "Startup Warnings/Errors",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);

                    // discard warning/errors after reporting them
                    this._messageTexts = new StringBuilder();
                }
            }

            #if VIXEN21
            return new List<Form> {};
            #endif
        }
示例#23
0
        public void Load()
        {
            bool settingsLoaded = false;
            // If configuration file not exists then...
            var settingsFi = new System.IO.FileInfo(InitialFile.FullName);

            if (settingsFi.Exists)
            {
                while (true)
                {
                    SettingsFile data;
                    // Deserialize and load data.
                    lock (saveReadFileLock)
                    {
                        try
                        {
                            data = Serializer.DeserializeFromXmlFile <SettingsFile>(InitialFile.FullName);
                            if (data == null)
                            {
                                return;
                            }
                            Programs.Clear();
                            if (data.Programs != null)
                            {
                                // Make sure default settings have unique by file name.
                                var distinctPrograms = data.Programs
                                                       .GroupBy(p => p.FileName.ToLower())
                                                       .Select(g => g.First())
                                                       .ToList();
                                for (int i = 0; i < distinctPrograms.Count; i++)
                                {
                                    Programs.Add(distinctPrograms[i]);
                                }
                            }
                            Games.Clear();
                            if (data.Games != null)
                            {
                                // Make sure default settings have unique by file name.
                                var distinctGames = data.Games
                                                    .GroupBy(p => p.FileName.ToLower())
                                                    .Select(g => g.First())
                                                    .ToList();
                                for (int i = 0; i < distinctGames.Count; i++)
                                {
                                    Games.Add(distinctGames[i]);
                                }
                            }
                            Pads.Clear();
                            if (data.Pads != null)
                            {
                                for (int i = 0; i < data.Pads.Count; i++)
                                {
                                    Pads.Add(data.Pads[i]);
                                }
                            }
                            settingsLoaded = true;
                            break;
                        }
                        catch (Exception)
                        {
                            var form       = new MessageBoxForm();
                            var backupFile = InitialFile.FullName + ".bak";
                            form.StartPosition = FormStartPosition.CenterParent;
                            var result = form.ShowForm(
                                "User settings file has become corrupted.\r\n" +
                                "Program must reset your user settings in order to continue.\r\n\r\n" +
                                "   Click [Yes] to reset your user settings and continue.\r\n" +
                                "   Click [No] if you wish to attempt manual repair.\r\n\r\n" +
                                "Settings File: " + InitialFile.FullName,
                                "Corrupt user settings of " + Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                            if (result == DialogResult.Yes)
                            {
                                if (System.IO.File.Exists(backupFile))
                                {
                                    System.IO.File.Copy(backupFile, InitialFile.FullName, true);
                                    settingsFi.Refresh();
                                }
                                else
                                {
                                    System.IO.File.Delete(InitialFile.FullName);
                                    break;
                                }
                            }
                            else
                            {
                                // Avoid the inevitable crash by killing application first.
                                Process.GetCurrentProcess().Kill();
                                return;
                            }
                        }
                    }
                }
            }
            // If settings failed to load then...
            if (!settingsLoaded)
            {
                var resource = EngineHelper.GetResource("x360ce_Games.xml.gz");
                // If internal preset was found.
                if (resource != null)
                {
                    var sr = new StreamReader(resource);
                    var compressedBytes = default(byte[]);
                    using (var memstream = new MemoryStream())
                    {
                        sr.BaseStream.CopyTo(memstream);
                        compressedBytes = memstream.ToArray();
                    }
                    var bytes    = EngineHelper.Decompress(compressedBytes);
                    var xml      = System.Text.Encoding.UTF8.GetString(bytes);
                    var programs = Serializer.DeserializeFromXmlString <List <x360ce.Engine.Data.Program> >(xml);
                    Programs.Clear();
                    for (int i = 0; i < programs.Count; i++)
                    {
                        Programs.Add(programs[i]);
                    }
                }
            }
            // Check if current app doesn't exist in the list then...
            var currentFile = new System.IO.FileInfo(Application.ExecutablePath);
            var currentGame = Games.FirstOrDefault(x => x.FileName == currentFile.Name);

            if (currentGame == null)
            {
                // Add x360ce.exe
                var item    = x360ce.Engine.Data.Game.FromDisk(currentFile.Name);
                var program = Programs.FirstOrDefault(x => x.FileName == currentFile.Name);
                item.LoadDefault(program);
                SettingsFile.Current.Games.Add(item);
            }
            else
            {
                currentGame.FullPath = currentFile.FullName;
            }
        }
        /// <summary>
        /// 重新读取卡信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReload_Click(object sender, EventArgs e)
        {
            try
            {
                this.lblMessage.Text = "提示: 只有在空卡状态下,才可进行换卡操作!";
                this.lblNum.Text     = string.Empty;
                string password = CurrentUser.Current.PassWordKey;
                bool   flag     = false;

                string[] mary1 = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(password, Convert.ToInt32(1)));
                if (mary1[4] == "11" || mary1[4] == "12")
                {
                    flag     = true;
                    password = SystemConstant.StringEmpty;
                    mary1    = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(password, Convert.ToInt32(1)));
                }
                if (mary1[4] != "0")
                {
                    this.lblNum.Text = string.Empty;
                    throw new Exception(RFIDClass.ConvertMeassByStatus(Convert.ToInt32(mary1[4])));
                }
                //string[] mary6 = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(CurrentUser.Current.PassWordKey, Convert.ToInt32(6)));
                //判断当前读的卡是否能初始化的条件; 1: 卡状态为空卡255 ;2:卡状态为已充值,但最后操作时间为空
                string cardStatus = string.IsNullOrEmpty(mary1[2]) ? "" : mary1[2].ToString();
                //判断如果长度是16
                if (cardStatus.Length >= 16)
                {
                    cardStatus = HelperClass.getCardStatus(cardStatus.Substring(13, 1));
                }
                else
                {
                    cardStatus = Bouwa.ITSP2V31.Model.CardTypeInfo.CardTypeInfoDefaultCardStatus.空白卡.ToString("D");
                }

                if (cardStatus.Equals(CardTypeInfo.CardTypeInfoDefaultCardStatus.空白卡.ToString("D")) ||
                    (cardStatus.Equals(CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString("D")) && string.IsNullOrEmpty(HelperClass.DecryptByString(mary1[3] == null ? "" : mary1[3].ToString()))) ||
                    flag
                    )
                {
                    //把RFID卡内编号赋值给卡内编号控件
                    _objCardId           = mary1[0];
                    this.lblMessage.Text = "提示: 此卡为空卡,可进行换卡操作!";
                }
                else
                {
                    this.lblNum.Text     = string.Empty;
                    this.lblMessage.Text = "提示: 此卡非空卡,请更换卡!";
                    ////this.Close();
                    //Bouwa.ITSP2V31.Win.CardType.CardTypeInitFail frmCardType = new Bouwa.ITSP2V31.Win.CardType.CardTypeInitFail();
                    ////把RFID卡内编号加入到Paramter参数中
                    //frmCardType.Parameter.Add("cardNum", mary1[0]);
                    //frmCardType.Parameter.Add("ActionType", ActionType.Init.ToString("D"));
                    //frmCardType.Parameter.Add("Id", _objId.ToString());
                    //frmCardType.StartPosition = FormStartPosition.CenterScreen;
                    //frmCardType.ShowDialog(this);
                }
            }
            catch (Exception ep)
            {
                this.lblNum.Text = string.Empty;
                MessageBoxForm.Show(ep.Message, MessageBoxButtons.OK);
                return;
            }
            SetFormFromInfo(_objId);
        }
示例#25
0
        private List <PatchStatusItem <IDataFlowComponentReference> > GetOrderedElementOutputs(IEnumerable <ElementNode> nodes)
        {
            List <PatchStatusItem <IDataFlowComponentReference> > outputList = new List <PatchStatusItem <IDataFlowComponentReference> >();

            //Compile the list of leaf nodes
            List <ElementNode> leafNodes = new List <ElementNode>();

            foreach (var node in nodes)
            {
                leafNodes.AddRange(node.GetLeafEnumerator());
            }

            leafNodes = leafNodes.Distinct().ToList();
            var orderedLeafNodes = leafNodes;

            //check to see if we have any order properties
            if (leafNodes.Any(x => x.Properties.Contains(OrderDescriptor.ModuleId)))
            {
                //We have some, but do all of them have an order property??
                if (leafNodes.All(x => x.Properties.Contains(OrderDescriptor.ModuleId)))
                {
                    //They all have them but are there any dupes???
                    if (leafNodes.GroupBy(x => ((OrderModule)x.Properties.Get(OrderDescriptor.ModuleId)).Order)
                        .Any(g => g.Count() > 1))
                    {
                        MessageBoxForm mbf = new MessageBoxForm(@"Some elements have a duplicate preferred patching order set. Would you like to fix this before proceeding?" +
                                                                "\n\nYes) Open the order wizard.\nNo) Proceed using the element tree order.\nCancel) Abort patching.",
                                                                "Patching Order Conflict", MessageBoxButtons.YesNoCancel, SystemIcons.Warning);
                        var result = mbf.ShowDialog(this);
                        if (result == DialogResult.Cancel)
                        {
                            return(null);
                        }

                        if (result == DialogResult.OK)
                        {
                            if (!ConfigureOrder())
                            {
                                return(null);
                            }

                            orderedLeafNodes = OrderNodes(leafNodes);
                        }
                    }
                    else
                    {
                        orderedLeafNodes = OrderNodes(leafNodes);
                    }
                }
                else
                {
                    MessageBoxForm mbf = new MessageBoxForm(@"Not all elements have a preferred patching order set. Would you like to fix this before proceding?" +
                                                            "\n\nYes) Open the order wizard.\nNo) Proceed using the element tree order.\nCancel) Abort patching.",
                                                            "Patching Order Conflict", MessageBoxButtons.YesNoCancel, SystemIcons.Warning);
                    var result = mbf.ShowDialog(this);
                    if (result == DialogResult.Cancel)
                    {
                        return(null);
                    }

                    if (result == DialogResult.OK)
                    {
                        if (ConfigureOrder())
                        {
                            orderedLeafNodes = OrderNodes(leafNodes);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }
            }

            //Reverse if we need to.
            if (_reverseElementOrder)
            {
                orderedLeafNodes.Reverse();
            }

            foreach (var orderedLeafNode in orderedLeafNodes)
            {
                if (orderedLeafNode.Element != null)
                {
                    IDataFlowComponent dfc = VixenSystem.DataFlow.GetComponent(orderedLeafNode.Element.Id);
                    var childOutputs       = _findPatchedAndUnpatchedOutputsFromComponent(dfc);
                    outputList.AddRange(childOutputs);
                }
            }

            return(outputList);
        }
        /// <summary>
        /// 为控件赋值
        /// </summary>
        /// <param name="theId"></param>
        private void SetFormFromInfo(Guid theId)
        {
            if (theId != Bouwa.Helper.SystemConstant.GuidEmpty)
            {
                _objCardTypeInfo = _objCardTypeBLL.GetById(theId, null, ref _objSystemMessageInfo);
                if (!_objSystemMessageInfo.Success)
                {
                    MessageBoxForm.Show(_objSystemMessageInfo, MessageBoxButtons.OK);
                }
                if (_objCardTypeInfo != null)
                {
                    this.lblNum.Text      = _objCardId;
                    this.tbxLotNum.Text   = _objCardTypeInfo.Batch;
                    this.tbxCardType.Text = _objCardTypeInfo.Name;
                    this.ddlStatus.Text   = CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString();//_objCardTypeInfo.DefaultCardStatus;

                    this.lblSaasId.Text     = _objCardTypeInfo.SaasId.ToString();
                    this.lblCardTypeId.Text = _objCardTypeInfo.Id.ToString("N");
                    this.lblCostType.Text   = _objCardTypeInfo.CostType.ToString("D");
                    this.lblEffectDate.Text = _objCardTypeInfo.EffectDate.ToString();
                    this.lblOutDate.Text    = _objCardTypeInfo.OutDate.ToString();

                    this.lblPurpose.Text    = _objCardTypeInfo.Purpose.ToString("D");
                    this.lblSubmitType.Text = _objCardTypeInfo.SubmitType.ToString("D");

                    this.lblExtSaasId.Text = Convert.ToString(_objCardTypeInfo.extSaasId);

                    this.lblExtCardTypeId.Text = Convert.ToString(_objCardTypeInfo.extCardTypeId);
                    //判断上限金额字段是否可更改
                    if (_objCardTypeInfo.DefaultChange.Equals(CardTypeInfo.CardTypeInfoDefaultChange.可变))
                    {
                        this.tbxOverPlus.ReadOnly = false;
                    }
                    else
                    {
                        this.tbxOverPlus.ReadOnly = true;
                    }

                    if ((int)_objCardTypeInfo.CostType == (int)CardTypeInfo.CardTypeInfoCostType.限时卡)
                    {
                        this.lblOverPlus.Text     = "剩余时间:";
                        this.lblOverPlusUnit.Text = this.lblMaxUnit.Text = "分钟";
                        this.lblMax.Text          = "上限时间:";
                        this.tbxOverPlus.Text     = _objCardInfo.charges_date.ToString(); //_objCardTypeInfo.DefaultChargesDate.ToString();
                        this.tbxMax.Text          = _objCardTypeInfo.MaxChargesDate.ToString();
                    }
                    else if ((int)_objCardTypeInfo.CostType == (int)CardTypeInfo.CardTypeInfoCostType.限次卡)
                    {
                        this.lblOverPlus.Text     = "剩余次数:";
                        this.lblOverPlusUnit.Text = this.lblMaxUnit.Text = "次";
                        this.lblMax.Text          = "上限次数:";
                        this.tbxOverPlus.Text     = _objCardInfo.times.ToString(); // _objCardTypeInfo.DefaultTimes.ToString();
                        this.tbxMax.Text          = _objCardTypeInfo.MaxTimes.ToString();
                    }
                    else if ((int)_objCardTypeInfo.CostType == (int)CardTypeInfo.CardTypeInfoCostType.限期卡)
                    {
                        this.lblOverPlus.Text     = "到期日期:";
                        this.lblOverPlusUnit.Text = "";
                        this.tbxOverPlus.Text     = _objCardInfo.end_date.ToString("yyyy-MM-dd"); ////_objCardTypeInfo.OutDate.ToString("yyyy-MM-dd");
                        this.lblMax.Visible       = this.tbxMax.Visible = this.lblMaxUnit.Visible = false;
                    }
                    else
                    {
                        this.tbxOverPlus.Text = _objCardInfo.money.ToString("0.00"); //_objCardTypeInfo.DefaultMoney.ToString();
                        this.tbxMax.Text      = _objCardTypeInfo.MaxMoney.ToString();
                    }
                }
            }
        }
        /// <summary>
        /// 初始化写卡数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbnWriteCard_Click(object sender, EventArgs e)
        {
            string d        = Guid.NewGuid().ToString("N");
            string password = CurrentUser.Current.PassWordKey;

            try
            {
                bool     flag  = false;
                string[] mary1 = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(password, Convert.ToInt32(1)));
                if (mary1[4] == "11" || mary1[4] == "12")
                {
                    flag     = true;
                    password = SystemConstant.StringEmpty;
                    mary1    = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(password, Convert.ToInt32(1)));
                }
                if (mary1[4] != "0")
                {
                    throw new Exception(RFIDClass.ConvertMeassByStatus(Convert.ToInt32(mary1[4])));
                }

                string cardStatus = string.IsNullOrEmpty(mary1[2])?"":mary1[2];
                //判断如果长度是16
                if (cardStatus.Length >= 16)
                {
                    cardStatus = HelperClass.getCardStatus(cardStatus.Substring(13, 1));
                }
                else
                {
                    cardStatus = Bouwa.ITSP2V31.Model.CardTypeInfo.CardTypeInfoDefaultCardStatus.空白卡.ToString("D");
                }
                //如果是从重新初始化的按钮进入,则跳过下面判断
                if (!(Bouwa.ITSP2V31.Model.CardTypeInfo.CardTypeInfoDefaultCardStatus.空白卡.ToString("D").Equals(cardStatus) ||
                      (cardStatus.Equals(CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString("D")) && string.IsNullOrEmpty(HelperClass.DecryptByString(mary1[3] == null ? "" : mary1[3].ToString()))) ||
                      flag))
                {
                    this.lblNum.Text = string.Empty;
                    MessageBoxForm.Show("此卡非空卡,请更换卡!", MessageBoxButtons.OK);
                    return;
                }
                if (!mary1[0].Equals(this.lblNum.Text))
                {
                    //MessageBoxForm.Show(_objSystemMessage.GetInfoByCode("ReadNoSameCard"), MessageBoxButtons.OK);
                    MessageBoxForm.Show("读取停车卡和待写入卡不是同一张卡,不能被写入!", MessageBoxButtons.OK);
                    return;
                }
                if (string.IsNullOrEmpty(this.lblNum.Text))
                {
                    this.lblNum.Text = string.Empty;
                    MessageBoxForm.Show("未读取到卡内编号,请重试!", MessageBoxButtons.OK);
                    return;
                }
                if (string.IsNullOrEmpty(this.tbxCardNum.Text))
                {
                    MessageBoxForm.Show("卡面编号不能为空,请重新输入!", MessageBoxButtons.OK);
                    return;
                }


                //判断卡面编号输入是否合法
                Regex rx = new Regex("^[\u4E00-\u9FA5]+$");
                if (rx.IsMatch(this.tbxCardNum.Text.Trim()))
                {
                    MessageBoxForm.Show("卡面编号必须是数字或者字母,请重新输入!", MessageBoxButtons.OK);
                    return;
                }
                //判断输入的值是否超过预定的最大值
                string      maxValue        = "0";
                Hashtable   table           = new Hashtable();
                CardTypeBLL _objCardTypeBLL = new CardTypeBLL();
                table.Add("tcit_system", (int)CurrentUser.Current.PARKING_SYSTEM);
                table.Add("tcit_type", (int)CurrentUser.Current.PARK_BACKSTAGE);
                //判断上限分钟是否大于预设值
                if (this.lblCostType.Text.Equals(Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限时卡.ToString("D")))
                {
                    table.Add("tcit_code", CurrentUser.Current.MaxTime);

                    maxValue = _objCardTypeBLL.GetRegisterType(table, null);
                    int   max   = 0;
                    Regex regex = new Regex("[^0-9]");
                    if (string.IsNullOrEmpty(this.tbxOverPlus.Text))
                    {
                        MessageBoxForm.Show("剩余时间不能为空!", MessageBoxButtons.OK);
                        return;
                    }
                    if (regex.IsMatch(maxValue))
                    {
                        MessageBoxForm.Show("限时预设值格式不正确,无法继续充值,请联系管理员!", MessageBoxButtons.OK);
                        return;
                    }
                    if (regex.IsMatch(this.tbxOverPlus.Text))
                    {
                        MessageBoxForm.Show("剩余时间必须为数字,请重新输入!", MessageBoxButtons.OK);
                        return;
                    }
                    max = Convert.ToInt32(this.tbxOverPlus.Text);
                    if (Convert.ToInt32(this.tbxOverPlus.Text) > Convert.ToInt32(this.tbxMax.Text))
                    {
                        MessageBoxForm.Show("剩余时间不能大于上限时间!", MessageBoxButtons.OK);
                        return;
                    }
                    if (Convert.ToInt32(this.tbxOverPlus.Text) > max)
                    {
                        MessageBoxForm.Show("剩余时间不能大于预设最大" + maxValue + "分!", MessageBoxButtons.OK);
                        return;
                    }
                }
                //判断剩余次数是否大于预设值
                else if (this.lblCostType.Text.Equals(Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限次卡.ToString("D")))
                {
                    table.Add("tcit_code", CurrentUser.Current.MaxDegree);

                    maxValue = _objCardTypeBLL.GetRegisterType(table, null);
                    int   max   = 0;
                    Regex regex = new Regex("[^0-9]");
                    if (string.IsNullOrEmpty(this.tbxOverPlus.Text))
                    {
                        MessageBoxForm.Show("剩余次数不能为空!", MessageBoxButtons.OK);
                        return;
                    }
                    if (regex.IsMatch(maxValue))
                    {
                        MessageBoxForm.Show("次数预设值格式不正确,无法继续初始化,请联系管理员!", MessageBoxButtons.OK);
                        return;
                    }
                    if (regex.IsMatch(this.tbxOverPlus.Text))
                    {
                        MessageBoxForm.Show("剩余次数必须为数字,请重新输入!", MessageBoxButtons.OK);
                        return;
                    }
                    max = Int32.Parse(this.tbxOverPlus.Text);
                    if (Convert.ToInt32(this.tbxOverPlus.Text) > Convert.ToInt32(this.tbxMax.Text))
                    {
                        MessageBoxForm.Show("剩余次数不能大于上限次数!", MessageBoxButtons.OK);
                        return;
                    }
                    if (Convert.ToInt32(this.tbxOverPlus.Text) > Convert.ToInt32(maxValue))
                    {
                        MessageBoxForm.Show("剩余次数不能大于预设最大" + maxValue + "次!", MessageBoxButtons.OK);
                        return;
                    }
                }
                //判断剩余金额是否大于预设值
                else if (this.lblCostType.Text.Equals(Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.金额卡.ToString("D")))
                {
                    table.Add("tcit_code", CurrentUser.Current.MaxMoney);

                    maxValue = _objCardTypeBLL.GetRegisterType(table, null);
                    decimal max            = new Decimal(0.00);
                    Regex   RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$");
                    if (string.IsNullOrEmpty(this.tbxOverPlus.Text))
                    {
                        MessageBoxForm.Show("剩余次数不能为空!", MessageBoxButtons.OK);
                        return;
                    }
                    if (!RegDecimalSign.IsMatch(maxValue))
                    {
                        MessageBoxForm.Show("次数预设值格式不正确,无法继续初始化,请联系管理员!", MessageBoxButtons.OK);
                        return;
                    }
                    if (!RegDecimalSign.IsMatch(this.tbxOverPlus.Text))
                    {
                        MessageBoxForm.Show("剩余次数必须为数字,请重新输入!", MessageBoxButtons.OK);
                        return;
                    }
                    max = Convert.ToDecimal(this.tbxOverPlus.Text);
                    if (Convert.ToDecimal(this.tbxOverPlus.Text) > Convert.ToDecimal(this.tbxMax.Text))
                    {
                        MessageBoxForm.Show("剩余金额不能大于上限金额!", MessageBoxButtons.OK);
                        return;
                    }
                    if (Convert.ToDecimal(this.tbxOverPlus.Text) > max)
                    {
                        MessageBoxForm.Show("剩余金额不能大于上限金额" + maxValue + "元!", MessageBoxButtons.OK);
                        return;
                    }
                }
                StringBuilder sb = new StringBuilder();
                //初始化写入密码
                RFIDClass.UpdateCardPassWordAndReturnStatus(this.lblNum.Text, 1, SystemConstant.StringEmpty, CurrentUser.Current.PassWordKey);

                //写入扩展的SAASID
                if (!"0".Equals(SystemConstant.saas_type.SAAS_TYPE.ToString("D")))
                {
                    sb.Append(StringUtil.formatDataString(Convert.ToInt32(lblExtSaasId.Text), 3));
                }
                //写入系统编号
                sb.Append(SystemConstant.system_type.CS_SYSTEM.ToString("D"));
                //写入剩余金额及剩余次数及剩余时间,限期卡为5个0,限时卡前面是小时数,最后一位是分钟数数
                if (this.lblCostType.Text.Equals(Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限期卡.ToString("D")))
                {
                    sb.Append(StringUtil.formatDataString(0, 5));
                }
                else if (this.lblCostType.Text.Equals(Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限时卡.ToString("D")))
                {
                    string hours   = Convert.ToString(Convert.ToInt32(this.tbxOverPlus.Text) / 60);      //根据输入分钟数,输入数字除60取余计算出小时数
                    string minutes = Convert.ToString(Convert.ToInt32(this.tbxOverPlus.Text) % 60 / 10); //根据输入数字除60取模,然后再除以10,得到分钟数,1代表10分钟,2代表20分钟,依次类推

                    sb.Append(StringUtil.formatDataString(Convert.ToInt32(hours + minutes), 5));
                }
                else if (this.lblCostType.Text.Equals(Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.金额卡.ToString("D")))
                {
                    //格式化金额的存储,前4位保存整数,后1位保存小数点后面第一位
                    string money = Convert.ToDecimal(this.tbxOverPlus.Text).ToString("0.0");
                    sb.Append(StringUtil.formatDataString(Convert.ToInt32(money.Replace(".", "")), 5));
                }
                else
                {
                    sb.Append(StringUtil.formatDataString(Convert.ToInt32(this.tbxOverPlus.Text), 5));
                }
                //写入卡面编号
                sb.Append(StringUtil.formatDataString(this.tbxCardNum.Text, 7));
                //写入第一扇区的第零块
                writeBlock(1, 0, sb.ToString());
                sb = new StringBuilder();
                //写入生效日期
                sb.Append(DateTime.Parse(this.lblEffectDate.Text).ToString("yyMMdd"));
                //写入最晚日期
                sb.Append(DateTime.Parse(this.lblOutDate.Text).ToString("yyMMdd"));
                //写入扣费类型
                sb.Append(this.lblCostType.Text.ToString());
                //写入停车卡状态
                sb.Append(Bouwa.ITSP2V31.Model.CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString("D"));
                //写入卡类型
                sb.Append(StringUtil.formatDataString(this.lblExtCardTypeId.Text.ToString(), 2));
                //写入第一扇区的第一块
                writeBlock(1, 1, sb.ToString());
                //把最后操作时间写入第一扇区的第二块
                sb = new StringBuilder();
                sb.Append(DateTime.Now.ToString("yyyyMMddHHmmss"));
                writeBlock(1, 2, sb.ToString());

                RFIDClass.IssueSound(50); //发出声音代表完成
                //将该卡信息写入后台数据库
                Hashtable cardInfo = new Hashtable();
                //插入初始化记录
                Hashtable htCardInfo = new Hashtable();
                //主键
                cardInfo.Add("id", Guid.NewGuid());
                htCardInfo.Add("id", Guid.NewGuid().ToString());
                //saasId
                if (!string.IsNullOrEmpty(this.lblSaasId.Text))
                {
                    cardInfo.Add("saas_id", new Guid(this.lblSaasId.Text));
                    htCardInfo.Add("saas_id", this.lblSaasId.Text);
                }
                //卡内编号
                if (!string.IsNullOrEmpty(this.lblNum.Text))
                {
                    cardInfo.Add("card_id", this.lblNum.Text);
                    htCardInfo.Add("card_id", Guid.Empty.ToString());
                }
                else
                {
                    MessageBoxForm.Show("未读取到卡内编号,请重试!", MessageBoxButtons.OK);
                    return;
                }
                //卡面编号
                if (!string.IsNullOrEmpty(this.tbxCardNum.Text.Trim()))
                {
                    cardInfo.Add("no", StringUtil.formatDataString(this.tbxCardNum.Text, 7));
                    htCardInfo.Add("no", StringUtil.formatDataString(this.tbxCardNum.Text, 7));
                }
                else
                {
                    MessageBoxForm.Show("卡面编号不能为空,请重新输入!", MessageBoxButtons.OK);
                    return;
                }
                //批次
                if (!string.IsNullOrEmpty(this.tbxLotNum.Text))
                {
                    cardInfo.Add("batch", this.tbxLotNum.Text);
                }
                //停车卡类型
                if (!string.IsNullOrEmpty(this.lblCardTypeId.Text))
                {
                    cardInfo.Add("card_type", _objId.ToString());
                }
                cardInfo.Add("status", Bouwa.ITSP2V31.Model.CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString("D"));
                //生效日期
                if (!string.IsNullOrEmpty(this.lblEffectDate.Text))
                {
                    cardInfo.Add("efffect_date", Convert.ToDateTime(this.lblEffectDate.Text));
                }
                //最晚到期
                if (!string.IsNullOrEmpty(this.lblOutDate.Text))
                {
                    cardInfo.Add("end_date", Convert.ToDateTime(this.lblOutDate.Text));
                }

                //停车卡用途
                if (!string.IsNullOrEmpty(this.lblPurpose.Text))
                {
                    cardInfo.Add("purpose", Convert.ToInt32(this.lblPurpose.Text));
                    //cardInfo.purpose = 0;
                }
                //注册类型
                if (!string.IsNullOrEmpty(this.lblSubmitType.Text))
                {
                    cardInfo.Add("submit_type", Convert.ToInt32(this.lblSubmitType.Text));
                }
                //扣费类型
                if (!string.IsNullOrEmpty(this.lblCostType.Text))
                {
                    cardInfo.Add("cost_type", Convert.ToInt32(this.lblCostType.Text));
                    htCardInfo.Add("cost_type", Convert.ToInt32(this.lblCostType.Text));
                }
                //初始化操作日志,仅对非空白卡进行写数据

                string message = SystemConstant.StringEmpty;
                //剩余操作次数
                if (this.lblCostType.Text.Equals(CardTypeInfo.CardTypeInfoCostType.限次卡.ToString("D")))
                {
                    cardInfo.Add("times", Convert.ToInt32(this.tbxOverPlus.Text));
                    //备注信息
                    cardInfo.Add("memo", this.tbxCardNum.Text + "初始化成功!");
                    htCardInfo.Add("volume", Convert.ToInt32(this.tbxOverPlus.Text));
                    //htCardInfo.Add("operation_memo", String.Format(_objSystemMessage.GetInfoByCode("InitMemo").Content, this.tbxCardNum.Text, String.Format(_objSystemMessage.GetInfoByCode("InitTime").Content, this.tbxOverPlus.Text)));
                    message = "InitTime";
                }
                else
                {
                    cardInfo.Add("times", 0);
                }
                //剩余操作金额
                if (this.lblCostType.Text.Equals(CardTypeInfo.CardTypeInfoCostType.金额卡.ToString("D")))
                {
                    cardInfo.Add("money", Convert.ToDecimal(this.tbxOverPlus.Text));
                    //备注信息
                    cardInfo.Add("memo", this.tbxCardNum.Text + "初始化成功!");
                    htCardInfo.Add("volume", Convert.ToDecimal(this.tbxOverPlus.Text));
                    // htCardInfo.Add("operation_memo", String.Format(_objSystemMessage.GetInfoByCode("InitMemo").Content, this.tbxCardNum.Text, String.Format(_objSystemMessage.GetInfoByCode("InitMoney").Content, this.tbxOverPlus.Text)));
                    message = "InitMoney";
                }
                else
                {
                    cardInfo.Add("money", 0);
                }
                //剩余计费时间
                if (this.lblCostType.Text.Equals(CardTypeInfo.CardTypeInfoCostType.限时卡.ToString("D")))
                {
                    cardInfo.Add("charges_date", Convert.ToInt32(this.tbxOverPlus.Text));
                    //备注信息
                    cardInfo.Add("memo", this.tbxCardNum.Text + "初始化成功!");
                    htCardInfo.Add("volume", Convert.ToInt32(this.tbxOverPlus.Text));
                    //htCardInfo.Add("operation_memo", String.Format(_objSystemMessage.GetInfoByCode("InitMemo").Content, this.tbxCardNum.Text, String.Format(_objSystemMessage.GetInfoByCode("InitDegree").Content, this.tbxOverPlus.Text)));
                    message = "InitDegree";
                }
                else
                {
                    cardInfo.Add("charges_date", 0);
                }
                //剩余计费时间
                if (this.lblCostType.Text.Equals(CardTypeInfo.CardTypeInfoCostType.限期卡.ToString("D")))
                {
                    //备注信息
                    cardInfo.Add("memo", this.tbxCardNum.Text + "初始化成功!");
                    htCardInfo.Add("volume", Convert.ToDateTime(this.lblOutDate.Text).ToString("yyyyMMdd"));
                    //htCardInfo.Add("operation_memo", "初始化成功!");
                    message = "InitDate";
                }
                htCardInfo.Add("operation_memo_init", _objSystemMessage.GetInfoByCode("InitMemo").Content);
                htCardInfo.Add("operation_type_init", 1);

                if (this.ddlStatus.Text == CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString())
                {
                    htCardInfo.Add("operation_type_payment", 5);
                    htCardInfo.Add("operation_memo_payment", string.Format(_objSystemMessage.GetInfoByCode(message).Content, this.tbxOverPlus.Text));
                }


                //初始化人员ID
                cardInfo.Add("create_user", CurrentUser.Current.UserId);
                htCardInfo.Add("operation_user", CurrentUser.Current.UserId);
                //初始化时间
                cardInfo.Add("create_time", DateTime.Now);
                htCardInfo.Add("operation_time", DateTime.Now.ToString());
                htCardInfo.Add("modity_user", CurrentUser.Current.UserId);
                htCardInfo.Add("modity_time", DateTime.Now.ToString());
                // htCardInfo.Add("operation_type","1");
                htCardInfo.Add("address_type", "1");
                htCardInfo.Add("network_id", CurrentUser.Current.NetWorkID);
                string mes = _objCardInfoBLL.ChangeCardInitAndBack(cardInfo, htCardInfo, null, ref _objSystemMessageInfo);

                if ("换卡操作成功!".Equals(mes))
                {
                    MessageBoxForm.Show("停车卡[" + this.tbxCardNum.Text + "]换卡成功!", MessageBoxButtons.OK);
                    this.Close();
                }
                else if ("换卡操作失败!".Equals(mes))
                {
                    //写入停车卡状态
                    RFIDClass.UpdateCardPassWordAndReturnStatus(this.lblNum.Text, 1, password, SystemConstant.StringEmpty);
                    writeBlock(1, 0, "");
                    writeBlock(1, 1, "");
                    writeBlock(1, 2, "");
                    MessageBoxForm.Show("停车卡[" + this.tbxCardNum.Text + "]换卡失败!", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                //写入停车卡状态
                RFIDClass.UpdateCardPassWordAndReturnStatus(this.lblNum.Text, 1, password, SystemConstant.StringEmpty);
                writeBlock(1, 0, "");
                writeBlock(1, 1, "");
                writeBlock(1, 2, "");
                MessageBoxForm.Show(ex.Message, MessageBoxButtons.OK);
            }
        }
示例#28
0
        public VixenApplication()
        {
            InitializeComponent();
            labelVersion.Font = new Font("Segoe UI", 14);
            //Get rid of the ugly grip that we dont want to show anyway.
            //Workaround for a MS bug
            statusStrip.Padding = new Padding(statusStrip.Padding.Left,
                                              statusStrip.Padding.Top, statusStrip.Padding.Left, statusStrip.Padding.Bottom);
            statusStrip.Font = SystemFonts.StatusFont;

            Icon      = Resources.Icon_Vixen3;
            ForeColor = ThemeColorTable.ForeColor;
            BackColor = ThemeColorTable.BackgroundColor;
            ThemeUpdateControls.UpdateControls(this);
            statusStrip.BackColor           = ThemeColorTable.BackgroundColor;
            statusStrip.ForeColor           = ThemeColorTable.ForeColor;
            toolStripStatusLabel1.ForeColor = ThemeColorTable.ForeColor;
            toolStripStatusLabelExecutionLight.ForeColor = ThemeColorTable.ForeColor;
            toolStripStatusLabelExecutionState.ForeColor = ThemeColorTable.ForeColor;
            toolStripStatusLabel_memory.ForeColor        = ThemeColorTable.ForeColor;
            contextMenuStripRecent.Renderer = new ThemeToolStripRenderer();

            string[] args = Environment.GetCommandLineArgs();
            foreach (string arg in args)
            {
                _ProcessArg(arg);
            }

            StartJITProfiler();

            if (_rootDataDirectory == null)
            {
                ProcessProfiles();
            }

            _applicationData = new VixenApplicationData(_rootDataDirectory);

            _rootDataDirectory = _applicationData.DataFileDirectory;

            if (!CreateLockFile())
            {
                var form = new MessageBoxForm("Profile is already in use or unable to the lock the profile.", "Error", MessageBoxButtons.OK, SystemIcons.Error);
                form.ShowDialog();
                form.Dispose();
                Environment.Exit(0);
            }

            stopping = false;
            PopulateVersionStrings();
            AppCommands = new AppCommand(this);
            Execution.ExecutionStateChanged += executionStateChangedHandler;
            VixenSystem.Start(this, _openExecution, _disableControllers, _applicationData.DataFileDirectory);

            InitStats();

            // other modules look for and create it this way...
            AppCommand toolsMenu = AppCommands.Find("Tools");

            if (toolsMenu == null)
            {
                toolsMenu = new AppCommand("Tools", "Tools");
                AppCommands.Add(toolsMenu);
            }
            var myMenu = new AppCommand("Options", "Options...");

            myMenu.Click += optionsToolStripMenuItem_Click;
            toolsMenu.Add(myMenu);

            toolStripItemClearSequences.Click += (mySender, myE) => ClearRecentSequencesList();
        }
示例#29
0
        private void ProcessProfiles()
        {
            XMLProfileSettings profile = new XMLProfileSettings();

            // if we don't have any profiles yet, fall through so the "Default" profile will be created
            int profileCount = profile.GetSetting(XMLProfileSettings.SettingType.Profiles, "ProfileCount", 0);

            if (profileCount == 0)
            {
                return;
            }

            // now that we know we have profiles, get the rest of the settings
            string loadAction    = profile.GetSetting(XMLProfileSettings.SettingType.Profiles, "LoadAction", "LoadSelected");
            int    profileToLoad = profile.GetSetting(XMLProfileSettings.SettingType.Profiles, "ProfileToLoad", -1);

            // try to load the selected profile
            if (loadAction != "Ask" && profileToLoad > -1 && profileToLoad < profileCount)
            {
                string directory = profile.GetSetting(XMLProfileSettings.SettingType.Profiles, "Profile" + profileToLoad + "/DataFolder", string.Empty);
                var    isLocked  = IsProfileLocked(directory);
                if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory) && !isLocked)
                {
                    _rootDataDirectory = directory;
                    string profileName = profile.GetSetting(XMLProfileSettings.SettingType.Profiles, "Profile" + profileToLoad + "/Name", string.Empty);
                    UpdateTitleWithProfileName(profileName);
                }
                else
                {
                    string name = profile.GetSetting(XMLProfileSettings.SettingType.Profiles, "Profile" + profileToLoad + "/Name", string.Empty);
                    ShowLoadProfileErrorMessage(name, isLocked);
                }
            }

            // if _rootDataDirectory is still empty at this point either we're configured to always ask or loading the selected profile failed
            // keep asking until we get a good profile directory
            while (string.IsNullOrEmpty(_rootDataDirectory))
            {
                SelectProfile selectProfile = new SelectProfile();
                DialogResult  result        = selectProfile.ShowDialog();

                if (result == DialogResult.OK)
                {
                    string directory = selectProfile.DataFolder;
                    var    isLocked  = IsProfileLocked(directory);
                    if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory) && !isLocked)
                    {
                        _rootDataDirectory = directory;
                        UpdateTitleWithProfileName(selectProfile.ProfileName);
                        break;
                    }
                    ShowLoadProfileErrorMessage(selectProfile.ProfileName, isLocked);
                }
                else if (result == DialogResult.Cancel)
                {
                    var messageBox = new MessageBoxForm(Application.ProductName + " cannot continue without a vaild profile." + Environment.NewLine + Environment.NewLine +
                                                        "Are you sure you want to exit " + Application.ProductName + "?",
                                                        Application.ProductName, MessageBoxButtons.YesNo, SystemIcons.Warning);
                    messageBox.ShowDialog();
                    if (messageBox.DialogResult == DialogResult.OK)
                    {
                        Environment.Exit(0);
                    }
                }
                else
                {
                    // SelectProfile.ShowDialog() should only return DialogResult.OK or Cancel, how did we get here?
                    throw new NotImplementedException("SelectProfile.ShowDialog() returned " + result.ToString());
                }
            }

            SetLogFilePaths();
        }
示例#30
0
        // edits the selected color in the 'edit' control
        private void editSelectedPoints()
        {
            if (edit.Gradient == null || edit.FocusSelection)
            {
                return;
            }

            if (DiscreteColors)
            {
                List <Color> selectedColors = new List <Color>();
                foreach (ColorGradient.Point point in edit.Selection)
                {
                    ColorPoint pt = point as ColorPoint;
                    if (pt == null)
                    {
                        continue;
                    }
                    selectedColors.Add(pt.Color.ToRGB().ToArgb());
                }

                using (DiscreteColorPicker picker = new DiscreteColorPicker()) {
                    picker.ValidColors    = ValidDiscreteColors;
                    picker.SelectedColors = selectedColors;
                    if (picker.ShowDialog() == DialogResult.OK)
                    {
                        if (picker.SelectedColors.Count() == 0)
                        {
                            DeleteColor();
                        }
                        else if (picker.SelectedColors.Count() == selectedColors.Count)
                        {
                            int i = 0;
                            foreach (Color selectedColor in picker.SelectedColors)
                            {
                                ColorPoint pt = edit.Selection[i] as ColorPoint;
                                pt.Color = XYZ.FromRGB(selectedColor);
                            }
                        }
                        else
                        {
                            double position = edit.Selection.First().Position;

                            foreach (ColorGradient.Point point in edit.Selection)
                            {
                                edit.Gradient.Colors.Remove(point as ColorPoint);
                            }

                            foreach (Color selectedColor in picker.SelectedColors)
                            {
                                ColorPoint newPoint = new ColorPoint(selectedColor, position);
                                edit.Gradient.Colors.Add(newPoint);
                            }
                        }
                    }
                }
            }
            else
            {
                if (edit.Selection.Count > 1)
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Error;                     //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("Non-discrete color gradient, >1 selected point. oops! please report it.", "Delete library gradient?", false, false);
                    messageBox.ShowDialog();
                }
                ColorPoint pt = edit.Selection.FirstOrDefault() as ColorPoint;
                if (pt == null)
                {
                    return;
                }
                using (ColorPicker frm = new ColorPicker(_mode, _fader)) {
                    frm.LockValue_V = LockColorEditorHSV_Value;
                    frm.Color       = _xyz;
                    if (frm.ShowDialog(this.FindForm()) == DialogResult.OK)
                    {
                        pt.Color             = _xyz = frm.Color;
                        lblColorSelect.Color = _xyz.ToRGB().ToArgb();
                        _mode  = frm.SecondaryMode;
                        _fader = frm.PrimaryFader;
                    }
                }
            }
        }
示例#31
0
		private void toolStripButtonExportGradients_Click(object sender, EventArgs e)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog
			{
				DefaultExt = ".vgl",
				Filter = @"Vixen 3 Color Gradient Library (*.vgl)|*.vgl|All Files (*.*)|*.*"
			};

			if (_lastFolder != string.Empty) saveFileDialog.InitialDirectory = _lastFolder;
			if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
			_lastFolder = Path.GetDirectoryName(saveFileDialog.FileName);

			var xmlsettings = new XmlWriterSettings
			{
				Indent = true,
				IndentChars = "\t",
			};

			try
			{
				Dictionary<string, ColorGradient> gradients = _colorGradientLibrary.ToDictionary(gradient => gradient.Key, gradient => gradient.Value);

				DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<string, ColorGradient>));
				var writer = XmlWriter.Create(saveFileDialog.FileName, xmlsettings);
				ser.WriteObject(writer, gradients);
				writer.Close();
			}
			catch (Exception ex)
			{
				Logging.Error("While exporting Color Gradient Library: " + saveFileDialog.FileName + " " + ex.InnerException);
				//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
				MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
				var messageBox = new MessageBoxForm("Unable to export data, please check the error log for details.", "Unable to export", false, false);
				messageBox.ShowDialog();
			}
		}
示例#32
0
        private void buttonUnpatchElements_Click(object sender, EventArgs e)
        {
            // find all patches that will be removed. keep track of the element->filter patches,
            // then all other patches, in case we want to keep them.
            // TODO: eh, I may have written this while drunk, it doesn't seem like a particlarly good way to do it

            int patchedCount = _componentOutputs.Count(x => x.Patched);

            if (patchedCount > 20)
            {
                string message = string.Format("Are you sure you want to unpatch {0} patch points?", patchedCount);

                var messageBox = new MessageBoxForm(message, "Unpatch Elements?", MessageBoxButtons.YesNo, SystemIcons.Question);
                messageBox.ShowDialog(this);
                if (messageBox.DialogResult == DialogResult.No)
                {
                    return;
                }
            }

            List <IDataFlowComponent> directElementChildren    = new List <IDataFlowComponent>();
            List <IDataFlowComponent> nonDirectElementChildren = new List <IDataFlowComponent>();

            foreach (ElementNode selectedNode in _cachedElementNodes)
            {
                foreach (ElementNode leafNode in selectedNode.GetLeafEnumerator())
                {
                    if (leafNode.Element == null)
                    {
                        continue;
                    }

                    IDataFlowComponent leafNodeComponent = VixenSystem.DataFlow.GetComponent(leafNode.Element.Id);

                    List <IDataFlowComponent> children = VixenSystem.DataFlow.GetDestinationsOfComponent(leafNodeComponent).ToList();
                    directElementChildren.AddRange(children);

                    foreach (IDataFlowComponent child in children)
                    {
                        nonDirectElementChildren.AddRange(_findComponentsOfTypeInTreeFromComponent(child, typeof(IDataFlowComponent)));
                    }
                }
            }

            bool removeFilters = false;

            if (nonDirectElementChildren.Any(x => x is IOutputFilterModuleInstance))
            {
                var messageBox = new MessageBoxForm("Some elements are patched to filters.  Should these filters be removed as well?",
                                                    "Remove Filters?", MessageBoxButtons.YesNoCancel, SystemIcons.Question);
                messageBox.ShowDialog(this);

                if (messageBox.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                removeFilters = (messageBox.DialogResult == DialogResult.OK);
            }

            foreach (IDataFlowComponent directElementChild in directElementChildren)
            {
                VixenSystem.DataFlow.ResetComponentSource(directElementChild);

                if (removeFilters && directElementChild is IOutputFilterModuleInstance)
                {
                    VixenSystem.Filters.RemoveFilter(directElementChild as IOutputFilterModuleInstance);
                }
            }

            if (removeFilters)
            {
                foreach (IDataFlowComponent nonDirectElementChild in nonDirectElementChildren)
                {
                    if (nonDirectElementChild is IOutputFilterModuleInstance)
                    {
                        VixenSystem.Filters.RemoveFilter(nonDirectElementChild as IOutputFilterModuleInstance);
                    }
                }
            }

            OnPatchingUpdated();
            _UpdateEverything(_cachedElementNodes, _cachedControllersAndOutputs);
        }
示例#33
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     if (txtEffectCount.Value == 0)
     {
         //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
         MessageBoxForm.msgIcon = SystemIcons.Exclamation; //this is used if you want to add a system icon to the message form.
         var messageBox = new MessageBoxForm("OOPS! Your effect count is set to 0 (zero)", "Warning", false, false);
         messageBox.ShowDialog();
         DialogResult = DialogResult.None;
     }
     //Double check for calculations
     if (!TimeExistsForAddition() && !checkBoxAlignToBeatMarks.Checked && !checkBoxFillDuration.Checked )
     {
         //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
         MessageBoxForm.msgIcon = SystemIcons.Exclamation; //this is used if you want to add a system icon to the message form.
         var messageBox = new MessageBoxForm("At least one effect would be placed beyond the sequence length, and will not be added.\n\nWould you like to proceed anyway?", "Warning", true, false);
         messageBox.ShowDialog();
         if (messageBox.DialogResult == DialogResult.No)
         {
             DialogResult = DialogResult.None;
         }
     }
 }
示例#34
0
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChargeValue_Click(object sender, EventArgs e)
        {
            int status = -1; //保存读取后返回的一个状态

            Bouwa.ITSP2V31.Model.CardInfo _cardInfo = _cardBll.GetCardInfoByCard(Bouwa.Helper.CurrentUser.Current.PassWordKey, out status);

            if (_cardInfo == null)
            {
                MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                return;
            }
            else if (status != 0)
            {
                MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                return;
            }
            else if (string.IsNullOrEmpty(_cardInfo.card_id))
            {
                MessageBoxForm.Show("未读取到卡信息,请将卡放到入读卡器上!", MessageBoxButtons.OK);
                return;
            }
            else if (_objCardInfo.card_id != null & _cardInfo.card_id.ToString() != _objCardInfo.card_id.ToString())
            {
                MessageBoxForm.Show("卡信息与当前所读卡信息不一致,请更换卡!", MessageBoxButtons.OK);
                return;
            }
            else if (_objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已充值 ||
                     _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已初始化)
            {
                //测试数据存放
                _cardInfo.id      = _objCardInfo.id;
                _cardInfo.saas_id = CurrentUser.Current.SAASID;
                //_cardInfo.no = _objCardInfo.no;
                _cardInfo.Network_id = CurrentUser.Current.NetWorkID;
                //更新人临时存放当前操作人
                _cardInfo.modify_user = CurrentUser.Current.UserId;
                //最大限额
                _cardInfo.MaxCount = string.IsNullOrEmpty(tbxMax.Text)?99999: decimal.Parse(tbxMax.Text);

                BaseForm bf = null; //保存窗口
                //根据扣费类型跳转到对应的充值界面
                if (_cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.金额卡)
                {
                    bf = new MemoryCard(_cardInfo);
                }
                else if (_cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限次卡)
                {
                    bf = new LimitOfTimeCard(_cardInfo);
                }
                else if (_cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限期卡)
                {
                    bf = new DeadlineCard(_cardInfo);
                }
                else if (_cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限时卡)
                {
                    bf = new TimeCard(_cardInfo);
                }
                else
                {
                    MessageBoxForm.Show("消费类型有误,请联系管理员!", MessageBoxButtons.OK);
                    return;
                }
                //执行跳转
                bf.ShowDialog();

                //刷新窗口数据
                View_Load(sender, e);
            }
            else
            {
                MessageBoxForm.Show("只能对初始化或已充值状态下的卡进行充值!", MessageBoxButtons.OK);
                return;
            }
        }
示例#35
0
        private void ColorSetsSetupForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (displayedColorSetHasDifferences()) {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("Do you want to save changes to the displayed color set?", "Save Changes?", true, true);
                messageBox.ShowDialog();

                switch (messageBox.DialogResult)
                {
                    case DialogResult.OK:
                        if (!SaveDisplayedColorSet()) {
                            e.Cancel = true;
                        }
                        break;

                    case DialogResult.No:
                        break;

                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }
示例#36
0
        /// <summary>
        /// 进行卡重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            if (MessageBoxForm.Show("您确定要进行卡重置?", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                int status = -1; //保存读取后返回的一个状态
                Bouwa.ITSP2V31.Model.CardInfo _cardInfo = _cardBll.GetCardInfoByCard(Bouwa.Helper.CurrentUser.Current.PassWordKey, out status);

                if (_cardInfo == null)
                {
                    MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                    return;
                }
                else if (status != 0)
                {
                    MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                    return;
                }
                else if (string.IsNullOrEmpty(_cardInfo.card_id))
                {
                    MessageBoxForm.Show("未读取到卡信息,请将卡放到入读卡器上!", MessageBoxButtons.OK);
                    return;
                }
                else if (_objCardInfo.card_id != null & _cardInfo.card_id.ToString() != _objCardInfo.card_id.ToString())
                {
                    MessageBoxForm.Show("卡信息与当前所读卡信息不一致,请更换卡!", MessageBoxButtons.OK);
                    return;
                }
                else if (_objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已充值 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已初始化 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.空白卡 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已挂失 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已禁用 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已退卡 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已重置 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.制卡审批
                         )
                {
                    _cardInfo.modify_user = CurrentUser.Current.UserId; //保存更新人
                    int resout = _cardBll.ResetCarInforAndCarHistoryByID(_cardInfo, CurrentUser.Current.PassWordKey);
                    if (resout == 0)
                    {
                        MessageBoxForm.Show("恭喜您卡重置成功!", MessageBoxButtons.OK);
                        //关闭窗口
                        this.Close();
                        return;
                    }
                    else if (resout == 1)
                    {
                        MessageBoxForm.Show("网络连接不正常,请重新进行卡重置!", MessageBoxButtons.OK);
                    }
                    else
                    {
                        MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(resout), MessageBoxButtons.OK);
                    }
                }
                else
                {
                    MessageBoxForm.Show("卡不能识别!", MessageBoxButtons.OK);
                    return;
                }
            }
        }
示例#37
0
        private void timelineControl_ContextSelected(object sender, ContextSelectedEventArgs e)
        {
            _contextMenuStrip.Items.Clear();

            Element element          = e.ElementsUnderCursor.FirstOrDefault();
            TimedSequenceElement tse = element as TimedSequenceElement;

            #region Add Effect

            ToolStripMenuItem contextMenuItemAddEffect = new ToolStripMenuItem("Add Effect(s)")
            {
                Image = Resources.effects
            };
            IEnumerable <IEffectModuleDescriptor> effectDesriptors =
                ApplicationServices.GetModuleDescriptors <IEffectModuleInstance>()
                .Cast <IEffectModuleDescriptor>()
                .OrderBy(x => x.EffectGroup)
                .ThenBy(n => n.EffectName);
            EffectGroups group = effectDesriptors.First().EffectGroup;
            foreach (IEffectModuleDescriptor effectDesriptor in effectDesriptors)
            {
                if (effectDesriptor.EffectName == "Nutcracker")
                {
                    continue;                                                             //Remove this when the Nutcracker module is removed
                }
                if (effectDesriptor.EffectGroup != group)
                {
                    ToolStripSeparator seperator = new ToolStripSeparator();
                    contextMenuItemAddEffect.DropDownItems.Add(seperator);
                    group = effectDesriptor.EffectGroup;
                }
                // Add an entry to the menu
                ToolStripMenuItem contextMenuItemEffect = new ToolStripMenuItem(effectDesriptor.EffectName);
                contextMenuItemEffect.Image       = effectDesriptor.GetRepresentativeImage();
                contextMenuItemEffect.Tag         = effectDesriptor.TypeId;
                contextMenuItemEffect.ToolTipText = @"Use Shift key to add multiple effects of the same type.";
                contextMenuItemEffect.Click      += (mySender, myE) =>
                {
                    if (e.Row != null)
                    {
                        //add multiple
                        if (ModifierKeys == Keys.Shift || ModifierKeys == (Keys.Shift | Keys.Control))
                        {
                            AddMultipleEffects(e.GridTime, effectDesriptor.EffectName, (Guid)contextMenuItemEffect.Tag, e.Row);
                        }
                        else                         //add single
                        {
                            AddNewEffectById((Guid)contextMenuItemEffect.Tag, e.Row, e.GridTime, TimeSpan.FromSeconds(2), true);
                        }
                    }
                };

                contextMenuItemAddEffect.DropDownItems.Add(contextMenuItemEffect);
            }

            _contextMenuStrip.Items.Add(contextMenuItemAddEffect);

            #endregion

            #region Layer Section

            ConfigureLayerMenu(e);

            #endregion

            #region Effect Alignment Section

            ToolStripMenuItem contextMenuItemAlignment = new ToolStripMenuItem("Alignment")
            {
                Enabled = TimelineControl.grid.OkToUseAlignmentHelper(TimelineControl.SelectedElements),
                Image   = Resources.alignment
            };
            //Disables the Alignment menu if too many effects are selected in a row.
            if (!contextMenuItemAlignment.Enabled)
            {
                contextMenuItemAlignment.ToolTipText = @"Disabled, maximum selected effects per row is 32.";
            }

            ToolStripMenuItem contextMenuItemAlignStart = new ToolStripMenuItem("Align Start Times")
            {
                ToolTipText = @"Holding shift will align the start times, while holding duration.",
                Image       = Resources.alignStart
            };
            contextMenuItemAlignStart.Click +=
                (mySender, myE) =>
                TimelineControl.grid.AlignElementStartTimes(TimelineControl.SelectedElements, element, ModifierKeys == Keys.Shift);
            contextMenuItemAlignStart.ShortcutKeyDisplayString = @"(Shift)+S";

            ToolStripMenuItem contextMenuItemAlignEnd = new ToolStripMenuItem("Align End Times")
            {
                ToolTipText = @"Holding shift will align the end times, while holding duration.",
                Image       = Resources.alignEnd
            };
            contextMenuItemAlignEnd.Click +=
                (mySender, myE) =>
                TimelineControl.grid.AlignElementEndTimes(TimelineControl.SelectedElements, element, ModifierKeys == Keys.Shift);
            contextMenuItemAlignEnd.ShortcutKeyDisplayString = @"(Shift)+E";

            ToolStripMenuItem contextMenuItemAlignBoth = new ToolStripMenuItem("Align Both Times")
            {
                Image = Resources.alignBoth
            };
            contextMenuItemAlignBoth.Click +=
                (mySender, myE) => TimelineControl.grid.AlignElementStartEndTimes(TimelineControl.SelectedElements, element);
            contextMenuItemAlignBoth.ShortcutKeyDisplayString = @"B";

            ToolStripMenuItem contextMenuItemMatchDuration = new ToolStripMenuItem("Match Duration")
            {
                ToolTipText =
                    @"Holding shift will hold the effects end time and adjust the start time, by default the end time is adjusted.",
                Image = Resources.matchDuration
            };
            contextMenuItemMatchDuration.Click +=
                (mySender, myE) =>
                TimelineControl.grid.AlignElementDurations(TimelineControl.SelectedElements, element, ModifierKeys == Keys.Shift);
            contextMenuItemMatchDuration.ShortcutKeyDisplayString = @"(Shift)";

            ToolStripMenuItem contextMenuItemAlignStartToEnd = new ToolStripMenuItem("Align Start to End")
            {
                ToolTipText =
                    @"Holding shift will hold the effects end time and only adjust the start time, by default the entire effect is moved.",
                Image = Resources.alignStartEnd
            };
            contextMenuItemAlignStartToEnd.Click +=
                (mySender, myE) =>
                TimelineControl.grid.AlignElementStartToEndTimes(TimelineControl.SelectedElements, element,
                                                                 ModifierKeys == Keys.Shift);
            contextMenuItemAlignStartToEnd.ShortcutKeyDisplayString = @"(Shift)";

            ToolStripMenuItem contextMenuItemAlignEndToStart = new ToolStripMenuItem("Align End to Start")
            {
                ToolTipText =
                    @"Holding shift will hold the effects start time and only adjust the end time, by default the entire effect is moved.",
                Image = Resources.alignStartEnd
            };
            contextMenuItemAlignEndToStart.Click +=
                (mySender, myE) =>
                TimelineControl.grid.AlignElementEndToStartTime(TimelineControl.SelectedElements, element,
                                                                ModifierKeys == Keys.Shift);
            contextMenuItemAlignEndToStart.ShortcutKeyDisplayString = @"(Shift)";

            ToolStripMenuItem contextMenuItemDistDialog = new ToolStripMenuItem("Distribute Effects")
            {
                Image = Resources.distribute
            };
            contextMenuItemDistDialog.Click += (mySender, myE) => DistributeSelectedEffects();

            ToolStripMenuItem contextMenuItemAlignCenter = new ToolStripMenuItem("Align Centerpoints")
            {
                Image = Resources.alignCenter
            };
            contextMenuItemAlignCenter.Click +=
                (mySender, myE) => TimelineControl.grid.AlignElementCenters(TimelineControl.SelectedElements, element);

            ToolStripMenuItem contextMenuItemDistributeEqually = new ToolStripMenuItem("Distribute Equally")
            {
                ToolTipText =
                    @"This will stair step the selected elements, starting with the element that has the earlier start mouseLocation on the time line.",
                Image = Resources.distribute
            };
            contextMenuItemDistributeEqually.Click += (mySender, myE) => DistributeSelectedEffectsEqually();

            ToolStripMenuItem contextMenuItemAlignStartToMark = new ToolStripMenuItem("Align Start to nearest mark")
            {
                Image = Resources.alignStartMark
            };
            contextMenuItemAlignStartToMark.Click += (mySender, myE) => AlignEffectsToNearestMarks("Start");
            contextMenuItemAlignStartToMark.ShortcutKeyDisplayString = @"Ctrl+Shift+S";

            ToolStripMenuItem contextMenuItemAlignEndToMark = new ToolStripMenuItem("Align End to nearest mark")
            {
                Image = Resources.alignEndMark
            };
            contextMenuItemAlignEndToMark.Click += (mySender, myE) => AlignEffectsToNearestMarks("End");
            contextMenuItemAlignEndToMark.ShortcutKeyDisplayString = @"Ctrl+Shift+E";

            ToolStripMenuItem contextMenuItemAlignBothToMark = new ToolStripMenuItem("Align Both to nearest mark")
            {
                Image = Resources.alignBothMark
            };
            contextMenuItemAlignBothToMark.Click += (mySender, myE) => AlignEffectsToNearestMarks("Both");
            contextMenuItemAlignBothToMark.ShortcutKeyDisplayString = @"Ctrl+Shift+B";

            _contextMenuStrip.Items.Add(contextMenuItemAlignment);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignStart);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignEnd);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignBoth);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignCenter);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemMatchDuration);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignStartToEnd);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignEndToStart);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemDistributeEqually);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemDistDialog);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignStartToMark);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignEndToMark);
            contextMenuItemAlignment.DropDown.Items.Add(contextMenuItemAlignBothToMark);

            if (TimelineControl.SelectedElements.Count() > 1 || (TimelineControl.SelectedElements.Any() && !element.Selected))
            {
                contextMenuItemDistributeEqually.Enabled = true;
                contextMenuItemDistDialog.Enabled        = true;
                contextMenuItemAlignStart.Enabled        = true;
                contextMenuItemAlignEnd.Enabled          = true;
                contextMenuItemAlignBoth.Enabled         = true;
                contextMenuItemAlignCenter.Enabled       = true;
                contextMenuItemMatchDuration.Enabled     = true;
                contextMenuItemAlignEndToStart.Enabled   = true;
                contextMenuItemAlignStartToEnd.Enabled   = true;
                contextMenuItemAlignment.Enabled         = true;
                contextMenuItemAlignment.ToolTipText     = string.Empty;
            }
            else
            {
                contextMenuItemDistributeEqually.Enabled = false;
                contextMenuItemDistDialog.Enabled        = false;
                contextMenuItemAlignStart.Enabled        = false;
                contextMenuItemAlignEnd.Enabled          = false;
                contextMenuItemAlignBoth.Enabled         = false;
                contextMenuItemAlignCenter.Enabled       = false;
                contextMenuItemMatchDuration.Enabled     = false;
                contextMenuItemAlignEndToStart.Enabled   = false;
                contextMenuItemAlignStartToEnd.Enabled   = false;
                contextMenuItemAlignment.Enabled         = false;
                if (TimelineControl.SelectedElements.Count() == 1)
                {
                    contextMenuItemAlignment.ToolTipText =
                        @"Select more then one effect or ensure you have Marks added to enable the Alignment feature.";
                }
                else
                {
                    contextMenuItemAlignment.ToolTipText = @"Select more then one effect to enable the Alignment feature.";
                }
            }

            contextMenuItemAlignStartToMark.Enabled = false;
            contextMenuItemAlignEndToMark.Enabled   = false;
            contextMenuItemAlignBothToMark.Enabled  = false;

            foreach (MarkCollection mc in _sequence.LabeledMarkCollections)
            {
                if (mc.Marks.Any())
                {
                    contextMenuItemAlignStartToMark.Enabled = true;
                    contextMenuItemAlignEndToMark.Enabled   = true;
                    contextMenuItemAlignBothToMark.Enabled  = true;
                    contextMenuItemAlignment.Enabled        = true;
                    contextMenuItemAlignment.ToolTipText    = string.Empty;
                    break;
                }
            }
            #endregion

            #region Effect Manipulation Section
            if (tse != null)
            {
                ToolStripMenuItem contextMenuItemManipulation     = new ToolStripMenuItem("Manipulation");
                ToolStripMenuItem contextMenuItemManipulateDivide = new ToolStripMenuItem("Divide at cursor")
                {
                    Image = Resources.divide
                };
                contextMenuItemManipulateDivide.Click += (mySender, myE) =>
                {
                    if (TimelineControl.SelectedElements.Any())
                    {
                        TimelineControl.grid.SplitElementsAtTime(
                            TimelineControl.SelectedElements.Where(elem => elem.StartTime <e.GridTime && elem.EndTime> e.GridTime)
                            .ToList(), e.GridTime);
                    }
                    else
                    {
                        TimelineControl.grid.SplitElementsAtTime(new List <Element> {
                            element
                        }, e.GridTime);
                    }
                };

                ToolStripMenuItem contextMenuItemManipulationClone = new ToolStripMenuItem("Clone")
                {
                    Image = Resources.page_copy
                };
                contextMenuItemManipulationClone.Click += (mySender, myE) =>
                {
                    if (TimelineControl.SelectedElements.Any())
                    {
                        CloneElements(TimelineControl.SelectedElements ?? new List <Element> {
                            element
                        });
                    }
                    else
                    {
                        CloneElements(new List <Element> {
                            element
                        });
                    }
                };

                ToolStripMenuItem contextMenuItemManipulationCloneToOther = new ToolStripMenuItem("Clone to selected effects")
                {
                    Image = Resources.copySelect
                };
                contextMenuItemManipulationCloneToOther.Click += (mySender, myE) =>
                {
                    if (TimelineControl.SelectedElements.Any(elem => elem.EffectNode.Effect.TypeId != element.EffectNode.Effect.TypeId))
                    {
                        //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                        MessageBoxForm.msgIcon = SystemIcons.Warning;                         //this is used if you want to add a system icon to the message form.
                        var messageBox = new MessageBoxForm(string.Format(
                                                                "Some of the selected effects are not of the same type, only effects of {0} type will be modified.",
                                                                element.EffectNode.Effect.EffectName), @"Multiple type effect selected", false, true);
                        messageBox.ShowDialog();
                        if (messageBox.DialogResult == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    foreach (
                        Element elem in
                        TimelineControl.SelectedElements.Where(elem => elem != element)
                        .Where(elem => elem.EffectNode.Effect.TypeId == element.EffectNode.Effect.TypeId))
                    {
                        elem.EffectNode.Effect.ParameterValues = element.EffectNode.Effect.ParameterValues;
                        elem.RenderElement();
                    }
                };
                contextMenuItemManipulationCloneToOther.Enabled = (TimelineControl.SelectedElements.Count() > 2);

                _contextMenuStrip.Items.Add(contextMenuItemManipulation);
                contextMenuItemManipulation.DropDown.Items.Add(contextMenuItemManipulateDivide);
                contextMenuItemManipulation.DropDown.Items.Add(contextMenuItemManipulationClone);
                contextMenuItemManipulation.DropDown.Items.Add(contextMenuItemManipulationCloneToOther);

                ToolStripMenuItem contextMenuItemEditTime = new ToolStripMenuItem("Edit Time")
                {
                    Image = Resources.clock_edit
                };
                contextMenuItemEditTime.Click += (mySender, myE) =>
                {
                    EffectTimeEditor editor = new EffectTimeEditor(tse.EffectNode.StartTime, tse.EffectNode.TimeSpan, SequenceLength);
                    if (editor.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }

                    if (TimelineControl.SelectedElements.Any())
                    {
                        var elementsToMove = TimelineControl.SelectedElements.ToDictionary(elem => elem,
                                                                                           elem => new Tuple <TimeSpan, TimeSpan>(editor.Start, editor.Start + editor.Duration));
                        TimelineControl.grid.MoveResizeElements(elementsToMove);
                    }
                    else
                    {
                        TimelineControl.grid.MoveResizeElement(element, editor.Start, editor.Duration);
                    }
                };
                //Why do we set .Tag ?
                contextMenuItemEditTime.Tag     = tse;
                contextMenuItemEditTime.Enabled = TimelineControl.grid.OkToUseAlignmentHelper(TimelineControl.SelectedElements);
                if (!contextMenuItemEditTime.Enabled)
                {
                    contextMenuItemEditTime.ToolTipText = @"Disabled, maximum selected effects per row is 32.";
                }
                _contextMenuStrip.Items.Add(contextMenuItemEditTime);
            }
            #endregion

            #region Cut Copy Paste Section

            _contextMenuStrip.Items.Add("-");

            ToolStripMenuItem contextMenuItemCopy = new ToolStripMenuItem("Copy", null, toolStripMenuItem_Copy_Click)
            {
                ShortcutKeyDisplayString = @"Ctrl+C",
                Image = Resources.page_copy
            };
            ToolStripMenuItem contextMenuItemCut = new ToolStripMenuItem("Cut", null, toolStripMenuItem_Cut_Click)
            {
                ShortcutKeyDisplayString = @"Ctrl+X",
                Image = Resources.cut
            };
            contextMenuItemCopy.Enabled = contextMenuItemCut.Enabled = TimelineControl.SelectedElements.Any();
            ToolStripMenuItem contextMenuItemPaste = new ToolStripMenuItem("Paste", null, toolStripMenuItem_Paste_Click)
            {
                ShortcutKeyDisplayString = @"Ctrl+V", Image = Resources.page_white_paste,
                Enabled = ClipboardHasData()
            };

            _contextMenuStrip.Items.AddRange(new ToolStripItem[] { contextMenuItemCut, contextMenuItemCopy, contextMenuItemPaste });

            if (TimelineControl.SelectedElements.Any())
            {
                //Add Delete/Collections
                ToolStripMenuItem contextMenuItemDelete = new ToolStripMenuItem("Delete Effect(s)", null,
                                                                                toolStripMenuItem_deleteElements_Click)
                {
                    ShortcutKeyDisplayString = @"Del", Image = Resources.delete
                };
                _contextMenuStrip.Items.Add(contextMenuItemDelete);
                AddContextCollectionsMenu();
            }

            #endregion

            #region Mark Section

            ToolStripMenuItem contextMenuItemAddMark = new ToolStripMenuItem("Add Marks to Effects")
            {
                Image = Resources.marks
            };
            contextMenuItemAddMark.Click += (mySender, myE) => AddMarksToSelectedEffects();
            _contextMenuStrip.Items.Add(contextMenuItemAddMark);

            #endregion

            e.AutomaticallyHandleSelection = false;
            _contextMenuStrip.Show(MousePosition);
        }
示例#38
0
        /// <summary>
        /// 执行退卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click(object sender, EventArgs e)
        {
            if (MessageBoxForm.Show("您确定要进行退卡?", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                int status = -1; //保存读取后返回的一个状态
                Bouwa.ITSP2V31.Model.CardInfo _cardInfo = _cardBll.GetCardInfoByCard(Bouwa.Helper.CurrentUser.Current.PassWordKey, out status);

                if (_cardInfo == null)
                {
                    MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                    return;
                }
                else if (status != 0)
                {
                    MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                    return;
                }
                else if (string.IsNullOrEmpty(_cardInfo.card_id))
                {
                    MessageBoxForm.Show("未读取到卡信息,请将卡放到入读卡器上!", MessageBoxButtons.OK);
                    return;
                }
                else if (_objCardInfo.card_id != null & _cardInfo.card_id.ToString() != _objCardInfo.card_id.ToString())
                {
                    MessageBoxForm.Show("卡信息与当前所读卡信息不一致,请更换卡!", MessageBoxButtons.OK);
                    return;
                }
                else if (_objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已充值)
                {
                    //测试数据存放
                    _cardInfo.id         = _objCardInfo.id;
                    _cardInfo.saas_id    = CurrentUser.Current.SAASID;
                    _cardInfo.Network_id = CurrentUser.Current.NetWorkID;
                    //更新人临时存放当前操作人
                    _cardInfo.modify_user = CurrentUser.Current.UserId;
                    //备份当前状态
                    Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus backStatus = _cardInfo.status;
                    //更改状态为退卡
                    _cardInfo.status = Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已退卡;

                    //根据扣费类型获取对应的量
                    if (_cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.金额卡 ||
                        _cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限次卡 ||
                        _cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限期卡 ||
                        _cardInfo.cost_type == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoCostType.限时卡)
                    {
                        //执行退卡操作
                        int resout = _cardBll.UpdateCarInfoAndBackCardHistoryRecord(_cardInfo, CurrentUser.Current.PassWordKey, true);
                        if (resout == 0)
                        {
                            MessageBoxForm.Show("恭喜您退卡成功!", MessageBoxButtons.OK);
                            //关闭窗口
                            this.Close();
                            return;
                        }
                        else if (resout == 1)
                        {
                            MessageBoxForm.Show("网络连接不正常,请重新进行退卡操作!", MessageBoxButtons.OK);
                        }
                        else
                        {
                            MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(resout), MessageBoxButtons.OK);
                        }
                        //更改到之前的状态
                        _cardInfo.status = backStatus;
                        //退卡失败后进行回写
                        _cardBll.UpdateCarInfoAndBackCardHistoryRecord(_cardInfo, CurrentUser.Current.PassWordKey, false);
                    }
                    else
                    {
                        MessageBoxForm.Show("消费类型有误,请联系管理员!", MessageBoxButtons.OK);
                        return;
                    }
                }
                else if (_objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已退卡)
                {
                    MessageBoxForm.Show("已是退卡状态,不能进行退卡操作!", MessageBoxButtons.OK);
                }
                else if (_objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已初始化 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.空白卡 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已挂失 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已禁用 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已重置 ||
                         _objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.制卡审批
                         )
                {
                    MessageBoxForm.Show("已充值状态下才能进行退卡操作!", MessageBoxButtons.OK);
                }
                else
                {
                    MessageBoxForm.Show("卡不能识别!", MessageBoxButtons.OK);
                    return;
                }
            }
        }
示例#39
0
        private XElement _Version_1_to_2(XElement content)
        {
            var messageBox = new MessageBoxForm(string.Format(
                                                    "Migrating sequence from version 1 to version 2. Changes include upgrades to the Alternating effect to allow more than 2 colors.{0}{0}" +
                                                    "These changes are not backward compatible.", Environment.NewLine), "Sequence Upgrade", MessageBoxButtons.OK, SystemIcons.Information);

            messageBox.StartPosition = FormStartPosition.CenterScreen;
            messageBox.ShowDialog();
            //This migration deals with changing the Alternating effect to a Multi Alternating
            //Style that allows N number of colors.
            var namespaces = GetStandardNamespaces();
            //Add in our specific ones
            XNamespace d2p1 = "http://schemas.datacontract.org/2004/07/VixenModules.Effect.Alternating";

            namespaces.AddNamespace("d2p1", d2p1.NamespaceName);


            //Find the Alternating effects.
            IEnumerable <XElement> alternatingElements =
                content.XPathSelectElements(
                    "_dataModels/d1p1:anyType[@i:type = 'd2p1:AlternatingData']",
                    namespaces);

            var datamodel = content.XPathSelectElement("_dataModels", namespaces);

            foreach (var alternatingElement in alternatingElements.ToList())
            {
                //Find all the data points.
                XElement isStaticColor1   = alternatingElement.XPathSelectElement("d2p1:StaticColor1", namespaces);
                XElement isStaticColor2   = alternatingElement.XPathSelectElement("d2p1:StaticColor2", namespaces);
                XElement color1           = alternatingElement.XPathSelectElement("d2p1:Color1", namespaces);
                XElement level1           = alternatingElement.XPathSelectElement("d2p1:Level1", namespaces);
                XElement colorGradient1   = alternatingElement.XPathSelectElement("d2p1:ColorGradient1", namespaces);
                XElement curve1           = alternatingElement.XPathSelectElement("d2p1:Curve1", namespaces);
                XElement color2           = alternatingElement.XPathSelectElement("d2p1:Color2", namespaces);
                XElement level2           = alternatingElement.XPathSelectElement("d2p1:Level2", namespaces);
                XElement colorGradient2   = alternatingElement.XPathSelectElement("d2p1:ColorGradient2", namespaces);
                XElement curve2           = alternatingElement.XPathSelectElement("d2p1:Curve2", namespaces);
                XElement enable           = alternatingElement.XPathSelectElement("d2p1:Enable", namespaces);
                XElement groupEffect      = alternatingElement.XPathSelectElement("d2p1:GroupEffect", namespaces);
                XElement interval         = alternatingElement.XPathSelectElement("d2p1:Interval", namespaces);
                XElement moduleInstanceId = alternatingElement.XPathSelectElement("ModuleInstanceId", namespaces);
                XElement moduleTypeId     = alternatingElement.XPathSelectElement("ModuleTypeId", namespaces);

                //Determine which of the old types were used, colors vs gradients
                //The new only uses gradients and levels so take the two and build up the new object
                var gradientLevelPairs = new List <GradientLevelPair>();

                //Colors are used backwards in the old effect, so pick them off in reverse.
                if (isStaticColor2.Value.Equals("true"))
                {
                    RGB    c2 = DeSerializer <RGB>(color2);
                    double l2 = DeSerializer <double>(level2);
                    l2 *= 100;
                    gradientLevelPairs.Add(new GradientLevelPair(c2,
                                                                 new Curve(new PointPairList(new[] { 0.0, 100.0 }, new[] { l2, l2 }))));
                }
                else
                {
                    ColorGradient cg2 = DeSerializer <ColorGradient>(colorGradient2);
                    Curve         c2  = DeSerializer <Curve>(curve2);
                    gradientLevelPairs.Add(new GradientLevelPair(cg2, c2));
                }


                if (isStaticColor1.Value.Equals("true"))
                {
                    RGB    c1 = DeSerializer <RGB>(color1);
                    double l1 = DeSerializer <double>(level1);
                    l1 *= 100;
                    gradientLevelPairs.Add(new GradientLevelPair(c1,
                                                                 new Curve(new PointPairList(new[] { 0.0, 100.0 }, new[] { l1, l1 }))));
                }
                else
                {
                    ColorGradient cg1 = DeSerializer <ColorGradient>(colorGradient1);
                    Curve         c1  = DeSerializer <Curve>(curve1);
                    gradientLevelPairs.Add(new GradientLevelPair(cg1, c1));
                }


                //Build the new data model
                AlternatingData data = new AlternatingData
                {
                    Colors            = gradientLevelPairs,
                    ModuleInstanceId  = DeSerializer <Guid>(moduleInstanceId),
                    ModuleTypeId      = DeSerializer <Guid>(moduleTypeId),
                    EnableStatic      = !DeSerializer <bool>(enable),
                    GroupLevel        = DeSerializer <int>(groupEffect),
                    Interval          = DeSerializer <int>(interval),
                    IntervalSkipCount = 1
                };

                //Remove the old data model from the xml
                alternatingElement.Remove();

                //Build up a temporary container similar to the way sequences are stored to
                //make all the namespace prefixes line up.
                IModuleDataModel[] dm = { data };
                DataContainer      dc = new DataContainer {
                    _dataModels = dm
                };

                //Serialize the object into a xelement
                XElement glp = Serializer(dc, new[] { typeof(AlternatingData), typeof(IModuleDataModel[]), typeof(DataContainer) });

                //Extract the new data model that we want and insert it in the tree
                datamodel.Add(glp.XPathSelectElement("//*[local-name()='anyType']", namespaces));
            }

            return(content);
        }
示例#40
0
        /// <summary>
        /// 申请换卡 跟换卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeCard_Click(object sender, EventArgs e)
        {
            try
            {
                //询问用户
                if (MessageBoxForm.Show("您确定要进行" + btnChangeCard.Text + "?", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    Bouwa.ITSP2V31.Model.CardInfo _cardInfo = new Bouwa.ITSP2V31.Model.CardInfo();
                    //执行对象复制
                    ObjectMapper.CopyProperties(_objCardInfo, _cardInfo);

                    //说明是申请换卡
                    if (btnChangeCard.Tag.ToString() == "0")
                    {
                        //只有在已充值的状态下才能申请换卡
                        if (_objCardInfo.status == Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已充值)
                        {
                            //测试数据存放
                            _cardInfo.saas_id    = CurrentUser.Current.SAASID;
                            _cardInfo.Network_id = CurrentUser.Current.NetWorkID;
                            //更新人临时存放当前操作人
                            _cardInfo.modify_user = CurrentUser.Current.UserId;
                            //更改状态为退卡
                            _cardInfo.status = Bouwa.ITSP2V31.Model.CardInfo.CardTypeInfoDefaultCardStatus.已挂失;

                            //执行退卡操作
                            int resout = _cardBll.UpdateCarInfoAndApplyChangeCardHistoryRecord(_cardInfo, CurrentUser.Current.PassWordKey, true);
                            if (resout == 0)
                            {
                                MessageBoxForm.Show("恭喜您" + btnChangeCard.Text + "成功!", MessageBoxButtons.OK);
                                //关闭窗口
                                this.Close();
                                return;
                            }
                            else if (resout == 1)
                            {
                                MessageBoxForm.Show("网络连接不正常,请重新进行" + btnChangeCard.Text + "操作!", MessageBoxButtons.OK);
                            }
                            else
                            {
                                MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(resout), MessageBoxButtons.OK);
                            }
                        }
                        else
                        {
                            MessageBoxForm.Show("已充值状态下才能进行" + btnChangeCard.Text + "操作!", MessageBoxButtons.OK);
                        }
                    }    //说明是执行换卡操作
                    else
                    {
                        //执行换卡操作
                        Bouwa.ITSP2V31.Win.CardType.ChangeCardInit _cardInit = new Bouwa.ITSP2V31.Win.CardType.ChangeCardInit(_cardInfo);
                        this.Parameter["ActionType"] = "Init";
                        _cardInit.ShowDialog();
                        this.Close();
                        //换卡结束
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriterLine(ELevel.error, "执行" + btnChangeCard.Text + "操作出现异常", ex.Message);
                MessageBoxForm.Show("执行" + btnChangeCard.Text + "操作出现异常,请稍后再试!", MessageBoxButtons.OK);
            }
        }
示例#41
0
        private bool _Validate()
        {
            List<string> messages = new List<string>();

            if (string.IsNullOrWhiteSpace(_ProgramName)) {
                messages.Add("* Program does not have a name.");
            }

            if (_ProgramSequences.Count() == 0) {
                messages.Add("* The program has no sequences.");
            }

            if (messages.Count > 0) {
                messages.Insert(0, "The following problems need to be corrected:");
                messages.Insert(1, Environment.NewLine);
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Hand; //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm(string.Join(Environment.NewLine, messages), "Vixen Program", false, false);
                messageBox.ShowDialog();
                return false;
            }

            return true;
        }
示例#42
0
        /// <summary>
        /// 绑定DataGirdView
        /// </summary>
        private int RefreshDataGridView()
        {
            BindingSource bs           = new BindingSource();
            Hashtable     objHashtable = new Hashtable();

            objHashtable.Add("no", this.tbxCardNo.Text.Trim());
            objHashtable.Add("batch", this.tbxBatch.Text.Trim());
            objHashtable.Add("card_type", this.tbtCardType.Text.Trim());

            if (this.ddlPurpose.SelectedValue != null && int.Parse(this.ddlPurpose.SelectedValue.ToString()) != -1)
            {
                objHashtable.Add("purpose", this.ddlPurpose.SelectedValue);
            }
            if (this.ddlRegistType.SelectedValue != null && int.Parse(this.ddlRegistType.SelectedValue.ToString()) != -1)
            {
                objHashtable.Add("submit_type", this.ddlRegistType.SelectedValue);
            }
            if (this.ddlCostType.SelectedValue != null && int.Parse(this.ddlCostType.SelectedValue.ToString()) != -1)
            {
                objHashtable.Add("cost_type", this.ddlCostType.SelectedValue);
            }
            if (int.Parse(this.ddlStatus.SelectedValue.ToString()) != -1)
            {
                objHashtable.Add("status", this.ddlStatus.SelectedValue);
            }
            objHashtable.Add("saas_id", CurrentUser.Current.SAASID);

            string OrderByName = string.Empty;
            string OrderBy     = string.Empty;
            string OrderName   = string.Empty;

            if (this.ddlOrderName.Text == "批次")
            {
                OrderName = "batch";
            }
            else
            {
                OrderName = "card_type";
            }

            if (this.ddlOrderBy.Text == "降序")
            {
                OrderBy = "DESC";
            }
            else
            {
                OrderBy = "ASC";
            }
            OrderByName = OrderName + " " + OrderBy;

            CurrentUser.Current.PageIndex = this.pager1.PageCurrent;
            CurrentUser.Current.PageSize  = this.pager1.PageSize;

            if (CurrentUser.Current.TotalCount == 0)
            {
                CurrentUser.Current.PageIndex = 0;
                CurrentUser.Current.PageCount = 0;
            }
            else
            {
                CurrentUser.Current.PageCount = CurrentUser.Current.TotalCount % CurrentUser.Current.PageSize == 0 ? CurrentUser.Current.TotalCount / CurrentUser.Current.PageSize : CurrentUser.Current.TotalCount / CurrentUser.Current.PageSize + 1;
                if (CurrentUser.Current.PageIndex > CurrentUser.Current.PageCount)
                {
                    CurrentUser.Current.PageIndex = CurrentUser.Current.PageCount;
                }
            }

            IList <Bouwa.ITSP2V31.Model.CardInfo> CardInfo = _objCardInfoBLL.SearchByCondition(objHashtable, null, CurrentUser.Current.PageSize, CurrentUser.Current.PageIndex, OrderByName, ref _objSystemMessageInfo);

            bs.DataSource = CardInfo;
            this.pager1.bindingSource.DataSource       = bs;
            this.pager1.bindingNavigator.BindingSource = pager1.bindingSource;
            this.dgvMain.DataSource = pager1.bindingSource;

            if (!_objSystemMessageInfo.Success)
            {
                MessageBoxForm.Show(_objSystemMessageInfo, MessageBoxButtons.OK);
            }
            return(CurrentUser.Current.TotalCount);
        }
示例#43
0
		private void toolStripButtonDeleteColor_Click(object sender, EventArgs e)
		{
			if (listViewColors.SelectedItems == null)
				return;

			//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
			MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
			var messageBox = new MessageBoxForm("Are you sure you want to delete this color?", "Delete color?", true, true);
			messageBox.ShowDialog();

			if (messageBox.DialogResult == DialogResult.OK)
			{
				_colors.Remove((Color)listViewColors.SelectedItems[0].Tag);
			}

			PopulateColors();
			Save_ColorPaletteFile();
		}
示例#44
0
        private void buttonStartCancel_Click(object sender, EventArgs e)
        {
            if (_working)
            {
                _bw.CancelAsync();
                return;
            }
            _item = comboBoxProfiles.SelectedItem as ProfileItem;
            if (_item == null)
            {
                //Oops.. Get outta here
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Error;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("Unable to find datafolder for that profile.", @"Error", false, false);
                messageBox.ShowDialog();
                return;
            }

            if (textBoxSaveFolder.Text == "")
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Error;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("Please choose a folder to create the zip file in.", @"Missing save folder", false, false);
                messageBox.ShowDialog();
                return;
            }

            var invalidChars = Path.GetInvalidPathChars();

            if (textBoxSaveFolder.Text.Any(s => invalidChars.Contains(s)))
            {
                var messageBox = new MessageBoxForm("The folder path for the zip file contains invalid characters.", @"Invalid Folder Path.", MessageBoxButtons.OK, SystemIcons.Error);
                messageBox.ShowDialog();
                return;
            }

            if (textBoxFileName.Text == "")
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Information;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("Please choose a filename for the zip file.", @"Missing Zip file name", false, false);
                messageBox.ShowDialog();
                return;
            }

            invalidChars = Path.GetInvalidFileNameChars();
            if (textBoxFileName.Text.Any(s => invalidChars.Contains(s)))
            {
                var messageBox = new MessageBoxForm("The filename for the zip file contains invalid characters.", @"Invalid Zip file name", MessageBoxButtons.OK, SystemIcons.Error);
                messageBox.ShowDialog();
                return;
            }

            if (".zip".Equals(Path.GetExtension(textBoxFileName.Text)))
            {
                textBoxFileName.Text = Path.GetFileNameWithoutExtension(textBoxFileName.Text);
            }

            string outPath = Path.Combine(textBoxSaveFolder.Text, textBoxFileName.Text + ".zip");

            if (!Directory.Exists(textBoxSaveFolder.Text))
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Question;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("The destination folder does not exist, would you like to create it ?", @"Folder not found", true, false);
                messageBox.ShowDialog();
                if (messageBox.DialogResult == DialogResult.No)
                {
                    return;
                }

                Directory.CreateDirectory(textBoxSaveFolder.Text);
            }
            else if (File.Exists(outPath))
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Question;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("The file name you have enter already exists, do you wish to overwrite it ?", @"File exists", true, false);
                messageBox.ShowDialog();
                if (messageBox.DialogResult == DialogResult.OK)
                {
                    File.Delete(outPath);
                }
                else
                {
                    return;
                }
            }

            buttonStartCancel.Text = "Stop";
            buttonClose.Enabled    = false;
            _bw.RunWorkerAsync();
        }
示例#45
0
		private void AddGradientToLibrary(ColorGradient cg, bool edit = true)
		{
			Common.Controls.TextDialog dialog = new Common.Controls.TextDialog("Gradient name?");

			while (dialog.ShowDialog() == DialogResult.OK)
			{
				if (dialog.Response == string.Empty)
				{
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
					var messageBox = new MessageBoxForm("Please enter a name.", "Warning", false, false);
					messageBox.ShowDialog();
					continue;
				}

				if (_colorGradientLibrary.Contains(dialog.Response))
				{
					//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
					MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
					var messageBox = new MessageBoxForm("There is already a gradient with that name. Do you want to overwrite it?", "Overwrite gradient?", true, true);
					messageBox.ShowDialog();
					if (messageBox.DialogResult == DialogResult.OK)
					{
						_colorGradientLibrary.AddColorGradient(dialog.Response, cg);
						if (edit)
						{
							_colorGradientLibrary.EditLibraryItem(dialog.Response);	
						}
						break;
					}

					if (messageBox.DialogResult == DialogResult.Cancel)
					{
						break;
					}
				}
				else
				{
					_colorGradientLibrary.AddColorGradient(dialog.Response, cg);
					if (edit)
					{
						_colorGradientLibrary.EditLibraryItem(dialog.Response);	
					}
					break;
				}
			}
		}
示例#46
0
        private void UnivDgvnCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            var cellValue     = e.FormattedValue;
            var cellValueText = cellValue as string;
            var cellValueInt  = 0;

            if (cellValueText != null)
            {
                if (!int.TryParse(cellValueText, out cellValueInt))
                {
                    cellValueInt = 0;
                }
            }

            switch (e.ColumnIndex)
            {
            case UNIVERSE_COLUMN:
                if (cellValueText == null)
                {
                    e.Cancel = true;
                }
                else if (cellValueInt < 1 || 64000 < cellValueInt)
                {
                    e.Cancel = true;
                }

                if (e.Cancel)
                {
                    this.univDGVN.Rows[e.RowIndex].ErrorText = "Universe must be between 1 and 64000 inclusive";
                }


                break;

            case START_COLUMN:
                if (cellValueText == null)
                {
                    e.Cancel = true;
                }
                else if (cellValueInt < 1 || 99999 < cellValueInt)
                {
                    e.Cancel = true;
                }

                if (e.Cancel)
                {
                    this.univDGVN.Rows[e.RowIndex].ErrorText = "Start must be between 1 and 99999 inclusive";
                }

                break;

            case SIZE_COLUMN:
                if (cellValueText == null)
                {
                    e.Cancel = true;
                }
                else if (cellValueInt < 1 || 512 < cellValueInt)
                {
                    e.Cancel = true;
                }

                if (e.Cancel)
                {
                    this.univDGVN.Rows[e.RowIndex].ErrorText = "Size must be between 1 and 512 inclusive";
                }

                break;
            }

            if (e.Cancel)
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Exclamation;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm(
                    this.univDGVN.Rows[e.RowIndex].ErrorText,
                    "Cell Validation", false, false);
                messageBox.ShowDialog();
            }
        }
示例#47
0
		private void toolStripButtonImportColors_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog
			{
				DefaultExt = ".vfc",
				Filter = @"Vixen 3 Favorite Colors (*.vfc)|*.vfc|All Files (*.*)|*.*",
				FilterIndex = 0
			};

			if (_lastFolder != string.Empty) openFileDialog.InitialDirectory = _lastFolder;
			if (openFileDialog.ShowDialog() != DialogResult.OK) return;
			_lastFolder = Path.GetDirectoryName(openFileDialog.FileName);
			List<Color> colors = new List<Color>();

			try
			{
				using (FileStream reader = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
				{
					DataContractSerializer ser = new DataContractSerializer(typeof(List<Color>));
					colors = (List<Color>)ser.ReadObject(reader);
				}

				foreach (Color color in colors)
				{
					_colors.Add(color);
				}
			}
			catch (Exception ex)
			{
				Logging.Error("Invalid file while importing Favorite Colors: " + openFileDialog.FileName + " " + ex.InnerException);
				//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
				MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
				var messageBox = new MessageBoxForm("Sorry, we didn't reconize the data in that file as valid Favorite Color data.", "Invalid file", false, false);
				messageBox.ShowDialog();
			}
			PopulateColors();
			Save_ColorPaletteFile();
		}
示例#48
0
        private void SetupForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
            {
                // only test for range if more than 0 channels, otherwise wait for runtime
                if (pluginChannelCount > 0)
                {
                    var valid         = true;
                    var errorList     = new StringBuilder();
                    var totalChannels = 0;
                    for (int x = 0; x < UniverseCount; x++)
                    {
                        bool active   = false;
                        int  start    = 0;
                        int  size     = 0;
                        int  universe = 0;
                        UniverseGet(x, ref active, ref universe, ref start, ref size);
                        // now test for valid channel start
                        if (start > pluginChannelCount)
                        {
                            if (!valid)
                            {
                                errorList.Append("\n\n");
                            }

                            errorList.Append($"Universe {universe} start channel exceeds controller output count of {pluginChannelCount}");
                            valid = false;
                        }

                        // now test for valid channel size
                        if (start + size - 1 > pluginChannelCount)
                        {
                            if (!valid)
                            {
                                errorList.Append("\n\n");
                            }

                            errorList.Append($"Universe {universe} {start} + {size} exceeds controller output count of {pluginChannelCount}");
                            valid = false;
                        }

                        totalChannels += size;
                    }

                    if (totalChannels != pluginChannelCount)
                    {
                        if (!valid)
                        {
                            errorList.Append("\n\n");
                        }

                        errorList.Append($"Total universe channel count of {totalChannels} does not match the controller output count of {pluginChannelCount}.\n\n" +
                                         "Check your universe setup or adjust the amount of output channels to match.");
                        valid = false;
                    }

                    if (!valid)
                    {
                        var messageBox = new MessageBoxForm($"{errorList}", "Universe Channel / Output count conflict.", MessageBoxButtons.OKCancel, SystemIcons.Warning);
                        messageBox.ShowDialog();
                        if (messageBox.DialogResult == DialogResult.Cancel)
                        {
                            e.Cancel = true;
                            return;
                        }
                    }
                }

                bool overlapWarning = false;

                //Validate that a given Vixen input channel doesn't go to multiple sACN output channels
                //Technically nothing bad will happen, but the user should be aware as it is most likely an accident.
                foreach (DataGridViewRow r1 in univDGVN.Rows)
                {
                    foreach (DataGridViewRow r2 in univDGVN.Rows)
                    {
                        if (r1 != r2)
                        {
                            int r1LowerBound = ((string)r1.Cells[START_COLUMN].Value).TryParseInt32(0);
                            int r1UpperBound = (((string)r1.Cells[START_COLUMN].Value).TryParseInt32(0) + ((string)r1.Cells[SIZE_COLUMN].Value).TryParseInt32(0) - 1);
                            int r2LowerBound = ((string)r2.Cells[START_COLUMN].Value).TryParseInt32(0);
                            int r2UpperBound = (((string)r2.Cells[START_COLUMN].Value).TryParseInt32(0) + ((string)r2.Cells[SIZE_COLUMN].Value).TryParseInt32(0) - 1);

                            if ((r1LowerBound >= r2LowerBound && r1LowerBound <= r2UpperBound) || (r1UpperBound >= r2LowerBound && r1UpperBound <= r2UpperBound))
                            {
                                var messageBox = new MessageBoxForm("The start values seem to be setup in an unusual way. You are sending identical lighting values to multiple sACN outputs. The start value column refers to where a given universe starts reading values in from the list of output channel data from Vixen. For example, setting Universe 1's start value to 5 will map Channel 1 in Universe 1 to output channel #5 in the Vixen controller setup. Would you like to review your settings?", "Warning", MessageBoxButtons.OKCancel, SystemIcons.Warning);
                                messageBox.ShowDialog();
                                if (messageBox.DialogResult == DialogResult.OK)
                                {
                                    e.Cancel = false;
                                    return;
                                }
                                overlapWarning = true;
                                break;
                            }
                        }
                    }
                    if (overlapWarning)
                    {
                        break;
                    }
                }

                var destination = new Tuple <string, string>(null, null);
                destination = GetDestination();                 //Item1 Unicast, Item2 Multicast

                //prevent duplicates in this plugin instance
                foreach (DataGridViewRow r1 in univDGVN.Rows)
                {
                    int univ = ((string)r1.Cells[UNIVERSE_COLUMN].Value).TryParseInt32(1);
                    foreach (DataGridViewRow r2 in univDGVN.Rows)
                    {
                        if (r1 != r2 && univ == ((string)r2.Cells[UNIVERSE_COLUMN].Value).TryParseInt32(1))
                        {
                            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                            MessageBoxForm.msgIcon = SystemIcons.Error;                             //this is used if you want to add a system icon to the message form.
                            var messageBox = new MessageBoxForm("Universe numbers must be unique.", "Error", false, false);
                            messageBox.ShowDialog();
                            e.Cancel = true;
                            return;
                        }
                    }
                }

                //Validate that the same universe isn't being broadcasted to the same devices from multiple
                //instances of the plugin
                foreach (E131OutputPlugin p in E131OutputPlugin.PluginInstances)
                {
                    if (p.isSetupOpen)                     //don't validate against this instance of the plugin
                    {
                        continue;
                    }

                    //Conditions which we need to validate for overlap
                    if (
                        !(((p.ModuleData as E131ModuleDataModel).Unicast != null && destination.Item1 != null && (p.ModuleData as E131ModuleDataModel).Unicast != destination.Item1) ||                      //unicasting to different IPs
                          ((p.ModuleData as E131ModuleDataModel).Multicast != null && destination.Item2 != null && (p.ModuleData as E131ModuleDataModel).Multicast != destination.Item2)))                            //Multicasting to different networks
                    {
                        int[] usedUniverses = (p.ModuleData as E131ModuleDataModel).Universes.Select(x => x.Universe).ToArray();

                        for (int i = 0; i < UniverseCount; i++)
                        {
                            bool active   = true;
                            int  universe = 0;
                            int  start    = 0;
                            int  size     = 0;

                            if (UniverseGet(
                                    i, ref active, ref universe, ref start, ref size))
                            {
                                if (usedUniverses.Contains(universe))
                                {
                                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                                    MessageBoxForm.msgIcon = SystemIcons.Exclamation;                                     //this is used if you want to add a system icon to the message form.
                                    var messageBox = new MessageBoxForm(string.Format("Universe {0} already exists on another controller transmitting to the same device or network. Please configure a different universe to prevent hardware errors.", universe), "Existing Universe", false, false);
                                    messageBox.ShowDialog();
                                    e.Cancel = true;
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
示例#49
0
		private void toolStripButtonImportGradients_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog
			{
				DefaultExt = ".vgl",
				Filter = @"Vixen 3 Color Gradient Library (*.vgl)|*.vgl|All Files (*.*)|*.*",
				FilterIndex = 0
			};

			if (_lastFolder != string.Empty) openFileDialog.InitialDirectory = _lastFolder;
			if (openFileDialog.ShowDialog() != DialogResult.OK) return;
			_lastFolder = Path.GetDirectoryName(openFileDialog.FileName);
			Dictionary<string, ColorGradient> gradients = new Dictionary<string, ColorGradient>();

			try
			{
				using (FileStream reader = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
				{
					DataContractSerializer ser = new DataContractSerializer(typeof(Dictionary<string, ColorGradient>));
					gradients = (Dictionary<string, ColorGradient>)ser.ReadObject(reader);
				}

				foreach (KeyValuePair<string, ColorGradient> gradient in gradients)
				{
					//This was just easier than prompting for a rename
					//and rechecking, and repormpting... and on and on and on...
					string gradientName = gradient.Key;
					int i = 2;
					while (_colorGradientLibrary.Contains(gradientName))
					{
						gradientName = gradient.Key + " " + i;
						i++;
					}

					_colorGradientLibrary.AddColorGradient(gradientName, gradient.Value);
				}
			}
			catch (Exception ex)
			{
				Logging.Error("Invalid file while importing Color Gradient Library: " + openFileDialog.FileName + " " + ex.InnerException);
				//messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
				MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
				var messageBox = new MessageBoxForm("Sorry, we didn't reconize the data in that file as valid Color Gradient Library data.", "Invalid file", false, false);
				messageBox.ShowDialog();
			}
		}
示例#50
0
        public bool Perform(IEnumerable <ElementNode> selectedNodes)
        {
            DialogResult dr = ShowDialog();

            if (dr != DialogResult.OK)
            {
                return(false);
            }

            ExistingBehaviour existingBehaviour = ExistingBehaviour.DoNothing;

            if (radioButtonExistingDoNothing.Checked)
            {
                existingBehaviour = ExistingBehaviour.DoNothing;
            }
            else if (radioButtonExistingUpdate.Checked)
            {
                existingBehaviour = ExistingBehaviour.UpdateExisting;
            }
            else if (radioButtonExistingAddNew.Checked)
            {
                existingBehaviour = ExistingBehaviour.AddNew;
            }
            else
            {
                Logging.Warn("no radio button selected");
            }


            IEnumerable <ElementNode> leafElements = selectedNodes.SelectMany(x => x.GetLeafEnumerator()).Distinct();
            int modulesCreated    = 0;
            int modulesConfigured = 0;
            int modulesSkipped    = 0;

            foreach (ElementNode leafNode in leafElements)
            {
                // get the leaf 'things' to deal with -- ie. either existing dimming curves on a filter branch, or data component outputs
                // (if we're adding new ones, ignore any existing dimming curves: always go to the outputs and we'll add new ones)
                IDataFlowComponent elementComponent = VixenSystem.DataFlow.GetComponent(leafNode.Element.Id);
                IEnumerable <IDataFlowComponentReference> references = _FindLeafOutputsOrDimmingCurveFilters(elementComponent, existingBehaviour == ExistingBehaviour.AddNew);

                foreach (IDataFlowComponentReference reference in references)
                {
                    int outputIndex = reference.OutputIndex;

                    if (reference.Component is DimmingCurveModule)
                    {
                        switch (existingBehaviour)
                        {
                        case ExistingBehaviour.DoNothing:
                            modulesSkipped++;
                            continue;

                        case ExistingBehaviour.UpdateExisting:
                            (reference.Component as DimmingCurveModule).DimmingCurve = _curve;
                            modulesConfigured++;
                            continue;

                        case ExistingBehaviour.AddNew:
                            outputIndex = 0;
                            break;
                        }
                    }

                    // assuming we're making a new one and going from there
                    DimmingCurveModule dimmingCurve = ApplicationServices.Get <IOutputFilterModuleInstance>(DimmingCurveDescriptor.ModuleId) as DimmingCurveModule;
                    VixenSystem.DataFlow.SetComponentSource(dimmingCurve, reference.Component, outputIndex);
                    VixenSystem.Filters.AddFilter(dimmingCurve);

                    dimmingCurve.DimmingCurve = _curve;

                    modulesCreated++;
                    modulesConfigured++;
                }
            }
            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
            var messageBox = new MessageBoxForm(modulesCreated + " Dimming Curves created, " + modulesConfigured + " configured, and " + modulesSkipped + " skipped.", "", false, false);

            messageBox.ShowDialog();

            return(true);
        }
示例#51
0
        private void checkBoxAlignToBeatMarks_CheckStateChanged(object sender, EventArgs e)
        {
            txtDurationBetween.Enabled = (checkBoxAlignToBeatMarks.Checked ? false : true);
            listBoxMarkCollections.Visible = !listBoxMarkCollections.Visible;
            listBoxMarkCollections.Enabled = checkBoxFillDuration.AutoCheck = checkBoxSkipEOBeat.AutoCheck = checkBoxAlignToBeatMarks.Checked;
            checkBoxSkipEOBeat.ForeColor = checkBoxAlignToBeatMarks.Checked ? ThemeColorTable.ForeColor : ThemeColorTable.ForeColorDisabled;
            checkBoxFillDuration.ForeColor = checkBoxAlignToBeatMarks.Checked ? ThemeColorTable.ForeColor : ThemeColorTable.ForeColorDisabled;
            if (checkBoxAlignToBeatMarks.Checked)
            {
                CalculatePossibleEffectsByBeatMarks();
            }
            else
            {
                CalculatePossibleEffects();
            }

            if (checkBoxAlignToBeatMarks.Checked)
            {
                var names = new HashSet<String>();
                foreach (MarkCollection mc in MarkCollections)
                {
                    if (!names.Add(mc.Name))
                    {
                        //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                        MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
                        var messageBox = new MessageBoxForm("You have Beat Mark collections with duplicate names.\nBecause of this, your results may not be as expected.", "Duplicate Names", false, false);
                        messageBox.ShowDialog();
                        break;
                    }
                }

            }
        }
示例#52
0
        private void ShowColorPicker()
        {
            //Logging.Debug("Enter color picker");
            var value = GetColorGradientValue();

            if (value == null)
            {
                return;
            }
            var selectedIndex = SelectedIndex;

            if (selectedIndex < 0)
            {
                return;
            }
            var           handle            = _points[selectedIndex];
            var           colorPointIndexes = (List <int>)handle.Tag;
            ColorGradient holdValue;

            if (IsDiscrete)
            {
                holdValue = new ColorGradient(value);
                List <Color>      selectedColors = new List <Color>();
                List <ColorPoint> colorPoints    = new List <ColorPoint>();
                foreach (int index in colorPointIndexes)
                {
                    ColorPoint pt = holdValue.Colors[index];
                    if (pt == null)
                    {
                        continue;
                    }
                    colorPoints.Add(pt);
                    selectedColors.Add(pt.Color.ToRGB().ToArgb());
                }

                using (DiscreteColorPicker picker = new DiscreteColorPicker())
                {
                    picker.ValidColors    = ValidColors;
                    picker.SelectedColors = selectedColors;
                    if (picker.ShowDialog() == DialogResult.OK)
                    {
                        if (!picker.SelectedColors.Any())
                        {
                            DeletePoint();
                        }
                        else
                        {
                            double position = colorPoints.First().Position;
                            foreach (var colorPoint in colorPoints)
                            {
                                holdValue.Colors.Remove(colorPoint);
                            }

                            foreach (Color selectedColor in picker.SelectedColors)
                            {
                                ColorPoint newPoint = new ColorPoint(selectedColor, position);
                                holdValue.Colors.Add(newPoint);
                            }
                            SetColorGradientValue(holdValue);
                        }
                    }
                }
            }
            else
            {
                if (colorPointIndexes.Count > 1)
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Error;                     //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("Non-discrete color gradient, >1 selected point. oops! please report it.", "Delete library gradient?", false, false);
                    messageBox.ShowDialog();
                }

                holdValue = new ColorGradient(value);
                ColorPoint pt = holdValue.Colors[colorPointIndexes.FirstOrDefault()];
                if (pt == null)
                {
                    return;
                }
                using (ColorPicker frm = new ColorPicker(_mode, _fader))
                {
                    frm.LockValue_V = false;
                    frm.Color       = pt.Color;
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        pt.Color = frm.Color;
                        _mode    = frm.SecondaryMode;
                        _fader   = frm.PrimaryFader;
                        SetColorGradientValue(holdValue);
                    }
                }
            }
            //Logging.Debug("Exit normally color picker");
        }
示例#53
0
        private void btnRestore_Click(object sender, EventArgs e)
        {
            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
            MessageBoxForm.msgIcon = SystemIcons.Hand; //this is used if you want to add a system icon to the message form.
            var messageBox = new MessageBoxForm("Are you sure you want to restore this version?  \n\rIf you have not saved the current file, all changes will be lost!", "Restore File", true, false);
            messageBox.ShowDialog();
            if (messageBox.DialogResult == DialogResult.OK)
            {

                var commit = _repo.Get<Commit>(this.txtChangeHash.Text);
                var tree = commit.Tree;
                foreach (Tree subtree in tree.Trees)
                {
                    var leaf = subtree.Leaves.Where(l => l.Path.Equals(treeViewFiles.SelectedNode.Tag as string)).FirstOrDefault();
                    if (leaf != null)
                    {

                        var rawData = leaf.RawData;
                        var fileName = System.IO.Path.Combine(_repo.WorkingDirectory, treeViewFiles.SelectedNode.Tag as string).Replace('/', '\\');
                        var b = fileName;
                        var c = b;
                        var fi = new FileInfo(fileName);
                        SaveFileDialog dlg = new SaveFileDialog();
                        dlg.FileName = fi.Name;
                        dlg.AddExtension = true;
                        dlg.DefaultExt = fi.Extension;
                        dlg.InitialDirectory = fi.DirectoryName;
                        dlg.Filter = "All files (*.*)|*.*";

                        var ddd = dlg.ShowDialog();
                        if (ddd == System.Windows.Forms.DialogResult.OK)
                        {
                            lock (Module.fileLockObject)
                            {
                                Module.restoringFile = true;
                                File.WriteAllBytes(fileName, rawData);
                            }
                        }
                    }
                }
            }
        }
        //Vixen 3 Beat Mark Collection Import routine 2-7-2014 JMB
        public static void ImportVixen3Beats(ObservableCollection <IMarkCollection> collections)
        {
            var openFileDialog = new OpenFileDialog();

            openFileDialog.DefaultExt       = ".v3m";
            openFileDialog.Filter           = @"Vixen 3 Mark Collection (*.v3m)|*.v3m|All Files (*.*)|*.*";
            openFileDialog.FilterIndex      = 0;
            openFileDialog.InitialDirectory = _lastFolder;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                _lastFolder = Path.GetDirectoryName(openFileDialog.FileName);
                var xdoc = XDocument.Load(openFileDialog.FileName);
                if (xdoc.Root != null)
                {
                    Type type;
                    bool migrate = false;
                    if (xdoc.Root.Name.NamespaceName.Equals("http://schemas.datacontract.org/2004/07/" + typeof(IMarkCollection)))
                    {
                        type = typeof(List <IMarkCollection>);
                    }
                    else if (xdoc.Root.Name.NamespaceName.Equals("http://schemas.datacontract.org/2004/07/VixenModules.Sequence.Timed"))
                    {
                        type    = typeof(List <Sequence.Timed.MarkCollection>);
                        migrate = true;
                    }
                    else
                    {
                        Logging.Error($"Could not determine type of Vixen Mark import file. Type {xdoc.Root.Name.LocalName} Namspace {xdoc.Root.Name.NamespaceName}");
                        string msg        = "There was an error importing the Vixen Marks.";
                        var    messageBox = new MessageBoxForm(msg, "Vixen Marks Import Error", MessageBoxButtons.OK, SystemIcons.Error);
                        messageBox.ShowDialog();
                        return;
                    }

                    using (FileStream reader = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
                    {
                        try
                        {
                            DataContractSerializer ser = CreateSerializer(type, migrate);
                            var markCollections        = ser.ReadObject(reader);
                            if (!migrate)
                            {
                                var imc = markCollections as List <IMarkCollection>;
                                if (imc != null && collections.Any(x => x.IsDefault))
                                {
                                    //make sure any imported are not default becasue we have a set and there will
                                    //be a default there.
                                    imc.ForEach(x => x.IsDefault = false);
                                }

                                collections.AddRange(imc);
                            }
                            else
                            {
                                MigrateMarkCollections(collections, (List <Sequence.Timed.MarkCollection>)markCollections);
                            }

                            if (!collections.Any(x => x.IsDefault))
                            {
                                SetDefaultCollection(collections);
                            }
                        }
                        catch (Exception e)
                        {
                            Logging.Error(e, "Unable to import V3 Marks");
                        }
                    }
                }
            }
        }
示例#55
0
        private bool SaveDisplayedColorSet()
        {
            string name = textBoxName.Text;
            ColorSet newColorSet = new ColorSet();

            if (name.Length <= 0) {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("You must enter a name for the Color Set.", "Name Requred", false, false);
                messageBox.ShowDialog();
                return false;
            }

            foreach (var control in tableLayoutPanelColors.Controls) {
                ColorPanel cp = (ColorPanel)control;
                newColorSet.Add(cp.Color);
            }

            _data.SetColorSet(textBoxName.Text, newColorSet);

            return true;
        }
        public static void ImportPapagayoTracks(ICollection <IMarkCollection> markCollection)
        {
            FileDialog openDialog = new OpenFileDialog();

            openDialog.Filter           = @"Papagayo files (*.pgo)|*.pgo|All files (*.*)|*.*";
            openDialog.FilterIndex      = 1;
            openDialog.InitialDirectory = _lastFolder;
            if (openDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            PapagayoDoc papagayoFile = new PapagayoDoc();
            string      fileName     = openDialog.FileName;

            _lastFolder = Path.GetDirectoryName(openDialog.FileName);
            papagayoFile.Load(fileName);
            var fileWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            int rownum = 0;

            foreach (string voice in papagayoFile.VoiceList)
            {
                var phraseCollection = new MarkCollection();
                phraseCollection.Name            = $"{fileWithoutExtension} {voice} Phrases";
                phraseCollection.ShowMarkBar     = true;
                phraseCollection.Decorator.Color = Color.FromArgb(205, 242, 162);
                var wordCollection = new MarkCollection();
                wordCollection.Name            = $"{fileWithoutExtension} {voice} Words";
                wordCollection.ShowMarkBar     = true;
                wordCollection.Decorator.Color = Color.FromArgb(242, 205, 162);
                var phonemeCollection = new MarkCollection();
                phonemeCollection.Name            = $"{fileWithoutExtension} {voice} Phonemes";
                phonemeCollection.ShowMarkBar     = true;
                phonemeCollection.Decorator.Color = Color.FromArgb(235, 185, 210);
                var phrases = papagayoFile.PhraseList(voice);
                foreach (var phrase in phrases)
                {
                    var mark = new Mark(TimeSpan.FromMilliseconds(phrase.StartMS));
                    mark.Duration = TimeSpan.FromMilliseconds(phrase.DurationMS);
                    mark.Text     = phrase.Text;
                    phraseCollection.AddMark(mark);
                    foreach (var word in phrase.Words)
                    {
                        mark          = new Mark(TimeSpan.FromMilliseconds(word.StartMS));
                        mark.Duration = TimeSpan.FromMilliseconds(word.EndMS) - mark.StartTime;
                        mark.Text     = word.Text;
                        wordCollection.AddMark(mark);
                        foreach (var phoneme in word.Phonemes)
                        {
                            mark          = new Mark(TimeSpan.FromMilliseconds(phoneme.StartMS));
                            mark.Duration = TimeSpan.FromMilliseconds(phoneme.EndMS) - mark.StartTime;
                            mark.Text     = phoneme.TypeName;
                            phonemeCollection.AddMark(mark);
                        }
                    }
                }

                phraseCollection.CollectionType = MarkCollectionType.Phrase;
                markCollection.Add(phraseCollection);
                wordCollection.CollectionType         = MarkCollectionType.Word;
                wordCollection.LinkedMarkCollectionId = phraseCollection.Id;
                markCollection.Add(wordCollection);
                phonemeCollection.CollectionType         = MarkCollectionType.Phoneme;
                phonemeCollection.LinkedMarkCollectionId = wordCollection.Id;
                markCollection.Add(phonemeCollection);


                //phonemeCollection = new MarkCollection();
                //phonemeCollection.Name = $"{fileWithoutExtension} {voice} Phonemes Coalesced";
                //phonemeCollection.ShowMarkBar = true;
                //phonemeCollection.Decorator.Color = Color.FromArgb(245, 75, 210); ;
                //foreach (var phoneme in papagayoFile.PhonemeList(voice))
                //{
                //	var mark = new Mark(TimeSpan.FromMilliseconds(phoneme.StartMS));
                //	mark.Duration = TimeSpan.FromMilliseconds(phoneme.EndMS) - mark.StartTime;
                //	mark.Text = phoneme.TypeName;
                //	phonemeCollection.AddMark(mark);
                //}
                //phonemeCollection.CollectionType = MarkCollectionType.Phoneme;
                //markCollection.Add(phonemeCollection);
                rownum++;
            }

            string displayStr = rownum + " Voices imported to clipboard as Mark Collctions\n\n";
            int    j          = 1;

            foreach (string voiceStr in papagayoFile.VoiceList)
            {
                displayStr += "Row #" + j + " - " + voiceStr + "\n";
                j++;
            }
            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
            MessageBoxForm.msgIcon = SystemIcons.Information;             //this is used if you want to add a system icon to the message form.
            var messageBox = new MessageBoxForm(displayStr, @"Papagayo Import", false, false);

            messageBox.ShowDialog();
        }
示例#57
0
 private void buttonRemoveColorSet_Click(object sender, EventArgs e)
 {
     if (listViewColorSets.SelectedItems.Count > 0) {
         string item = listViewColorSets.SelectedItems[0].Text;
         if (!_data.RemoveColorSet(item)) {
             //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
             MessageBoxForm.msgIcon = SystemIcons.Error; //this is used if you want to add a system icon to the message form.
             var messageBox = new MessageBoxForm("Error removing Color Set!", "Error", false, false);
             messageBox.ShowDialog();
         }
     }
     UpdateColorSetsList();
     UpdateGroupBoxWithColorSet(null, null);
 }
示例#58
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            XMLProfileSettings profile         = new XMLProfileSettings();
            List <string>      checkName       = new List <string>();
            List <string>      checkDataFolder = new List <string>();
            List <string>      duplicateItems  = new List <string>();
            List <string>      checkDataPath   = new List <string>();
            bool duplicateName       = false;
            bool duplicateDataFolder = false;
            bool invalidDataPath     = false;

            //Check for null values, duplicate profile name or datapath and non rooted datapath
            foreach (ProfileItem item in comboBoxProfiles.Items)
            {
                if (item.Name == null || item.DataFolder == null)
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Warning;                     //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("One or more of your profile entries has a blank name or data folder. You must correct this before continuing.",
                                                        @"Warning - Blank Entries", false, false);
                    messageBox.ShowDialog();
                }

                if (checkName.Contains(item.Name))
                {
                    duplicateName = true;
                    duplicateItems.Add(item.Name + ":\t " + item.DataFolder);
                }
                checkName.Add(item.Name);

                if (checkDataFolder.Contains(item.DataFolder))
                {
                    duplicateDataFolder = true;
                    duplicateItems.Add(item.Name + ":\t " + item.DataFolder);
                }

                checkDataFolder.Add(item.DataFolder);

                if (!Path.IsPathRooted(item.DataFolder) || !item.DataFolder.Contains(@"\"))
                {
                    invalidDataPath = true;
                    checkDataPath.Add(item.Name + ":\t " + item.DataFolder);
                }
            }

            if (duplicateName || duplicateDataFolder)
            {
                //Not pretty here, but works well on the dialog
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Warning;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("A duplicate profile name, or data path exists." + Environment.NewLine + Environment.NewLine +
                                                    @"The duplicate items found were:" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, duplicateItems) + Environment.NewLine + Environment.NewLine +
                                                    @"Click OK to accept and contine, or Cancel to go back and edit.",
                                                    @"Warning - Duplicate Entries", false, true);
                messageBox.ShowDialog();

                if (messageBox.DialogResult != DialogResult.OK)
                {
                    DialogResult = DialogResult.None;
                    return;
                }
            }

            if (invalidDataPath)
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Warning;                 //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("An invalid profile data folder exists." + Environment.NewLine + Environment.NewLine +
                                                    @"The items with invalid paths were:" + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, checkDataPath) + Environment.NewLine + Environment.NewLine +
                                                    @"Click OK to accept and contine, or Cancel to go back and edit.",
                                                    @"Warning - Invalid Data Path", false, true);
                messageBox.ShowDialog();

                if (messageBox.DialogResult != DialogResult.OK)
                {
                    DialogResult = DialogResult.None;
                    return;
                }
            }

            SaveCurrentItem();
            profile.PutSetting(XMLProfileSettings.SettingType.Profiles, "ProfileCount", comboBoxProfiles.Items.Count);
            for (int i = 0; i < comboBoxProfiles.Items.Count; i++)
            {
                ProfileItem item = comboBoxProfiles.Items[i] as ProfileItem;
                profile.PutSetting(XMLProfileSettings.SettingType.Profiles, "Profile" + i + "/Name", item.Name);
                profile.PutSetting(XMLProfileSettings.SettingType.Profiles, "Profile" + i + "/DataFolder", item.DataFolder);
                if (!Directory.Exists(item.DataFolder))
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Exclamation;                     //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("The data directory '" + item.DataFolder + "' for profile '" + item.Name + "' does not exist.  Would you like to create it?",
                                                        Application.ProductName, true, false);
                    messageBox.ShowDialog();
                    if (messageBox.DialogResult == DialogResult.OK)
                    {
                        try
                        {
                            Directory.CreateDirectory(item.DataFolder);
                        }
                        catch (Exception)
                        {
                            //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                            MessageBoxForm.msgIcon = SystemIcons.Error;                             //this is used if you want to add a system icon to the message form.
                            messageBox             = new MessageBoxForm("Could not create new profile directory: " + item.DataFolder + Environment.NewLine + Environment.NewLine +
                                                                        "Click OK to ignore and continue, or Cancel to go back and edit.",
                                                                        "Error", false, true);
                            messageBox.ShowDialog();
                            if (messageBox.DialogResult == DialogResult.Cancel)
                            {
                                DialogResult = DialogResult.None;
                                return;
                            }
                        }
                    }
                }
            }

            profile.PutSetting(XMLProfileSettings.SettingType.Profiles, "LoadAction",
                               radioButtonAskMe.Checked ? "Ask" : "LoadSelected");

            if (comboBoxLoadThisProfile.SelectedIndex >= 0)
            {
                profile.PutSetting(XMLProfileSettings.SettingType.Profiles, "ProfileToLoad", comboBoxLoadThisProfile.SelectedIndex);
            }

            DialogResult = DialogResult.OK;
            Close();
        }
示例#59
0
        public bool Perform(IEnumerable <IElementNode> selectedNodes)
        {
            if (!SilentMode)
            {
                DialogResult dr = ShowDialog();
                if (dr != DialogResult.OK)
                {
                    return(false);
                }
            }

            // note: the color property can only be applied to leaf nodes.

            // pull out the new data settings from the form elements
            ElementColorType colorType;
            string           colorSetName = "";

            System.Drawing.Color singleColor = System.Drawing.Color.Black;

            if (radioButtonOptionSingle.Checked)
            {
                colorType    = ElementColorType.SingleColor;
                singleColor  = colorPanelSingleColor.Color;
                colorSetName = null;
            }
            else if (radioButtonOptionMultiple.Checked)
            {
                colorType    = ElementColorType.MultipleDiscreteColors;
                colorSetName = comboBoxColorSet.SelectedItem.ToString();
                singleColor  = System.Drawing.Color.Empty;
            }
            else if (radioButtonOptionFullColor.Checked)
            {
                colorType    = ElementColorType.FullColor;
                singleColor  = System.Drawing.Color.Empty;
                colorSetName = null;
            }
            else
            {
                Logging.Warn("Unexpected radio option selected");
                colorType    = ElementColorType.SingleColor;
                singleColor  = colorPanelSingleColor.Color;
                colorSetName = null;
            }


            // PROPERTY SETUP
            // go through all elements, making a color property for each one.
            // (If any has one already, check with the user as to what they want to do.)
            IEnumerable <IElementNode> leafElements    = selectedNodes.SelectMany(x => x.GetLeafEnumerator()).Distinct();
            List <IElementNode>        leafElementList = leafElements.ToList();

            bool askedUserAboutExistingProperties = false;
            bool overrideExistingProperties       = false;

            int colorPropertiesAdded      = 0;
            int colorPropertiesConfigured = 0;
            int colorPropertiesSkipped    = 0;

            MessageBoxForm messageBox;

            foreach (IElementNode leafElement in leafElementList)
            {
                bool        skip             = false;
                ColorModule existingProperty = null;

                if (leafElement.Properties.Contains(ColorDescriptor.ModuleId))
                {
                    if (!askedUserAboutExistingProperties)
                    {
                        //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                        MessageBoxForm.msgIcon = SystemIcons.Warning;                         //this is used if you want to add a system icon to the message form.
                        messageBox             = new MessageBoxForm("Some elements already have color properties set up. Should these be overwritten?",
                                                                    "Color Setup", true, false);
                        messageBox.ShowDialog();
                        overrideExistingProperties       = (messageBox.DialogResult == DialogResult.OK);
                        askedUserAboutExistingProperties = true;
                    }

                    skip             = !overrideExistingProperties;
                    existingProperty = leafElement.Properties.Get(ColorDescriptor.ModuleId) as ColorModule;
                }
                else
                {
                    existingProperty = leafElement.Properties.Add(ColorDescriptor.ModuleId) as ColorModule;
                    colorPropertiesAdded++;
                }

                if (!skip)
                {
                    if (existingProperty == null)
                    {
                        Logging.Error("Null color property for element " + leafElement.Name);
                    }
                    else
                    {
                        existingProperty.ColorType    = colorType;
                        existingProperty.SingleColor  = singleColor;
                        existingProperty.ColorSetName = colorSetName;
                        colorPropertiesConfigured++;
                    }
                }
                else
                {
                    colorPropertiesSkipped++;
                }
            }


            // PATCHING
            // go through each element, walking the tree of patches, building up a list.  If any are a 'color
            // breakdown' already, warn/check with the user if it's OK to overwrite them.  Make a new breakdown
            // filter for each 'leaf' of the patching process. If it's fully patched to an output, ignore it.

            List <IDataFlowComponentReference> leafOutputs = new List <IDataFlowComponentReference>();

            foreach (IElementNode leafElement in leafElementList.Where(x => x.Element != null))
            {
                leafOutputs.AddRange(_FindLeafOutputsOrBreakdownFilters(VixenSystem.DataFlow.GetComponent(leafElement.Element.Id)));
            }

            bool askedUserAboutExistingFilters = false;
            bool overrideExistingFilters       = false;
            ColorBreakdownModule breakdown     = null;

            int colorFiltersAdded      = 0;
            int colorFiltersConfigured = 0;
            int colorFiltersSkipped    = 0;

            foreach (IDataFlowComponentReference leaf in leafOutputs)
            {
                bool skip = false;

                if (leaf.Component is ColorBreakdownModule)
                {
                    if (!askedUserAboutExistingFilters)
                    {
                        //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                        MessageBoxForm.msgIcon = SystemIcons.Warning;                         //this is used if you want to add a system icon to the message form.
                        messageBox             = new MessageBoxForm("Some elements are already patched to color filters. Should these be overwritten?",
                                                                    "Color Setup", true, false);
                        messageBox.ShowDialog();
                        overrideExistingFilters       = (messageBox.DialogResult == DialogResult.OK);
                        askedUserAboutExistingFilters = true;
                    }

                    skip      = !overrideExistingFilters;
                    breakdown = leaf.Component as ColorBreakdownModule;
                }
                else if (leaf.Component.OutputDataType == DataFlowType.None)
                {
                    // if it's a dead-end -- ie. most likely a controller output -- skip it
                    skip = true;
                }
                else
                {
                    // doesn't exist? make a new module and assign it
                    breakdown =
                        ApplicationServices.Get <IOutputFilterModuleInstance>(ColorBreakdownDescriptor.ModuleId) as ColorBreakdownModule;
                    VixenSystem.DataFlow.SetComponentSource(breakdown, leaf);
                    VixenSystem.Filters.AddFilter(breakdown);
                    colorFiltersAdded++;
                }

                if (!skip)
                {
                    List <ColorBreakdownItem> newBreakdownItems = new List <ColorBreakdownItem>();
                    bool mixColors = false;
                    ColorBreakdownItem cbi;

                    switch (colorType)
                    {
                    case ElementColorType.FullColor:
                        mixColors = true;

                        foreach (var color in comboBoxColorOrder.SelectedItem.ToString().ToCharArray())
                        {
                            switch (color)
                            {
                            case 'R':
                                cbi       = new ColorBreakdownItem();
                                cbi.Color = System.Drawing.Color.Red;
                                cbi.Name  = Red;
                                newBreakdownItems.Add(cbi);
                                break;

                            case 'G':
                                cbi       = new ColorBreakdownItem();
                                cbi.Color = System.Drawing.Color.Lime;
                                cbi.Name  = Green;
                                newBreakdownItems.Add(cbi);
                                break;

                            case 'B':
                                cbi       = new ColorBreakdownItem();
                                cbi.Color = System.Drawing.Color.Blue;
                                cbi.Name  = Blue;
                                newBreakdownItems.Add(cbi);
                                break;
                            }
                        }
                        break;

                    case ElementColorType.MultipleDiscreteColors:
                        mixColors = false;

                        ColorStaticData csd = ApplicationServices.GetModuleStaticData(ColorDescriptor.ModuleId) as ColorStaticData;

                        if (!csd.ContainsColorSet(colorSetName))
                        {
                            Logging.Error("Color sets doesn't contain " + colorSetName);
                        }
                        else
                        {
                            ColorSet cs = csd.GetColorSet(colorSetName);
                            foreach (var c in cs)
                            {
                                cbi       = new ColorBreakdownItem();
                                cbi.Color = c;
                                // heh heh, this can be.... creative.
                                cbi.Name = c.Name;
                                newBreakdownItems.Add(cbi);
                            }
                        }

                        break;

                    case ElementColorType.SingleColor:
                        mixColors = false;
                        cbi       = new ColorBreakdownItem();
                        cbi.Color = singleColor;
                        newBreakdownItems.Add(cbi);
                        break;
                    }

                    breakdown.MixColors      = mixColors;
                    breakdown.BreakdownItems = newBreakdownItems;

                    colorFiltersConfigured++;
                }
                else
                {
                    colorFiltersSkipped++;
                }
            }

            if (!SilentMode)
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Information;                 //this is used if you want to add a system icon to the message form.
                messageBox             = new MessageBoxForm("Color Properties:  " + colorPropertiesAdded + " added, " +
                                                            colorPropertiesConfigured + " configured, " + colorPropertiesSkipped + " skipped. " +
                                                            "Color Filters:  " + colorFiltersAdded + " added, " + colorFiltersConfigured + " configured, " +
                                                            colorFiltersSkipped + " skipped.",
                                                            "Color Setup", false, false);
                messageBox.ShowDialog();
            }

            return(true);
        }
示例#60
0
        /// <summary>
        /// 进行读卡操作
        /// </summary>
        private void ReadCard()
        {
            //先读取卡内信息
            CardInfoBLL _cardBll = new CardInfoBLL();
            int         status   = -1; //保存读取后返回的一个状态

            Bouwa.ITSP2V31.Model.CardInfo _cardInfo = _cardBll.GetCardInfoByCard(Bouwa.Helper.CurrentUser.Current.PassWordKey, out status);
            try
            {
                //string[] mary1 = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(CurrentUser.Current.PassWordKey, Convert.ToInt32(1)));
                //if (mary1[4] != "0")
                //{
                //    //MessageBoxForm.Show(RFIDClass.ConvertMeassByStatus(Convert.ToInt32(mary1[4])));
                //    throw new Exception(RFIDClass.ConvertMeassByStatus(Convert.ToInt32(mary1[4])));
                //}
                ////string[] mary6 = StringUtil.readBlock(RFIDClass.ReadCardAndReturnStatus(CurrentUser.Current.PassWordKey, Convert.ToInt32(6)));
                ////判断当前读的卡是否能初始化的条件; 1: 卡状态为空卡255 ;2:卡状态为已充值,但最后操作时间为空
                //string cardStatus = mary1[2].ToString();
                //if (cardStatus.Length >= 16)
                //{
                //    cardStatus = HelperClass.getCardStatus(cardStatus.Substring(13, 1));
                //}
                //else
                //{
                //    cardStatus = Bouwa.ITSP2V31.Model.CardTypeInfo.CardTypeInfoDefaultCardStatus.空白卡.ToString("D");
                //}

                //if (cardStatus.Equals(CardTypeInfo.CardTypeInfoDefaultCardStatus.空白卡.ToString("D"))
                //    || (cardStatus.Equals(CardTypeInfo.CardTypeInfoDefaultCardStatus.已充值.ToString("D")) && string.IsNullOrEmpty(HelperClass.DecryptByString(mary1[3])))
                //    ||  _cardInfo ==null
                //    )
                //{
                //    Bouwa.ITSP2V31.WIN.CardType.CardTypeList frmCardType = new Bouwa.ITSP2V31.WIN.CardType.CardTypeList();
                //    MessageBoxForm.Show("停车卡还未初始化,需先初始化停车卡!", MessageBoxButtons.OK);

                //    frmCardType.StartPosition = FormStartPosition.CenterScreen;

                //    frmCardType.ShowDialog(this);
                //    return;
                //}
                //再去读取一次
                if (status == 11 || status == 12)
                {
                    _cardInfo = _cardBll.GetCardInfoByCard(string.Empty, out status);
                }
                if (status != 0)
                {
                    MessageBoxForm.Show(RFIDClass.ConvertMeassByStatus(status), MessageBoxButtons.OK);
                    return;
                }
                else if (_cardInfo == null)
                {
                    MessageBoxForm.Show("此卡为空卡,请先进行初始化!", MessageBoxButtons.OK);
                    return;
                }
                //执行查询
                BindingSource bs           = new BindingSource();
                Hashtable     objHashtable = new Hashtable();
                objHashtable.Add("no", _cardInfo.no);
                objHashtable.Add("cost_type", (int)_cardInfo.cost_type); //扣费类型
                objHashtable.Add("card_id", _cardInfo.card_id);          //卡内编号
                //objHashtable.Add("saas_id", CurrentUser.Current.SAASID);

                IList <Bouwa.ITSP2V31.Model.CardInfo> CardInfo = _objCardInfoBLL.SearchByCondition(objHashtable, null, 1, 1, "[status] DESC", ref _objSystemMessageInfo);

                //说明注册过了
                if (CardInfo != null && CardInfo.Count > 0)
                {
                    Bouwa.ITSP2V31.Win.CardInfo.View frmCardInfoEdit = new Bouwa.ITSP2V31.Win.CardInfo.View();

                    frmCardInfoEdit.Parameter.Add("ActionType", ActionType.View.ToString("D"));
                    frmCardInfoEdit.Parameter.Add("Id", CardInfo[0].id.ToString());
                    frmCardInfoEdit.StartPosition = FormStartPosition.CenterScreen;
                    frmCardInfoEdit.ShowDialog(this);
                }//说明未注册
                else
                {
                    //Bouwa.ITSP2V31.WIN.CardType.CardTypeList frmCardType = new Bouwa.ITSP2V31.WIN.CardType.CardTypeList();
                    //MessageBoxForm.Show("停车卡还未初始化,需先初始化停车卡!", MessageBoxButtons.OK);
                    MessageBoxForm.Show("后台未找到停车卡信息,请联系管理员!", MessageBoxButtons.OK);
                    //frmCardType.StartPosition = FormStartPosition.CenterScreen;
                    //frmCardType.ShowDialog(this);
                    return;
                }
            }
            catch (Exception ex)
            {
                Bouwa.Helper.Class.Log.WriterLine(Bouwa.Helper.Class.ELevel.error, "读卡出现异常", ex.Message);
                MessageBoxForm.Show(_cardBll.ConvertMeassByStatus(status), MessageBoxButtons.OK);
            }
        }