예제 #1
0
        private void BuildNode(ref Match node, StringBuilder sb, bool first)
        {
            if (!(first))
            {
                sb.Append(",");
            }
            SortedDictionary <string, string> propList = new SortedDictionary <string, string>();
            Match prop = MenuItemPropRegex.Match(node.Groups["PropList"].Value);

            while (prop.Success)
            {
                propList[prop.Groups["Name"].Value.ToLower().Replace("-", String.Empty)] = prop.Groups["Value"].Value;
                prop = prop.NextMatch();
            }
            string roles = null;

            propList.TryGetValue("roles", out roles);
            string users = null;

            propList.TryGetValue("users", out users);
            string roleExceptions = null;

            propList.TryGetValue("roleexceptions", out roleExceptions);
            string userExceptions = null;

            propList.TryGetValue("userexceptions", out userExceptions);
            string url    = node.Groups["Url"].Value.Trim();
            string target = null;

            if (url.StartsWith("_blank:"))
            {
                target = "_blank:";
                url    = url.Substring(7);
            }
            url = ResolveUrl(url);
            if (!(String.IsNullOrEmpty(target)))
            {
                url = (target + url);
            }
            bool resourceAuthorized = true;

            if (!(String.IsNullOrEmpty(roles)))
            {
                if (!(ApplicationServices.UserIsAuthorizedToAccessResource(url, roles)))
                {
                    resourceAuthorized = false;
                }
            }
            if (resourceAuthorized && !(String.IsNullOrEmpty(users)))
            {
                if (!((users == "?")) && (Array.IndexOf(users.ToLower().Split(new char[] {
                    ','
                }, StringSplitOptions.RemoveEmptyEntries), Page.User.Identity.Name.ToLower()) == -1))
                {
                    resourceAuthorized = false;
                }
            }
            if (!(resourceAuthorized) && !(String.IsNullOrEmpty(roleExceptions)))
            {
                if (DataControllerBase.UserIsInRole(roleExceptions))
                {
                    resourceAuthorized = true;
                }
            }
            if (!(resourceAuthorized) && !(String.IsNullOrEmpty(userExceptions)))
            {
                if (!((Array.IndexOf(userExceptions.ToLower().Split(new char[] {
                    ','
                }, StringSplitOptions.RemoveEmptyEntries), Page.User.Identity.Name.ToLower()) == -1)))
                {
                    resourceAuthorized = true;
                }
            }
            sb.Append("{");
            if (resourceAuthorized)
            {
                string title = node.Groups["Title"].Value.Trim();
                string depth = node.Groups["Depth"].Value;
                sb.AppendFormat("title:\"{0}\"", BusinessRules.JavaScriptString(title));
                if (!((url == "about:blank")))
                {
                    sb.AppendFormat(",url:\"{0}\"", BusinessRules.JavaScriptString(url));
                }
                if (Page.Request.RawUrl == url)
                {
                    sb.Append(",selected:true");
                }
                string description = null;
                propList.TryGetValue("description", out description);
                if (!(String.IsNullOrEmpty(description)))
                {
                    sb.AppendFormat(",description:\"{0}\"", BusinessRules.JavaScriptString(description));
                }
                node = node.NextMatch();
                if (node.Success)
                {
                    string firstChildDepth = node.Groups["Depth"].Value;
                    if (firstChildDepth.Length > depth.Length)
                    {
                        sb.Append(",children:[");
                        first = true;
                        while (node.Success)
                        {
                            BuildNode(ref node, sb, first);
                            if (first)
                            {
                                first = false;
                            }
                            if (node.Success)
                            {
                                string nextDepth = node.Groups["Depth"].Value;
                                if (firstChildDepth.Length > nextDepth.Length)
                                {
                                    break;
                                }
                            }
                        }
                        sb.Append("]");
                    }
                }
            }
            else
            {
                node = node.NextMatch();
            }
            sb.Append("}");
        }
예제 #2
0
        public TimedSequenceEditorEffectEditor(EffectNode effectNode)
        {
            InitializeComponent();
            ForeColor = ThemeColorTable.ForeColor;
            BackColor = ThemeColorTable.BackgroundColor;
            ThemeUpdateControls.UpdateControls(this);
            _effectNode  = effectNode;
            _effectNodes = null;
            IEnumerable <IEffectEditorControl> controls =
                ApplicationServices.GetEffectEditorControls(_effectNode.Effect.Descriptor.TypeId);

            if (controls == null)
            {
                Label l = new Label();
                l.Text   = "Can't find any effect editors that can edit this effect!";
                l.Anchor = AnchorStyles.None;
                tableLayoutPanelEffectEditors.Controls.Add(l);
                tableLayoutPanelEffectEditors.SetColumnSpan(l, 2);
                return;
            }

            _controls = new List <IEffectEditorControl>();
            object[] values = _effectNode.Effect.ParameterValues;
            if (_effectNode.Effect.EffectName.Equals("Nutcracker"))
            {
                var data = _effectNode.Effect.ParameterValues.First() as ICloneable;
                values = new [] { data.Clone() };
            }


            _cleanValues = _effectNode.Effect.ParameterValues;

            // if there were multiple controls returned, or there was only a single control needed (ie. the efffect parameters had only
            // a single item) then add controls inside a ParameterEditor wrapper using editors for that type, and label them appropriately.
            // if it was only a single control returned, it must have matched the entire effect (by GUID or signature), so just dump the
            // control it, and let it deal with everything it needs to.
            if (controls.Count() > 1 ||
                (controls.Count() == 1 && (_effectNode.Effect.Descriptor as IEffectModuleDescriptor).Parameters.Count == 1))
            {
                _usedSingleControl = false;
                int i = 0;
                foreach (IEffectEditorControl ec in controls)
                {
                    // as it's a single control for a single parameter, it *should* take the corresponding indexed parameter from the effect.
                    // so pull that individual parameter out, and give it to the control as a single item. This is a bit of an assumption
                    // and seems...... prone to breaking. TODO: review.
                    ec.EffectParameterValues = values[i].AsEnumerable().ToArray();

                    ec.TargetEffect = effectNode.Effect;

                    if (_effectNode.Effect.Parameters[i].ShowLabel)
                    {
                        Label l = new Label();
                        l.Width    = 1;
                        l.Height   = 1;
                        l.Text     = string.Format("{0}:", _effectNode.Effect.Parameters[i].Name);
                        l.AutoSize = true;
                        l.Anchor   = AnchorStyles.None;
                        tableLayoutPanelEffectEditors.Controls.Add(l);
                    }

                    (ec as Control).Anchor = AnchorStyles.None;
                    tableLayoutPanelEffectEditors.Controls.Add(ec as Control);

                    // save the editor control into a list we can use as a reference later on, to pull the data back out of them in the right order.
                    _controls.Add(ec);
                    i++;
                }
            }
            else
            {
                _usedSingleControl = true;
                IEffectEditorControl control = controls.First();
                control.EffectParameterValues = _effectNode.Effect.ParameterValues;
                control.TargetEffect          = effectNode.Effect;
                tableLayoutPanelEffectEditors.Controls.Add(control as Control);
                tableLayoutPanelEffectEditors.SetColumnSpan((control as Control), 2);

                _controls.Add(control);
            }
        }
예제 #3
0
        private static void FeedSampleChapters()
        {
            var sampleChapters = ApplicationServices.GetRequiredService <SampleChapters>();

            sampleChapters.CreateSampleChapters();
        }
예제 #4
0
 public virtual CommitResult Commit(JArray log)
 {
     _commitResult = new CommitResult();
     try
     {
         if (log.Count > 0)
         {
             using (DataConnection connection = new DataConnection(LoadConfig(((string)(log[0]["controller"]))).ConnectionStringName, true))
             {
                 int    index            = -1;
                 int    sequence         = -1;
                 int    lastSequence     = sequence;
                 string transactionScope = ((string)(ApplicationServices.Settings("odp.transactions.scope")));
                 for (int i = 0; (i < log.Count); i++)
                 {
                     JToken     entry       = log[i];
                     string     controller  = ((string)(entry["controller"]));
                     string     view        = ((string)(entry["view"]));
                     ActionArgs executeArgs = entry["args"].ToObject <ActionArgs>();
                     if (executeArgs.Sequence.HasValue)
                     {
                         sequence = executeArgs.Sequence.Value;
                         if ((transactionScope == "sequence") && (sequence != lastSequence && (i > 0)))
                         {
                             connection.Commit();
                             _commitResult.Sequence = lastSequence;
                             connection.BeginTransaction();
                         }
                         lastSequence = sequence;
                     }
                     ControllerConfiguration config = LoadConfig(executeArgs.Controller);
                     ProcessArguments(config, executeArgs);
                     ActionResult executeResult = ControllerFactory.CreateDataController().Execute(controller, view, executeArgs);
                     if (executeResult.Errors.Count > 0)
                     {
                         index = i;
                         _commitResult.Index  = index;
                         _commitResult.Errors = executeResult.Errors.ToArray();
                         break;
                     }
                     else
                     {
                         ProcessResult(config, executeResult);
                     }
                 }
                 if (index == -1)
                 {
                     connection.Commit();
                     _commitResult.Sequence = sequence;
                 }
                 else
                 {
                     connection.Rollback();
                     _commitResult.Index = index;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         _commitResult.Errors = new string[] {
             ex.Message
         };
         _commitResult.Index = 0;
     }
     return(_commitResult);
 }
 private void UpdateCaption()
 {
     this.Text = String.Format("{0} {1}", ApplicationServices.GetApplicationDescription(), new AssemblyInfo().Version.ToString());
 }
예제 #6
0
        protected override void OnInit(EventArgs e)
        {
            if (Request.Path.StartsWith((ResolveUrl(AquariumExtenderBase.DefaultServicePath) + "/"), StringComparison.CurrentCultureIgnoreCase) || Request.Path.StartsWith((ResolveUrl(AquariumExtenderBase.AppServicePath) + "/"), StringComparison.CurrentCultureIgnoreCase))
            {
                ApplicationServices.HandleServiceRequest(Context);
            }
            if (Request.Params["_page"] == "_blank")
            {
                return;
            }
            var link = Request.Params["_link"];

            if (!(string.IsNullOrEmpty(link)))
            {
                var permalink = StringEncryptor.FromString(link.Replace(" ", "+").Split(',')[0]).Split('?');
                if (permalink.Length == 2)
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "Redirect", string.Format("window.location.replace(\'{0}?_link={1}\');", permalink[0], HttpUtility.UrlEncode(link)), true);
                }
            }
            else
            {
                var requestUrl = Request.RawUrl;
                if ((requestUrl.Length > 1) && requestUrl.EndsWith("/"))
                {
                    requestUrl = requestUrl.Substring(0, (requestUrl.Length - 1));
                }
                if (Request.ApplicationPath.Equals(requestUrl, StringComparison.CurrentCultureIgnoreCase))
                {
                    var homePageUrl = ApplicationServices.HomePageUrl;
                    if (!(Request.ApplicationPath.Equals(homePageUrl)))
                    {
                        Response.Redirect(homePageUrl);
                    }
                }
            }
            var contentInfo = ApplicationServices.LoadContent();

            InitializeSiteMaster();
            string s = null;

            if (!(contentInfo.TryGetValue("PageTitle", out s)))
            {
                s = ApplicationServicesBase.Current.DisplayName;
            }
            this.Title = s;
            if (_pageTitleContent != null)
            {
                if (_isTouchUI)
                {
                    _pageTitleContent.Text = string.Empty;
                }
                else
                {
                    _pageTitleContent.Text = s;
                }
            }
            var appName = new HtmlMeta();

            appName.Name    = "application-name";
            appName.Content = ApplicationServicesBase.Current.DisplayName;
            Header.Controls.Add(appName);
            if (contentInfo.TryGetValue("Head", out s) && (_headContent != null))
            {
                _headContent.Text = s;
            }
            if (contentInfo.TryGetValue("PageContent", out s) && (_pageContent != null))
            {
                if (_isTouchUI)
                {
                    s = string.Format("<div id=\"PageContent\" style=\"display:none\">{0}</div>", s);
                }
                var userControl = Regex.Match(s, "<div\\s+data-user-control\\s*=s*\"([\\s\\S]+?)\".*?>\\s*</div>");
                if (userControl.Success)
                {
                    var startPos = 0;
                    while (userControl.Success)
                    {
                        _pageContent.Controls.Add(new LiteralControl(s.Substring(startPos, (userControl.Index - startPos))));
                        startPos = (userControl.Index + userControl.Length);
                        var    controlFileName  = userControl.Groups[1].Value;
                        var    controlExtension = Path.GetExtension(controlFileName);
                        string siteControlText  = null;
                        if (!(controlFileName.StartsWith("~")))
                        {
                            controlFileName = (controlFileName + "~");
                        }
                        if (string.IsNullOrEmpty(controlExtension))
                        {
                            var testFileName = (controlFileName + ".ascx");
                            if (File.Exists(Server.MapPath(testFileName)))
                            {
                                controlFileName  = testFileName;
                                controlExtension = ".ascx";
                            }
                            else
                            {
                                if (ApplicationServices.IsSiteContentEnabled)
                                {
                                    var relativeControlPath = controlFileName.Substring(1);
                                    if (relativeControlPath.StartsWith("/"))
                                    {
                                        relativeControlPath = relativeControlPath.Substring(1);
                                    }
                                    siteControlText = ApplicationServices.Current.ReadSiteContentString(("sys/" + relativeControlPath));
                                }
                                if (siteControlText == null)
                                {
                                    testFileName = (controlFileName + ".html");
                                    if (File.Exists(Server.MapPath(testFileName)))
                                    {
                                        controlFileName  = testFileName;
                                        controlExtension = ".html";
                                    }
                                }
                            }
                        }
                        var userControlAuthorizeRoles = Regex.Match(userControl.Value, "data-authorize-roles\\s*=\\s*\"(.+?)\"");
                        var allowUserControl          = !userControlAuthorizeRoles.Success;
                        if (!allowUserControl)
                        {
                            var authorizeRoles = userControlAuthorizeRoles.Groups[1].Value;
                            if (authorizeRoles == "?")
                            {
                                if (!Context.User.Identity.IsAuthenticated)
                                {
                                    allowUserControl = true;
                                }
                            }
                            else
                            {
                                allowUserControl = ApplicationServices.UserIsAuthorizedToAccessResource(controlFileName, authorizeRoles);
                            }
                        }
                        if (allowUserControl)
                        {
                            try
                            {
                                if (controlExtension == ".ascx")
                                {
                                    _pageContent.Controls.Add(LoadControl(controlFileName));
                                }
                                else
                                {
                                    var controlText = siteControlText;
                                    if (controlText == null)
                                    {
                                        controlText = File.ReadAllText(Server.MapPath(controlFileName));
                                    }
                                    var bodyMatch = Regex.Match(controlText, "<body[\\s\\S]*?>([\\s\\S]+?)</body>");
                                    if (bodyMatch.Success)
                                    {
                                        controlText = bodyMatch.Groups[1].Value;
                                    }
                                    controlText = ApplicationServices.EnrichData(Localizer.Replace("Controls", Path.GetFileName(Server.MapPath(controlFileName)), controlText));
                                    _pageContent.Controls.Add(new LiteralControl(InjectPrefetch(controlText)));
                                }
                            }
                            catch (Exception ex)
                            {
                                _pageContent.Controls.Add(new LiteralControl(string.Format("Error loading \'{0}\': {1}", controlFileName, ex.Message)));
                            }
                        }
                        userControl = userControl.NextMatch();
                    }
                    if (startPos < s.Length)
                    {
                        _pageContent.Controls.Add(new LiteralControl(s.Substring(startPos)));
                    }
                }
                else
                {
                    _pageContent.Text = InjectPrefetch(s);
                }
            }
            else
            if (_isTouchUI)
            {
                _pageContent.Text = "<div id=\"PageContent\" style=\"display:none\"><div data-app-role=\"page\">404 Not Foun" +
                                    "d</div></div>";
                this.Title = ApplicationServicesBase.Current.DisplayName;
            }
            else
            {
                _pageContent.Text = "404 Not Found";
            }
            if (_isTouchUI)
            {
                if (_pageFooterContent != null)
                {
                    _pageFooterContent.Text = (("<footer style=\"display:none\"><small>" + Copyright)
                                               + "</small></footer>");
                }
            }
            else
            if (contentInfo.TryGetValue("About", out s))
            {
                if (_pageSideBarContent != null)
                {
                    _pageSideBarContent.Text = string.Format("<div class=\"TaskBox About\"><div class=\"Inner\"><div class=\"Header\">About</div><div" +
                                                             " class=\"Value\">{0}</div></div></div>", s);
                }
            }
            string bodyAttributes = null;

            if (contentInfo.TryGetValue("BodyAttributes", out bodyAttributes))
            {
                _bodyAttributes.Parse(bodyAttributes);
            }
            var classAttr = _bodyAttributes["class"];

            if (string.IsNullOrEmpty(classAttr))
            {
                classAttr = string.Empty;
            }
            if (!_isTouchUI)
            {
                if (!(classAttr.Contains("Wide")))
                {
                    classAttr = (classAttr + " Standard");
                }
                classAttr = ((classAttr + " ")
                             + (Regex.Replace(Request.Path.ToLower(), "\\W", "_").Substring(1) + "_html"));
            }
            else
            if (_summaryDisabled)
            {
                classAttr = (classAttr + " see-all-always");
            }
            if (!(string.IsNullOrEmpty(classAttr)))
            {
                _bodyAttributes["class"] = classAttr.Trim();
            }
            _bodyTag.Text = string.Format("\r\n<body{0}>\r\n", _bodyAttributes.ToString());
            base.OnInit(e);
        }
예제 #7
0
        private void MigrateLipSyncFrom4To5(XElement content)
        {
            //This migration deals with changing the LipSync matrix elements from version 4 to 5
            //Get the standard namespaces that are needed in the sequence
            var namespaces = GetStandardNamespaces();
            //Add in the ones for this effect
            XNamespace d2p1 = "http://schemas.datacontract.org/2004/07/VixenModules.Effect.LipSync";

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

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

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

            LipSyncMapLibrary _library =
                ApplicationServices.Get <IAppModuleInstance>(LipSyncMapDescriptor.ModuleID) as LipSyncMapLibrary;

            foreach (var lipSyncElement in lipSyncElements.ToList())
            {
                LipSyncMapData mapData = null;

                var lipSyncData = DeSerializer <LipSyncData>(lipSyncElement);

                if (_library.Library.TryGetValue(lipSyncData.PhonemeMapping, out mapData))
                {
                    if ((null != mapData) && (mapData.IsMatrix))
                    {
                        if (lipSyncData.Level == 0)
                        {
                            lipSyncData.Level = 100;
                        }

                        if (lipSyncData.ScalePercent == 0)
                        {
                            lipSyncData.ScalePercent = 100;
                        }

                        lipSyncData.Orientation = (mapData.StringsAreRows) ? StringOrientation.Horizontal : StringOrientation.Vertical;

                        lipSyncData.ScaleToGrid = true;
                        mapData.UsingDefaults   = false;
                    }
                }

                //Remove the old version
                lipSyncElement.Remove();

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

                //Serialize the object into a xelement
                XElement glp = Serializer(dc, new[] { typeof(LipSyncData), 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));
            }
        }
예제 #8
0
        private void papagayoImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PapagayoDoc papagayoFile = new PapagayoDoc();
            FileDialog  openDialog   = new OpenFileDialog();

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

            papagayoFile.Load(fileName);
            TimelineElementsClipboardData result = new TimelineElementsClipboardData
            {
                FirstVisibleRow   = -1,
                EarliestStartTime = TimeSpan.MaxValue,
            };

            result.FirstVisibleRow = 0;
            int rownum = 0;

            foreach (string voice in papagayoFile.VoiceList)
            {
                List <PapagayoPhoneme> phonemes = papagayoFile.PhonemeList(voice);
                if (phonemes.Count > 0)
                {
                    foreach (PapagayoPhoneme phoneme in phonemes)
                    {
                        if (phoneme.DurationMS == 0.0)
                        {
                            continue;
                        }
                        IEffectModuleInstance effect =
                            ApplicationServices.Get <IEffectModuleInstance>(new LipSyncDescriptor().TypeId);
                        ((LipSync)effect).StaticPhoneme = (App.LipSyncApp.PhonemeType)Enum.Parse(typeof(App.LipSyncApp.PhonemeType), phoneme.TypeName.ToUpper());
                        ((LipSync)effect).LyricData     = phoneme.LyricData;
                        TimeSpan             startTime      = TimeSpan.FromMilliseconds(phoneme.StartMS);
                        EffectModelCandidate modelCandidate =
                            new EffectModelCandidate(effect)
                        {
                            Duration  = TimeSpan.FromMilliseconds(phoneme.DurationMS - 1),
                            StartTime = startTime
                        };
                        result.EffectModelCandidates.Add(modelCandidate, rownum);
                        if (startTime < result.EarliestStartTime)
                        {
                            result.EarliestStartTime = startTime;
                        }
                        effect.Render();
                    }
                    IDataObject dataObject = new DataObject(ClipboardFormatName);
                    dataObject.SetData(result);
                    Clipboard.SetDataObject(dataObject, true);
                    _TimeLineSequenceClipboardContentsChanged(EventArgs.Empty);
                    SequenceModified();
                }
                rownum++;
            }
            string displayStr = rownum + " Voices imported to clipboard as seperate rows\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();
        }
예제 #9
0
 public virtual CommitResult Commit(JArray log)
 {
     _commitResult = new CommitResult();
     try
     {
         if (log.Count > 0)
         {
             using (var tx = new DataTransaction(LoadConfig(((string)(log[0]["controller"]))).ConnectionStringName))
             {
                 var index              = -1;
                 var sequence           = -1;
                 var lastSequence       = sequence;
                 var commitedValueCount = _commitResult.Values.Count;
                 var transactionScope   = ((string)(ApplicationServices.Settings("odp.transactions.scope")));
                 for (var i = 0; (i < log.Count); i++)
                 {
                     var entry      = log[i];
                     var controller = ((string)(entry["controller"]));
                     var view       = ((string)(entry["view"]));
                     ActionArgs.Forget();
                     var executeArgs = entry["args"].ToObject <ActionArgs>();
                     if (executeArgs.Sequence.HasValue)
                     {
                         sequence = executeArgs.Sequence.Value;
                         if (transactionScope != "all" && (sequence != lastSequence && (i > 0)))
                         {
                             tx.Commit();
                             _commitResult.Sequence = lastSequence;
                             commitedValueCount     = _commitResult.Values.Count;
                             tx.BeginTransaction();
                         }
                         lastSequence = sequence;
                     }
                     var config = LoadConfig(executeArgs.Controller);
                     ProcessArguments(config, executeArgs);
                     var executeResult = ControllerFactory.CreateDataController().Execute(controller, view, executeArgs);
                     if (executeResult.Errors.Count > 0)
                     {
                         index = i;
                         _commitResult.Index  = index;
                         _commitResult.Errors = executeResult.Errors.ToArray();
                         break;
                     }
                     else
                     {
                         ProcessResult(config, executeResult);
                     }
                 }
                 if (index == -1)
                 {
                     tx.Commit();
                     _commitResult.Sequence = sequence;
                     commitedValueCount     = _commitResult.Values.Count;
                 }
                 else
                 {
                     tx.Rollback();
                     _commitResult.Index = index;
                     _commitResult.Values.RemoveRange(commitedValueCount, (_commitResult.Values.Count - commitedValueCount));
                 }
             }
         }
     }
     catch (Exception ex)
     {
         _commitResult.Errors = new string[] {
             ex.Message
         };
         _commitResult.Index = 0;
     }
     return(_commitResult);
 }
예제 #10
0
 private void buttonOK_Click(object sender, EventArgs e)
 {
     Effect = ApplicationServices.Get <IEffectModuleInstance>(_descriptor.TypeId);
     Effect.ParameterValues = panelContainer.Controls.Cast <IEffectEditorControl>().SelectMany(x => x.EffectParameterValues).ToArray();
 }
예제 #11
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);
        }
예제 #12
0
 public void RegisterOperation(IBackgroundOperation operation)
 {
     ApplicationServices.ExecuteOnUIThread(() => Operations.Add(new BackgroundOperationViewModel(operation)));
 }
예제 #13
0
        private void InitializeLayers()
        {
            var descriptors = ApplicationServices.GetModuleDescriptors <ILayerMixingFilterInstance>();

            _standardFilters = descriptors.Select(filterType => ApplicationServices.Get <ILayerMixingFilterInstance>(filterType.TypeId)).ToList();
        }
예제 #14
0
        private void LoadAvailableEffects()
        {
            int imageSize = (int)(18 * ScalingTools.GetScaleFactor());

            effectTreeImages.ImageSize = new Size(imageSize, imageSize);
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form_Effects));
            effectTreeImages.ImageStream      = ((ImageListStreamer)(resources.GetObject("effectTreeImages.ImageStream")));
            effectTreeImages.TransparentColor = treeEffects.BackColor;
            effectTreeImages.Images.SetKeyName(0, "rightarrow.png");
            effectTreeImages.Images.SetKeyName(1, "downarrow.png");
            treeEffects.ItemHeight = (int)ScalingTools.MeasureHeight(treeEffects.Font, "My Text");

            foreach (
                IEffectModuleDescriptor effectDesriptor in
                ApplicationServices.GetModuleDescriptors <IEffectModuleInstance>().Cast <IEffectModuleDescriptor>())
            {
                // Add the effects to the tree
                // Set default to basic to get rid of annoying possible null reference warning.
                if (effectDesriptor.EffectName == "Nutcracker")
                {
                    continue;
                }
                TreeNode parentNode = treeEffects.Nodes["treeBasic"];

                switch (effectDesriptor.EffectGroup)
                {
                case EffectGroups.Basic:
                    parentNode = treeEffects.Nodes["treeBasic"];
                    break;

                case EffectGroups.Pixel:
                    parentNode = treeEffects.Nodes["treeAdvanced"];
                    break;

                case EffectGroups.Device:
                    parentNode = treeEffects.Nodes["treeDevice"];
                    break;
                }
                TreeNode node = new TreeNode(effectDesriptor.EffectName)
                {
                    Tag = effectDesriptor.TypeId
                };

                node.ForeColor = ThemeColorTable.ForeColor;
                parentNode.Nodes.Add(node);
                // Set the image
                Image image = effectDesriptor.GetRepresentativeImage(48, 48);
                if (image != null)
                {
                    effectTreeImages.Images.Add(effectDesriptor.EffectName, image);
                    node.ImageIndex         = effectTreeImages.Images.Count - 1;
                    node.SelectedImageIndex = node.ImageIndex;
                }
                else
                {
                    SetNodeImage(node, "blank.png");
                }

                if (treeEffects.Nodes.Count > 0)
                {
                    treeEffects.CollapseAll();
                    treeEffects.Nodes[0].Expand();
                    treeEffects.Nodes[1].Expand();
                }
                treeEffects.Nodes[0].EnsureVisible();
            }
        }
예제 #15
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;

                            case 'W':
                                cbi       = new ColorBreakdownItem();
                                cbi.Color = System.Drawing.Color.White;
                                cbi.Name  = White;
                                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);
        }
예제 #16
0
 private void LipSyncMapSelector_FormClosing(object sender, FormClosingEventArgs e)
 {
     var data = (ApplicationServices.Get <IAppModuleInstance>(LipSyncMapDescriptor.ModuleID) as LipSyncMapLibrary)?.StaticModuleData as
                LipSyncMapStaticData;
 }
예제 #17
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="applicationServices">Application Services</param>
 public RedisController(ApplicationServices applicationServices)
     : base(applicationServices)
 {
 }
예제 #18
0
        private static MimeLimits GetDefaultMimeDocumentLimits()
        {
            if (MimeLimits.defaultLimits == null)
            {
                lock (MimeLimits.configurationLockObject)
                {
                    if (MimeLimits.defaultLimits == null)
                    {
                        IList <CtsConfigurationSetting> configuration = ApplicationServices.Provider.GetConfiguration("MimeLimits");
                        int defaultValue  = 10;
                        int defaultValue2 = 100;
                        int defaultValue3 = int.MaxValue;
                        int defaultValue4 = int.MaxValue;
                        int defaultValue5 = 10000;
                        int defaultValue6 = 100000;
                        int defaultValue7 = int.MaxValue;
                        int defaultValue8 = 32768;
                        int defaultValue9 = int.MaxValue;
                        int num           = 256;
                        foreach (CtsConfigurationSetting ctsConfigurationSetting in configuration)
                        {
                            string key;
                            switch (key = ctsConfigurationSetting.Name.ToLower())
                            {
                            case "maximumpartdepth":
                                defaultValue = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue, 5, false);
                                break;

                            case "maximumembeddeddepth":
                                defaultValue2 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue2, 10, false);
                                break;

                            case "maximumsize":
                                defaultValue3 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue3, 100, true);
                                break;

                            case "maximumtotalheaderssize":
                                defaultValue4 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue4, 100, true);
                                break;

                            case "maximumparts":
                                defaultValue5 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue5, 100, false);
                                break;

                            case "maximumheaders":
                                defaultValue6 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue6, 100, false);
                                break;

                            case "maximumaddressitemsperheader":
                                defaultValue7 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue7, 100, false);
                                break;

                            case "maximumparametersperheader":
                                defaultValue9 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue9, 10, false);
                                break;

                            case "maximumtextvaluesize":
                                defaultValue8 = ApplicationServices.ParseIntegerSetting(ctsConfigurationSetting, defaultValue8, 10, true);
                                break;
                            }
                        }
                        MimeLimits.defaultLimits = new MimeLimits(defaultValue, defaultValue2, defaultValue3, defaultValue4, defaultValue5, defaultValue6, defaultValue7, defaultValue8, defaultValue9, num);
                    }
                }
            }
            return(MimeLimits.defaultLimits);
        }
예제 #19
0
 public static void CreateStandardMembershipAccounts()
 {
     ApplicationServices.RegisterStandardMembershipAccounts();
 }
예제 #20
0
        protected string PreparePrefetch(string content)
        {
            string output = null;

            if (!(string.IsNullOrEmpty(Request.Url.Query)) || (Request.Headers["X-Cot-Manifest-Request"] == "true"))
            {
                return(output);
            }
            var token = ApplicationServices.TryGetJsonProperty(ApplicationServices.Current.DefaultSettings, "ui.history.dataView");
            var supportGridPrefetch = ((token != null) && !(Regex.IsMatch(((string)(token)), "\\b(search|sort|group|filter)\\b")));
            var prefetches          = new List <string>();
            var prefetch            = false;
            var dataViews           = new List <Tuple <string, AttributeDictionary> >();

            foreach (Match m in Regex.Matches(content, "<div\\s+(id=\"(?\'Id\'\\w+)\")\\s+(?\'Props\'data-controller.*?)>"))
            {
                dataViews.Add(new Tuple <string, AttributeDictionary>(m.Groups["Id"].Value, new AttributeDictionary(m.Groups["Props"].Value)));
            }
            if (dataViews.Count == 1)
            {
                prefetch = true;
            }
            else
            {
                // LEGACY MASTER DETAIL PAGE SUPPORT
                //
                //
                // 1. convert text of containers into single container with single dataview referring to virtual dashboard controller
                //
                // <div data-flow="row">
                //   <div id="view1" data-controller="Dashboards" data-view="form1" data-show-action-buttons="none"></div>
                //
                // </div>
                //
                // 2. produce response for this controller.
                // a. standalone data views become data view fields of the virtual controller
                // b. the layout of the page is optionally converted into form1 layout of the virtual controller
                // c. render json response of virtual controller with layout in it
                //
            }
            if (prefetch)
            {
                for (var i = 0; (i < dataViews.Count); i++)
                {
                    var dataView   = dataViews[i];
                    var dataViewId = dataView.Item1;
                    var attrs      = dataView.Item2;
                    foreach (var p in UnsupportedDataViewProperties)
                    {
                        if (attrs.ContainsKey(p))
                        {
                            return(output);
                        }
                    }
                    var    controllerName = attrs["data-controller"];
                    string viewId         = null;
                    string tags           = null;
                    attrs.TryGetValue("data-tags", out tags);
                    var c = Controller.CreateConfigurationInstance(GetType(), controllerName);
                    if (!(attrs.TryGetValue("data-view", out viewId)))
                    {
                        viewId = ((string)(c.Evaluate("string(/c:dataController/c:views/c:view[1]/@id)")));
                    }
                    var viewNav = c.SelectSingleNode("/c:dataController/c:views/c:view[@id=\'{0}\']", viewId);
                    if (!Context.User.Identity.IsAuthenticated && !((viewNav.GetAttribute("access", string.Empty) == "Public")))
                    {
                        return(output);
                    }
                    string roles = null;
                    if (attrs.TryGetValue("data-roles", out roles) && !(new ControllerUtilities().UserIsInRole(roles.Split(','))))
                    {
                        return(output);
                    }
                    tags = (tags
                            + (" " + viewNav.GetAttribute("tags", string.Empty)));
                    var isForm = (viewNav.GetAttribute("type", string.Empty) == "Form");
                    if (isForm)
                    {
                        _summaryDisabled = true;
                    }
                    if (!(Regex.IsMatch(tags, "\\bprefetch-data-none\\b")) && (supportGridPrefetch || isForm))
                    {
                        var request = new PageRequest(-1, 30, null, null);
                        request.Controller      = controllerName;
                        request.View            = viewId;
                        request.Tag             = tags;
                        request.ContextKey      = dataViewId;
                        request.SupportsCaching = true;
                        if (attrs.ContainsKey("data-search-on-start"))
                        {
                            request.DoesNotRequireData = true;
                        }
                        var response = ControllerFactory.CreateDataController().GetPage(request.Controller, request.View, request);
                        var result   = string.Format("{{ \"d\": {0} }}", ApplicationServices.CompressViewPageJsonOutput(JsonConvert.SerializeObject(response)));
                        prefetches.Add(string.Format("<script type=\"application/json\" id=\"_{0}_prefetch\">{1}</script>", dataViewId, Regex.Replace(result, "(<(/?\\s*script)(\\s|>))", "]_[$2$3]^[", RegexOptions.IgnoreCase)));
                        if (isForm)
                        {
                            foreach (var field in response.Fields)
                            {
                                if (string.IsNullOrEmpty(field.DataViewFilterFields) && (field.Type == "DataView"))
                                {
                                    var fieldAttr = new AttributeDictionary(string.Empty);
                                    fieldAttr.Add("data-controller", field.DataViewController);
                                    fieldAttr.Add("data-view", field.DataViewId);
                                    fieldAttr.Add("data-tags", field.Tag);
                                    if (field.DataViewSearchOnStart)
                                    {
                                        fieldAttr.Add("data-search-on-start", "true");
                                    }
                                    dataViews.Add(new Tuple <string, AttributeDictionary>(string.Format("{0}_{1}", dataViewId, field.Name), fieldAttr));
                                }
                            }
                        }
                    }
                }
            }
            if (prefetches.Count > 0)
            {
                output = string.Join(string.Empty, prefetches);
            }
            return(output);
        }
예제 #21
0
        void UpdateForm()
        {
            int selectedControllerCount = controllerTree.SelectedControllers.Count();

            buttonConfigureController.Enabled      = selectedControllerCount == 1;
            buttonNumberChannelsController.Enabled = selectedControllerCount == 1;
            buttonRenameController.Enabled         = selectedControllerCount == 1;

            buttonDeleteController.Enabled = selectedControllerCount >= 1;

            int runningCount    = 0;
            int notRunningCount = 0;
            int pausedCount     = 0;
            int notPausedCount  = 0;

            foreach (IControllerDevice controller in controllerTree.SelectedControllers)
            {
                if (controller.IsRunning)
                {
                    runningCount++;
                }
                else
                {
                    notRunningCount++;
                }
                if (controller.IsPaused)
                {
                    pausedCount++;
                }
                else
                {
                    notPausedCount++;
                }
            }
            buttonStartController.Enabled = notRunningCount > 0;
            buttonStopController.Enabled  = runningCount > 0;

            buttonAddController.Enabled = comboBoxNewControllerType.SelectedIndex >= 0;

            buttonSelectSourceElements.Enabled = controllerTree.SelectedTreeNodes.Count > 0;

            if (selectedControllerCount <= 0)
            {
                labelControllerType.Text = "";
                labelOutputCount.Text    = "";
            }
            else if (selectedControllerCount == 1)
            {
                labelControllerType.Text = ApplicationServices.GetModuleDescriptor(controllerTree.SelectedControllers.First().ModuleId).TypeName;
                labelOutputCount.Text    = controllerTree.SelectedControllers.First().OutputCount.ToString();
            }
            else
            {
                labelControllerType.Text = selectedControllerCount + " controllers selected";
                int count = 0;
                foreach (IControllerDevice controller in controllerTree.SelectedControllers)
                {
                    count += controller.OutputCount;
                }
                labelOutputCount.Text = count.ToString();
            }
        }
        private void RecursiveDataBindInternal(IHierarchicalEnumerable enumerable, StringBuilder sb)
        {
            bool first = true;

            if (this.Site != null)
            {
                return;
            }
            foreach (object item in enumerable)
            {
                IHierarchyData data = enumerable.GetHierarchyData(item);
                if (null != data)
                {
                    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(data);
                    if (props.Count > 0)
                    {
                        string title       = ((string)(props["Title"].GetValue(data)));
                        string description = ((string)(props["Description"].GetValue(data)));
                        string url         = ((string)(props["Url"].GetValue(data)));
                        string cssClass    = null;
                        bool   isPublic    = false;
                        if (item is SiteMapNode)
                        {
                            cssClass = ((SiteMapNode)(item))["cssClass"];
                            isPublic = ("true" == ((string)(((SiteMapNode)(item))["public"])));
                        }
                        string    roles    = String.Empty;
                        ArrayList roleList = ((ArrayList)(props["Roles"].GetValue(data)));
                        if (roleList.Count > 0)
                        {
                            roles = String.Join(",", ((string[])(roleList.ToArray(typeof(string)))));
                        }
                        bool resourceAuthorized = ((isPublic || (roles == "*")) || ApplicationServices.UserIsAuthorizedToAccessResource(url, roles));
                        if (resourceAuthorized)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                sb.Append(",");
                            }
                            sb.AppendFormat("{{title:\"{0}\",url:\"{1}\"", BusinessRules.JavaScriptString(title), BusinessRules.JavaScriptString(url));
                            if (!(String.IsNullOrEmpty(description)))
                            {
                                sb.AppendFormat(",description:\"{0}\"", BusinessRules.JavaScriptString(description));
                            }
                            if (url == Page.Request.RawUrl)
                            {
                                sb.Append(",selected:true");
                            }
                            if (!(String.IsNullOrEmpty(cssClass)))
                            {
                                sb.AppendFormat(",cssClass:\"{0}\"", cssClass);
                            }
                            if (data.HasChildren)
                            {
                                IHierarchicalEnumerable childrenEnumerable = data.GetChildren();
                                if (null != childrenEnumerable)
                                {
                                    sb.Append(",\"children\":[");
                                    RecursiveDataBindInternal(childrenEnumerable, sb);
                                    sb.Append("]");
                                }
                            }
                            sb.Append("}");
                        }
                    }
                }
            }
        }
예제 #23
0
    static async Task Start()
    {
        Log.Logger = new LoggerConfiguration()
                     .MinimumLevel.Information()
                     .Enrich.With(new ExceptionMessageEnricher())
                     .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{ExceptionMessage}{NewLine}")
                     .CreateLogger();

        LogManager.Use <SerilogFactory>();

        Console.Title = "Frontend";

        var endpointUri = "https://localhost:8081";
        //TODO: Update key
        var primaryKey   = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        var cosmosClient = new CosmosClient(endpointUri, primaryKey);

        var repository = new ShoppingCartRepository(cosmosClient, "Ex14");
        var tokenStore = new TokenStore(cosmosClient, "Ex14");

        await repository.Initialize();

        await tokenStore.Initialize();

        var config = new EndpointConfiguration("Frontend");

        config.Pipeline.Register(new DuplicateMessagesBehavior(), "Duplicates outgoing messages");
        config.SendFailedMessagesTo("error");
        var routing = config.UseTransport <LearningTransport>().Routing();

        routing.RouteToEndpoint(typeof(SubmitOrder).Assembly, "Orders");
        config.Pipeline.Register(b => new OutboxBehavior <ShoppingCart>(repository, b.Build <IDispatchMessages>(), tokenStore,
                                                                        m =>
        {
            if (m is SendSubmitOrder sendSubmit)
            {
                return(sendSubmit.OrderId);
            }

            return(null);
        }), "Deduplicates incoming messages");


        config.EnableInstallers();

        var endpoint = await Endpoint.Start(config).ConfigureAwait(false);

        var appServices = new ApplicationServices(repository, endpoint);

        Console.WriteLine("'create <order-id>' to create a new order.");
        Console.WriteLine("'submit <order-id>' to submit an order.");
        Console.WriteLine($"'add ({string.Join("|", Enum.GetNames(typeof(Filling)))}) to <order-id>' to add item with selected filling.");

        while (true)
        {
            var command = Console.ReadLine();

            if (string.IsNullOrEmpty(command))
            {
                break;
            }

            var match = submitExpr.Match(command);
            if (match.Success)
            {
                var orderId = match.Groups[1].Value;
                await appServices.SubmitOrder(orderId);

                continue;
            }
            match = createExpr.Match(command);
            if (match.Success)
            {
                var orderId = match.Groups[1].Value;
                await appServices.CreateOrder(orderId);

                continue;
            }
            match = addExpr.Match(command);
            if (match.Success)
            {
                var filling = match.Groups[1].Value;
                var orderId = match.Groups[2].Value;

                await appServices.AddItem(orderId, (Filling)Enum.Parse(typeof(Filling), filling));

                continue;
            }
            match = removeExpr.Match(command);
            if (match.Success)
            {
                var filling = match.Groups[1].Value;
                var orderId = match.Groups[2].Value;
                await appServices.RemoveItem(orderId, (Filling)Enum.Parse(typeof(Filling), filling));

                continue;
            }
            Console.WriteLine("Unrecognized command.");
        }

        await endpoint.Stop().ConfigureAwait(false);
    }
예제 #24
0
 private static void GetRequiredServices()
 {
     s_bookChaptersService =
         ApplicationServices.GetRequiredService <IBookChaptersService>();
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="applicationServices"></param>
 /// <param name="sampleService"></param>
 public TestsController(ApplicationServices applicationServices, ISampleService sampleService)
     : base(applicationServices)
 {
     _sampleService = sampleService;
 }
예제 #26
0
 protected void Page_PreRender(object sender, EventArgs e)
 {
     ApplicationServices.RegisterCssLinks(Page);
 }
예제 #27
0
 public static void RegisterFrameworkSettings(Page p)
 {
     if (!(p.ClientScript.IsStartupScriptRegistered(typeof(AquariumExtenderBase), "TargetFramework")))
     {
         p.ClientScript.RegisterStartupScript(typeof(AquariumExtenderBase), "TargetFramework", string.Format("var __targetFramework=\"4.6\",__tf=4.0,__servicePath=\"{0}\",__baseUrl=\"{1}\";", p.ResolveUrl(AquariumExtenderBase.DefaultServicePath), p.ResolveUrl("~")), true);
         p.ClientScript.RegisterStartupScript(typeof(AquariumExtenderBase), "TouchUI", (("var __settings=" + ApplicationServices.Create().UserSettings(p).ToString(Newtonsoft.Json.Formatting.None))
                                                                                        + ";"), true);
     }
 }
예제 #28
0
 public static void RegisterFrameworkSettings(Page p)
 {
     if (!(p.ClientScript.IsStartupScriptRegistered(typeof(AquariumExtenderBase), "TargetFramework")))
     {
         string designerPort = ApplicationServices.DesignerPort;
         if (!(String.IsNullOrEmpty(designerPort)) && !(Controller.UserIsInRole(ApplicationServices.SiteContentDevelopers)))
         {
             designerPort = String.Empty;
         }
         p.ClientScript.RegisterStartupScript(typeof(AquariumExtenderBase), "TargetFramework", String.Format("var __targetFramework=\"4.6\",__tf=4.01,__servicePath=\"{0}\",__baseUrl=\"{1}\",__desig" +
                                                                                                             "nerPort=\"{2}\";", p.ResolveClientUrl(AquariumExtenderBase.DefaultServicePath), p.ResolveClientUrl("~"), designerPort), true);
         p.ClientScript.RegisterStartupScript(typeof(AquariumExtenderBase), "TouchUI", (("var __settings=" + ApplicationServices.Create().UserSettings(p).ToString(Newtonsoft.Json.Formatting.None))
                                                                                        + ";"), true);
     }
 }
 public void Cleanup()
 {
     ApplicationServices.Clear();
 }
예제 #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UpdateCheckResult"/> class.
 /// </summary>
 /// <param name="asyncState">
 /// The async state.
 /// </param>
 /// <param name="info">
 /// The info.
 /// </param>
 public UpdateCheckResult(object asyncState, ApplicationServices.Model.General.UpdateCheckInformation info)
 {
     this.AsyncState = asyncState;
     this.Result = info;
 }
예제 #31
0
 public CartController(ApplicationServices appServices)
 {
     this.appServices = appServices;
 }