Beispiel #1
0
 public void MatchValue()
 {
     ApplicationData postedData = new ApplicationData { { "First_name", "Superman" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsTrue(result);
 }
 /// <summary>
 /// Creates a new <see cref="TransactionVariables"/>.
 /// </summary>
 /// <param name="formId">The form id.</param>
 /// <param name="applicationId">The application id.</param>
 /// <param name="applicationData">The application data.</param>
 /// <returns>A new <see cref="TransactionVariables"/>.</returns>
 public TransactionVariables Create(string formId, string applicationId, ApplicationData applicationData)
 {
     ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(null, formId, null, applicationId, applicationData));
     double amountValue = evaluator.Evaluate<double>(this.AmountExpression);
     string referenceValue = evaluator.Evaluate<string>(this.ReferenceExpression);
     return new TransactionVariables(this.MerchantPassword, amountValue, referenceValue);
 }
        public void RepeaterHideRuleReferenceRootControl()
        {
            ITruthCondition condition = new HideTruthCondition { RuleType = "HIDE" };
            TruthConditionList subRuleList = new TruthConditionList();
            CompareDefinition compareDefinition = new CompareDefinition { CompareTo = ComparisonType.Value, Field = "Checkbox", FieldScope = FieldScope.Unknown, Operator = Operator.Equals, Value = "checked" };
            subRuleList.Add(new CompareTruthCondition { RuleType = "EVAL", Value = compareDefinition });
            condition.Value = subRuleList;

            ControlList controlList = new ControlList { new CheckboxControl { Name = "Checkbox" } };
            RepeaterControl repeater = new RepeaterControl { Name = "Parent" };
            repeater.AddChild(new ComboControl { Name = "Child", VisibilityRule = condition });
            controlList.Add(repeater);

            ApplicationData applicationData = new ApplicationData { { "Checkbox", "checked" } };
            Dictionary<string, object>[] repeaterValue = new Dictionary<string, object>[1];
            repeaterValue[0] = new Dictionary<string, object>();
            repeaterValue[0]["Child"] = string.Empty;
            applicationData.Add("Parent", repeaterValue);

            ITruthConditionEvaluator<ITruthCondition> evaluator = this.EvaluatorRegister.GetEvaluatorFor<HideTruthCondition>();
            bool result = evaluator.Evaluate(condition, controlList, applicationData, null, this.EvaluatorRegister, "Parent[0]");
            Assert.IsTrue(result);

            applicationData["Checkbox"] = string.Empty;
            result = evaluator.Evaluate(condition, controlList, applicationData, null, this.EvaluatorRegister, "Parent[0]");
            Assert.IsFalse(result);
        }
Beispiel #4
0
 public void MatchValueCaseDifferent()
 {
     ApplicationData postedData = new ApplicationData { { "First_name", "spIdERmAn" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsFalse(result);
 }
 public void LatitudeGreaterThanDoubleValue()
 {
     ApplicationData postedData = new ApplicationData { { "Geolocation", "100,300" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluatorLat.Evaluate(this.conditionLat, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsTrue(result);
 }
 public void LessThanDoubleValue()
 {
     ApplicationData postedData = new ApplicationData { { "Age", "49.5" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsTrue(result);
 }
 public void LongitudeLessThanDoubleValue()
 {
     ApplicationData postedData = new ApplicationData { { "Geolocation", "300,49.5" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluatorLong.Evaluate(this.conditionLong, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsFalse(result);
 }
 public void FieldMissing()
 {
     ApplicationData postedData = new ApplicationData();
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsFalse(result);
 }
        public void TestControlName()
        {
            string json = AssemblyResourceReader.ReadAsString("Test_Data.ValidateRule1.json");
            ValidateTruthCondition condition = JsonConvert.DeserializeObject<ValidateTruthCondition>(json);

            ControlList controlList = new ControlList();
            RepeaterControl repeater = new RepeaterControl
                                       { Id = 3, Name = "Repeater" };
            controlList.Add(repeater);
            repeater.Controls.Add(new TextControl { Id = 1, Name = "Field1", ParentId = 3 });
            repeater.Controls.Add(new TextControl { Id = 2, Name = "Field2", ParentId = 3 });

            ApplicationData appData = new ApplicationData();
            Dictionary<string, object>[] repeaterData = new Dictionary<string, object>[2];
            appData.Add("Repeater", repeaterData);
            repeaterData[0] = new Dictionary<string, object>
                              {
                                  { "Field1", "Is Valid" },
                                  { "Field2", "When Combined With This" }
                              };
            repeaterData[1] = new Dictionary<string, object>
                              {
                                  { "Field1", "Not Valid" },
                                  { "Field2", "When Combined With This" }
                              };

            TruthConditionEvaluatorFactory evaluatorFactory = new TruthConditionEvaluatorFactory();

            ITruthConditionValidator validator = new ITruthConditionValidator(condition, controlList, evaluatorFactory);
            ValidationResults results = validator.Validate(appData);
            Assert.AreEqual("Repeater[1].Field1", results.ToArray()[0].Key);
        }
 public void GreaterThanValue()
 {
     ApplicationData postedData = new ApplicationData { { "First_name", "Mix" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsFalse(result);
 }
 public void TestSerializeCheckboxGroup()
 {
     ApplicationData application = new ApplicationData { { "CheckboxGroupControl", new[] { "one", "three" } } };
     string json = JsonConvert.SerializeObject(application, Formatting.None);
     const string expected = "{\"CheckboxGroupControl\":[\"one\",\"three\"]}";
     Assert.AreEqual(expected, json);
 }
Beispiel #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Application"/> class.
 /// </summary>
 /// <param name="organisationId">The organisation id.</param>
 /// <param name="formId">The form id.</param>
 /// <param name="formVersion">The form version number.</param>
 /// <param name="applicationId">The application id.</param>
 /// <param name="applicationData">The application data.</param>
 public Application(string organisationId, string formId, int? formVersion, string applicationId = null, ApplicationData applicationData = null)
     : this(applicationData, applicationId)
 {
     this.OrganisationId = organisationId;
     this.FormId = formId;
     this.FormVersion = formVersion;
 }
Beispiel #13
0
 public void NotMatchNonEmptyStringValue()
 {
     ApplicationData postedData = new ApplicationData { { "First_name", "AmazingMan" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsTrue(result);
 }
Beispiel #14
0
 public void MatchValueWithSpaces()
 {
     ApplicationData postedData = new ApplicationData { { "First_name", "Amazing Man" } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsFalse(result);
 }
Beispiel #15
0
 public void DoesNotExist()
 {
     ApplicationData postedData = new ApplicationData();
     ApplicationData applicationData = new ApplicationData { { "First_name", "Batman" } };
     bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsFalse(result);
 }
Beispiel #16
0
 public void EmptyArrays()
 {
     ITruthCondition localCondition = JsonConvert.DeserializeObject<ITruthCondition>(this.GetTestResource("ConditionIn.empty.json"), new JsonKnownTypeConverter());
     ApplicationData postedData = new ApplicationData { { "First_name", new string[] { } } };
     ApplicationData applicationData = new ApplicationData();
     bool result = this.evaluator.Evaluate(localCondition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
     Assert.IsTrue(result);
 }
            public void SetsApplicationIdAndApplicationData()
            {
                ApplicationData data = new ApplicationData { { "Foo", "Bar" } };
                Application application = new Application(applicationId: "52ddb25d606fdc049c7aaf7e", applicationData: data);

                Assert.AreEqual("52ddb25d606fdc049c7aaf7e", application.Id);
                Assert.AreEqual("Bar", application.ApplicationData["Foo"]);
            }
 public void ControlHasBogusRule()
 {
     ControlList controlList = JsonConvert.DeserializeObject<ControlList>(this.GetTestResource("BogusRule.json"), new JsonKnownTypeConverter());
     ApplicationData postedData = new ApplicationData();
     GroupControl control = controlList.FindRecursive<GroupControl>(1);
     bool visible = control.IsVisible(controlList, postedData, null, this.register);
     Assert.IsTrue(visible);
 }
        public void Save(string applicationId, string itemId, string data)
        {
	        using (var client = Client.GetCoreService())
	        {
		        //Save the appdata here
		        var appdata = new ApplicationData { ApplicationId = applicationId, Data = new ASCIIEncoding().GetBytes(data) };
		        client.SaveApplicationData(itemId, new[] {appdata});
	        }
        }
            public void ControlIsHiddenByRule()
            {
                ControlList controlList = JsonConvert.DeserializeObject<ControlList>(this.GetTestResource("HideRule.json"), new JsonKnownTypeConverter());
                ApplicationData postedData = new ApplicationData { { "RuleTrigger", "HIDE IT" } };

                GroupControl control = controlList.FindRecursive<GroupControl>(1);
                bool visible = control.IsVisible(controlList, postedData, null, this.register);
                Assert.IsFalse(visible);
            }
            public void ChildControlIsNotHiddenByParentRule()
            {
                ControlList controlList = JsonConvert.DeserializeObject<ControlList>(this.GetTestResource("HideRule.json"), new JsonKnownTypeConverter());
                TextControl control = controlList.FindRecursive<TextControl>(2);

                ApplicationData postedData = new ApplicationData { { "RuleTrigger", "DON'T HIDE IT" } };
                bool visible = control.IsVisible(controlList, postedData, null, this.register);
                Assert.IsTrue(visible);
            }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationWorkflowItem"/> class.
 /// </summary>
 /// <param name="postedApplication">The updated <see cref="Application"/> containing
 /// the posted <see cref="ApplicationData"/>.</param>
 /// <param name="existingData">The existing <see cref="ApplicationData"/>. Defaults to <see langword="null"/>.</param>
 /// <param name="controlList">The controls. Defaults to <see langword="null"/>.</param>
 public ApplicationWorkflowItem(Application postedApplication, ApplicationData existingData = null, ControlList controlList = null)
     : this(postedApplication.FormId, postedApplication.LastEditBy)
 {
     this.ApplicationId = postedApplication.ApplicationId;
     this.VersionNumber = postedApplication.VersionNumber;
     this.PostedData = postedApplication.ApplicationData;
     this.ExistingData = existingData;
     this.ControlList = controlList;
 }
            public void ContinueAfterShownControl()
            {
                ApplicationData applicationData = new ApplicationData();
                applicationData.SetValue("Hide_trigger", "No", true);

                ValidationResults results = new ValidationResults();
                this.validator.Validate(applicationData, results);
                Assert.AreEqual(false, results.IsValid);
            }
        public void NotMatchEmptyStringAndNonNull()
        {
            ApplicationData postedData = new ApplicationData { { "First_name", "not null" } };
            ApplicationData applicationData = new ApplicationData();

            ((CompareDefinition)((CompareTruthCondition)((TruthConditionList)((IfTruthCondition)this.condition).Value).FirstOrDefault()).Value).Value = string.Empty;

            bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
            Assert.IsTrue(result);
        }
Beispiel #25
0
        public void MatchEmptyArray()
        {
            ApplicationData postedData = new ApplicationData();
            ApplicationData applicationData = new ApplicationData { { "Test", new object[0] } };

            this.condition = JsonConvert.DeserializeObject<ITruthCondition>(this.GetTestResource("ConditionEqArray.json"), new JsonKnownTypeConverter());

            bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
            Assert.IsFalse(result);
        }
            public void SetsParameters()
            {
                ApplicationData data = new ApplicationData { { "Foo", "Bar" } };
                Application application = new Application(null, "50adb7eae1b93108b04e63a9", 21, "52ddb25d606fdc049c7aaf7e", data);

                Assert.AreEqual("50adb7eae1b93108b04e63a9", application.FormId);
                Assert.AreEqual(21, application.FormVersion);
                Assert.AreEqual("52ddb25d606fdc049c7aaf7e", application.Id);
                Assert.AreEqual("Bar", application.ApplicationData["Foo"]);
            }
Beispiel #27
0
        public void MatchArrayAndArray()
        {
            ApplicationData postedData = new ApplicationData();
            ApplicationData applicationData = new ApplicationData { { "Checkbox_one", new[] { "1" } }, { "Checkbox_two", new[] { "1" } } };

            this.condition = JsonConvert.DeserializeObject<ITruthCondition>(this.GetTestResource("ConditionEqTwoArrays.json"), new JsonKnownTypeConverter());

            bool result = this.evaluator.Evaluate(this.condition, this.ControlList, postedData, applicationData, this.EvaluatorRegister);
            Assert.IsTrue(result);
        }
        public string SendRequest(ServiceEndpoint endpoint, ServiceEndpointUtilisation utilisation, Application application, ApplicationData updateTarget)
        {
            if (this.type == "VALIDATE")
            {
                string validateStr = AssemblyResourceReader.ReadAsString(string.Format("Test_Data.EndpointValidation.VALIDATE-{0}.json", endpoint.Id.PadLeft(2, '0')));

                return validateStr;
            }

            return null;
        }
        public void TestInitialize()
        {
            string json = AssemblyResourceReader.ReadAsString("Test_Data.ExpressionEvaluatorPostedData.json");
            this.postedData = JsonConvert.DeserializeObject<ApplicationData>(json);

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                                                {
                Formatting = Formatting.None,
                Converters = new JsonConverter[] { new JsonKnownTypeConverter() }
            };
        }
        public void TestSerializeRepeater()
        {
            ApplicationData application = new ApplicationData { { "Textbox1", "Value 1" } };
            List<Dictionary<string, object>> repeater = new List<Dictionary<string, object>>
                                                            {
                                                                new Dictionary<string, object> { { "Textbox2", "Repeater 1 Value 1" }, { "Textbox3", "Repeater 1 Value 2" } },
                                                                new Dictionary<string, object> { { "Textbox2", "Repeater 2 Value 1" }, { "Textbox3", "Repeater 2 Value 2" } }
                                                            };

            application.Add("Repeater", repeater);
            string json = JsonConvert.SerializeObject(application, Formatting.None);
            const string expected = "{\"Textbox1\":\"Value 1\",\"Repeater\":[{\"Textbox2\":\"Repeater 1 Value 1\",\"Textbox3\":\"Repeater 1 Value 2\"},{\"Textbox2\":\"Repeater 2 Value 1\",\"Textbox3\":\"Repeater 2 Value 2\"}]}";
            Assert.AreEqual(expected, json);
        }
Beispiel #31
0
    void MovingBall()
    {
        GameObject.FindGameObjectWithTag("YokaiGetPage").transform.Find("Button").GetComponent <Button> ().enabled = false;
        Debug.Log("GetPageManager.throwCount " + GetPageManager.throwCount);
        isBallFlying = true;
        throwCount++;
        if (UserData.IsShowedMessageForMiddleEndingBeforeBoss && !UserData.IsPassedBossOnce)
        {
            isBallFlying = false;
            GetPageManager.HideBackButton();
            GetPageManager.throwCount++;
            GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.SetActive(true);

            var sequence = DOTween.Sequence();
            sequence.Append(

                GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.DOLocalMoveY(0, .5f).SetEase(Ease.Linear).OnComplete(() => {
                GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.SetActive(false);
            })
                );
            sequence.Join(
                GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.DOScale(new Vector3(1, 1, 1), .5f).SetEase(Ease.Linear)

                );

            this.gameObject.SetActive(true);
            this.transform.localScale = new Vector3(8.5f, 8.5f, 8.5f);
            CircleScale();
            GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.localPosition = new Vector3(0, -4f, .2f);
            GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.localScale    = new Vector3(2, 2, 2);

            notification = GameObject.Find("TextCanvas").transform.Find("notification").gameObject;
            if (ApplicationData.SelectedLanguage == LanguageType.Thai)
            {
                notification.GetComponentInChildren <Text> ().font = ApplicationData.GetFont(4);
            }
            else
            {
                notification.GetComponentInChildren <Text> ().font = ApplicationData.GetFont(2);
            }
            if (GetPageManager.throwCount == 1)
            {
                notification.SetActive(true);
                notification.GetComponentInChildren <Text> ().text = ApplicationData.GetLocaleText(LocaleType.MiddleBossCrawMessage1);
            }
            if (GetPageManager.throwCount == 2)
            {
                notification.GetComponentInChildren <Text> ().text = ApplicationData.GetLocaleText(LocaleType.MiddleBossCrawMessage2);
            }
            if (GetPageManager.throwCount == 3)
            {
                notification.GetComponentInChildren <Text> ().text = ApplicationData.GetLocaleText(LocaleType.MiddleBossCrawMessage3);
                Invoke("FadeOut", 1);
                Invoke("EndingAfterMiddleBoss", 2f);
            }
        }
        else
        {
            if (PageData.IsItem)
            {
                GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.SetActive(true);
                var sequence = DOTween.Sequence();
                sequence.Append(

                    GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.DOLocalMoveY(0, .5f).SetEase(Ease.Linear).OnComplete(() => {
                    StartCoroutine(CatchYokai());
                })
                    );
                sequence.Join(
                    GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.DOScale(new Vector3(1, 1, 1), .5f).SetEase(Ease.Linear)

                    );
            }
            else
            {
                GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.SetActive(true);
                var sequence = DOTween.Sequence();
                sequence.Append(

                    GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.DOLocalMoveY(0, .5f).SetEase(Ease.Linear).OnComplete(() => {
                    StartCoroutine(CatchYokai());
                })
                    );
                sequence.Join(
                    GameObject.FindGameObjectWithTag("Model").transform.GetChild(2).gameObject.transform.DOScale(new Vector3(1, 1, 1), .5f).SetEase(Ease.Linear)

                    );
            }
        }
    }
        public static async Task <ApplicationDataStorageHelper> GetForUserAsync(User user, Toolkit.Helpers.IObjectSerializer?objectSerializer = null)
        {
            var appData = await ApplicationData.GetForUserAsync(user);

            return(new ApplicationDataStorageHelper(appData, objectSerializer));
        }
Beispiel #33
0
 /// <summary>
 /// This constructor is for design purposes only.
 /// </summary>
 public ProcessesViewModel()
 {
     _applicationData = new ApplicationData();
 }
Beispiel #34
0
 private static bool RunPackagingSequence(PreConfigurationState preConfigurationState, ApplicationData applicationData, out PackagedApplication packagedApplication)
 {
     try
     {
         var packager = new Packager(applicationData, preConfigurationState.InstallerOutputDestination);
         packagedApplication = packager.CreatePackage();
         return(true);
     }
     catch (Exception ex)
     {
         HostCore.Log.Error("Packaging failed", ex);
         MessageReporter.Show(FormatMessageFor(ex) + "\r\nCheck the log files or the extended information for troubleshooting.",
                              "Packaging failed!", ex, MessageBoxButtons.OK, MessageBoxIcon.Error);
         // ToDo: Clean up first!
         packagedApplication = null;
         return(false);
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PluginSettingDetails"/> class.
 /// </summary>
 /// <param name="applicationData">Application data where settings for plugin are stored.</param>
 public PluginSettingDetails(ApplicationData applicationData)
 {
     this.applicationData = applicationData ?? throw new System.ArgumentNullException(nameof(applicationData));
 }
Beispiel #36
0
        internal static void DoWork(List <INotifier> notifiers)
        {
            const string NOTIFICATION_FRAMEWORK_APPID = "code.google.com/p/tridion-notification-framework";
            const string NOTIFICATION_FREQUENCY       = "notification_frequency";
            const string NOTIFICATION_LAST_SEND       = "notification_last_send";
            var          client = Client.GetCoreService();
            var          users  = client.GetSystemWideList(new UsersFilterData {
                BaseColumns = ListBaseColumns.IdAndTitle, IsPredefined = false
            });
            var userIds = users.Select(f => f.Id).Distinct().ToArray();
            var userApplicationDataDict = client.ReadApplicationDataForSubjectsIds(userIds, new[] { NOTIFICATION_FRAMEWORK_APPID }).Where(a => a.Value.Length > 0);

            // REVIEW - too much logging?
            Logger.WriteToLog(string.Format("{0} users with application data found", userApplicationDataDict.Count()), EventLogEntryType.Information);


            // <NotificationFramework>
            //     <Notifier type="WorkflowEmailNotifier"
            //                notification_frequency="3D"
            //                notification_last_send="2012-10-07T23:13Z">
            //        <EmailAddress>[email protected]</EmailAddress>
            //    </Notifier>
            //    <Notifier type="WorkflowTwitterNotifier"
            //            notification_frequency="3D"
            //            notification_last_send="2012-10-07T23:13Z">
            //        <TwitterName>TridionLovingHackyGeek</TwitterName>
            //    </Notifier>
            //</NotificationFramework>
            var pollingInterval = GetPollingInterval();

            foreach (var notifier in notifiers)
            {
                foreach (KeyValuePair <string, ApplicationData[]> userApplicationData in userApplicationDataDict)
                {
                    var user = (UserData)users.Single(u => u.Id == userApplicationData.Key);
                    // REVIEW: The query expression is redundant, as we've asked the API for a filtered list....
                    // Oh wait - we want it to barf if there are two?
                    ApplicationData userNotificationApplicationData = userApplicationData.Value.Single(ad => ad.ApplicationId == NOTIFICATION_FRAMEWORK_APPID);
                    string          xmlData          = Encoding.UTF8.GetString(userNotificationApplicationData.Data);
                    var             doc              = XDocument.Parse(xmlData);
                    var             notifierElements = doc.Element("NotificationFramework").Elements("Notifier");
                    foreach (var notifierElement in notifierElements)
                    {
                        var notificationFrequency     = GetNotificationFrequency(notifierElement.Attribute(NOTIFICATION_FREQUENCY).Value);
                        var lastNotificationAttribute = notifierElement.Attribute(NOTIFICATION_LAST_SEND);
                        var lastNotificationTime      = ParseDate(lastNotificationAttribute.Value);
                        var nextNotificationCheckTime = lastNotificationTime.Add(notificationFrequency);

                        bool notificationIsNeeded = DateTime.Now.ToUniversalTime().Subtract(nextNotificationCheckTime) > pollingInterval;
                        if (notificationIsNeeded)
                        {
                            Logger.WriteToLog(string.Format("Impersonating as {0}", user.Title), EventLogEntryType.Information);
                            client.Impersonate(user.Title);

                            // Could factor this out more to allow for creating other kinds of notification data
                            // than WorkflowNotificationData, but for now YAGNI
                            // TODO: Do we check the CreationDate of the right subject???
                            var relevantWorkFlowDataItems = GetUserWorkflowItems(client).Where(
                                item => lastNotificationTime < client.Read(item.Subject.IdRef, null).VersionInfo.CreationDate).ToArray <WorkItemData>();

                            var notificationData = new WorkflowNotificationData()
                            {
                                ApplicationData = notifierElement.ToString(),
                                User            = user,
                                WorkItems       = relevantWorkFlowDataItems
                            };

                            notifier.Notify(notificationData);

                            lastNotificationAttribute.Value = DateTime.Now.ToUniversalTime().ToString("u");
                        }
                    }

                    userNotificationApplicationData.Data = Encoding.UTF8.GetBytes(doc.ToString());
                    client.SaveApplicationData(userApplicationData.Key, new[] { userNotificationApplicationData });
                }
                client.Close();
            }
        }
 private void AddApplicationDataToExcelPackage(ExcelPackage package, ApplicationData data) {
     AddAccountsWorksheetToExcelPackage(package, data.Accounts);
     AddCategoriesWorksheetToExcelPackage(package, data.Categories);
     AddAccountTransactionsWorksheetToExcelPackage(package, data.AccountTransactions);
 }
 public void ApplicationDataSerialize()
 {
     Assert.IsTrue(ApplicationData.Save(applicationData, ApplicationDataXmlFile));
 }
Beispiel #39
0
 public static string GetSpecialFolderPath()
 {
     return(ApplicationData.get_Current().get_LocalFolder().get_Path());
 }
Beispiel #40
0
 Application IOperationSource <Application> .CreateResult(Response response, CancellationToken cancellationToken)
 {
     using var document = JsonDocument.Parse(response.ContentStream);
     return(new Application(_operationBase, ApplicationData.DeserializeApplicationData(document.RootElement)));
 }
Beispiel #41
0
 public CustomerController(ApplicationData context)
 {
     _context = context;
 }
Beispiel #42
0
        /// <summary>
        /// Метод для трассировки
        /// </summary>
        /// <returns>Список логов шагов</returns>
        public static List <StepTracingLog> Trace(Scheme sch, PlacementResult plc, bool isOptimized, out string err)
        {
            // обязательно создаём лог действий
            var log = new List <StepTracingLog>();

            // при возникновении критической ошибки её нужно занести в эту переменную и сделать return null
            err = "";

            // формируем список плат, в котором хранится список слоёв (для каждого проводника свой слой ДРП)
            var boards = new List <List <Matrix <Cell> > >();

            // считываем список плат, в каждой плате хранится список проводников (Wire) соединяют всего 2 контакта
            List <List <Wire> > boardsWiresPositions = plc.BoardsWiresPositions;

            for (int boardNum = 0; boardNum < boardsWiresPositions.Count; boardNum++)
            {
                // получаем список проводов, которые необходимо развести на этой плате
                // элемент списка объект класса Wire, который хранит координаты точки А и Б на ДРП
                var boardWiresPositions = boardsWiresPositions[boardNum];

                // список ДРП текущей платы, в который будет заносится ДРП для каждого провода
                var boardDRPs = new List <Matrix <Cell> >();

                // добавляем этот список в список всех плат
                boards.Add(boardDRPs);

                // первым слоем будет являтся ДРП на котором просто отмечены места контактов платы
                boardDRPs.Add(plc.BoardsDRPs[boardNum]);

                // запускаем цикл по проводам
                foreach (var wire in boardWiresPositions)
                {
                    // ДРП для провода формируем на основе шаблона ДРП, на котором просто отмечены контакты. Оно уже имеет необходимые размеры.
                    var currentDRP = new Matrix <Cell>(plc.BoardsDRPs[boardNum].RowsCount, plc.BoardsDRPs[boardNum].ColsCount);

                    // добавляем это ДРП в список ДРП платы
                    boardDRPs.Add(currentDRP);

                    // заполняем ДРП пустыми ячейками
                    for (int i = 0; i < currentDRP.RowsCount; i++)
                    {
                        for (int j = 0; j < currentDRP.ColsCount; j++)
                        {
                            currentDRP[i, j] = new Cell();
                        }
                    }

                    // дрп, в котором будут объединены все слои с проводами (для определения гдле занята ячейка - где нет)
                    Matrix <Cell> fullDrp;

                    // получаем из провода стартовую и конечную позицию
                    var startPos = wire.A.PositionContact;
                    var endPos   = wire.B.PositionContact;

                    List <Beam> prioritetsPosBeamsA = new List <Beam>();
                    List <Beam> prioritetsPosBeamsB = new List <Beam>();

                    Position top    = new Position(-1, 0);
                    Position bottom = new Position(1, 0);
                    Position left   = new Position(0, -1);
                    Position right  = new Position(0, 1);

                    if (startPos.Row < endPos.Row)
                    {
                        prioritetsPosBeamsA.Add(new Beam(left, top));
                        prioritetsPosBeamsA.Add(new Beam(right, top));
                        prioritetsPosBeamsB.Add(new Beam(right, bottom));
                        prioritetsPosBeamsB.Add(new Beam(left, bottom));
                    }
                    else
                    {
                        prioritetsPosBeamsA.Add(new Beam(left, bottom));
                        prioritetsPosBeamsA.Add(new Beam(right, bottom));
                        prioritetsPosBeamsB.Add(new Beam(right, top));
                        prioritetsPosBeamsB.Add(new Beam(left, top));
                    }

                    if (startPos.Column < endPos.Column)
                    {
                        prioritetsPosBeamsA.Add(new Beam(top, left));
                        prioritetsPosBeamsA.Add(new Beam(bottom, left));
                        prioritetsPosBeamsB.Add(new Beam(top, right));
                        prioritetsPosBeamsB.Add(new Beam(bottom, right));
                    }
                    else
                    {
                        prioritetsPosBeamsA.Add(new Beam(top, right));
                        prioritetsPosBeamsA.Add(new Beam(bottom, right));
                        prioritetsPosBeamsB.Add(new Beam(top, left));
                        prioritetsPosBeamsB.Add(new Beam(bottom, left));
                    }



                    // помечаем буквами стартовую и конечную позицию на текущем слое провода
                    currentDRP[startPos.Row, startPos.Column].State = CellState.PointA;
                    currentDRP[endPos.Row, endPos.Column].State     = CellState.PointB;

                    // сообщаем о начале трассировки нового провода и печатаем сформированные приоритеты
                    string stepMsg = $"Начинаем трассировку {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле\n";
                    stepMsg += "Сформированы следующие приоритеты для лучей:\n";
                    int iterator = 1;
                    foreach (var prioritet in prioritetsPosBeamsA)
                    {
                        stepMsg += $"A{iterator}({getUnicodeArrowByPrioritetPos(prioritet.FirstPrioritetPos)},{getUnicodeArrowByPrioritetPos(prioritet.SecondPrioritetPos)}) ";
                        iterator++;
                    }
                    stepMsg += "\n";
                    iterator = 1;
                    foreach (var prioritet in prioritetsPosBeamsB)
                    {
                        stepMsg += $"B{iterator}({getUnicodeArrowByPrioritetPos(prioritet.FirstPrioritetPos)},{getUnicodeArrowByPrioritetPos(prioritet.SecondPrioritetPos)}) ";
                        iterator++;
                    }
                    log.Add(new StepTracingLog(boards, stepMsg));

                    // объединяем все слои с проводами платы, чтобы на основе этого ДРП получить список именно незанятых соседей
                    fullDrp = ApplicationData.MergeLayersDRPs(boardDRPs);

                    var beamsACurrentPos = new List <Position>();
                    var beamsBCurrentPos = new List <Position>();

                    for (int beamNum = 0; beamNum < prioritetsPosBeamsA.Count; beamNum++)
                    {
                        var posPrioritet = prioritetsPosBeamsA[beamNum].FirstPrioritetPos;
                        var pos          = new Position(startPos.Row - posPrioritet.Row, startPos.Column - posPrioritet.Column);
                        if (pos.isInDRP(fullDrp))
                        {
                            if (fullDrp[pos.Row, pos.Column].isBusyForBeam == false)
                            {
                                beamsACurrentPos.Add(pos);
                                currentDRP[pos.Row, pos.Column].State  = getArrowByPrioritet(posPrioritet.Row, posPrioritet.Column);
                                currentDRP[pos.Row, pos.Column].Weight = 1;
                                fullDrp[pos.Row, pos.Column].State     = getArrowByPrioritet(posPrioritet.Row, posPrioritet.Column);
                                fullDrp[pos.Row, pos.Column].Weight    = 1;
                                continue;
                            }
                        }
                        prioritetsPosBeamsA.RemoveAt(beamNum);
                        beamNum--;
                    }

                    for (int beamNum = 0; beamNum < prioritetsPosBeamsB.Count; beamNum++)
                    {
                        var posPrioritet = prioritetsPosBeamsB[beamNum].FirstPrioritetPos;
                        var pos          = new Position(endPos.Row - posPrioritet.Row, endPos.Column - posPrioritet.Column);
                        if (pos.isInDRP(fullDrp))
                        {
                            if (fullDrp[pos.Row, pos.Column].isBusyForBeam == false)
                            {
                                beamsBCurrentPos.Add(pos);
                                currentDRP[pos.Row, pos.Column].State  = getArrowByPrioritet(posPrioritet.Row, posPrioritet.Column);
                                currentDRP[pos.Row, pos.Column].Weight = 2;
                                fullDrp[pos.Row, pos.Column].State     = getArrowByPrioritet(posPrioritet.Row, posPrioritet.Column);
                                fullDrp[pos.Row, pos.Column].Weight    = 2;
                                continue;
                            }
                        }
                        prioritetsPosBeamsB.RemoveAt(beamNum);
                        beamNum--;
                    }
                    if (!isOptimized)
                    {
                        log.Add(new StepTracingLog(boards, $"Проведены лучи на 1 шаг {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле. Точек пересечения не найдено. Продолжаем."));
                    }

                    Position collisionPosBeamsA = null;
                    Position collisionPosBeamsB = null;
                    bool     isChanged          = false;

                    do
                    {
                        isChanged = false;

                        for (int beamNum = 0; beamNum < beamsACurrentPos.Count; beamNum++)
                        {
                            var currPos    = beamsACurrentPos[beamNum];
                            var prioritets = new List <Position>();
                            prioritets.Add(prioritetsPosBeamsA[beamNum].FirstPrioritetPos);
                            prioritets.Add(prioritetsPosBeamsA[beamNum].SecondPrioritetPos);
                            foreach (var prioritet in prioritets)
                            {
                                var checkingPos = new Position(currPos.Row - prioritet.Row, currPos.Column - prioritet.Column);
                                if (checkingPos.isInDRP(fullDrp))
                                {
                                    if (fullDrp[checkingPos.Row, checkingPos.Column].isBusyForBeam == false)
                                    {
                                        currentDRP[checkingPos.Row, checkingPos.Column].State  = getArrowByPrioritet(prioritet.Row, prioritet.Column);
                                        currentDRP[checkingPos.Row, checkingPos.Column].Weight = 1;
                                        fullDrp[checkingPos.Row, checkingPos.Column].State     = getArrowByPrioritet(prioritet.Row, prioritet.Column);
                                        fullDrp[checkingPos.Row, checkingPos.Column].Weight    = 1;
                                        isChanged = true;
                                        beamsACurrentPos[beamNum] = checkingPos;
                                        break;
                                    }
                                    else if (fullDrp[checkingPos.Row, checkingPos.Column].isArrow && fullDrp[checkingPos.Row, checkingPos.Column].Weight == 2)
                                    {
                                        isChanged          = true;
                                        collisionPosBeamsA = currPos;
                                        collisionPosBeamsB = checkingPos;
                                        beamNum            = 228;
                                        break;
                                    }
                                }
                            }
                        }

                        if (collisionPosBeamsA != null)
                        {
                            break;
                        }


                        for (int beamNum = 0; beamNum < beamsBCurrentPos.Count; beamNum++)
                        {
                            var currPos    = beamsBCurrentPos[beamNum];
                            var prioritets = new List <Position>();
                            prioritets.Add(prioritetsPosBeamsB[beamNum].FirstPrioritetPos);
                            prioritets.Add(prioritetsPosBeamsB[beamNum].SecondPrioritetPos);
                            foreach (var prioritet in prioritets)
                            {
                                var checkingPos = new Position(currPos.Row - prioritet.Row, currPos.Column - prioritet.Column);
                                if (checkingPos.isInDRP(fullDrp))
                                {
                                    if (fullDrp[checkingPos.Row, checkingPos.Column].isBusyForBeam == false)
                                    {
                                        currentDRP[checkingPos.Row, checkingPos.Column].State  = getArrowByPrioritet(prioritet.Row, prioritet.Column);
                                        currentDRP[checkingPos.Row, checkingPos.Column].Weight = 2;
                                        fullDrp[checkingPos.Row, checkingPos.Column].State     = getArrowByPrioritet(prioritet.Row, prioritet.Column);
                                        fullDrp[checkingPos.Row, checkingPos.Column].Weight    = 2;
                                        isChanged = true;
                                        beamsBCurrentPos[beamNum] = checkingPos;
                                        break;
                                    }
                                    else if (fullDrp[checkingPos.Row, checkingPos.Column].isArrow && fullDrp[checkingPos.Row, checkingPos.Column].Weight == 1)
                                    {
                                        isChanged          = true;
                                        collisionPosBeamsB = currPos;
                                        collisionPosBeamsA = checkingPos;
                                        beamNum            = 228;
                                        break;
                                    }
                                }
                            }
                        }
                        if (!isOptimized)
                        {
                            log.Add(new StepTracingLog(boards, $"Проведены лучи на 1 шаг {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле. Точек пересечения не найдено. Продолжаем."));
                        }
                    } while (collisionPosBeamsA == null && isChanged == true);

                    if (isChanged == false)
                    {
                        for (int i = 0; i < currentDRP.RowsCount; i++)
                        {
                            for (int j = 0; j < currentDRP.ColsCount; j++)
                            {
                                currentDRP[i, j] = new Cell();
                            }
                        }
                        // оставляем только 2 контакта, которые должны быть соеденены
                        currentDRP[startPos.Row, startPos.Column].State = CellState.Contact;
                        currentDRP[endPos.Row, endPos.Column].State     = CellState.Contact;
                        log.Add(new StepTracingLog(boards, $"Невозможно выполнить трассировку {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле. Все лучи упёрлись в препятствие и не пересеклись."));
                        continue;
                    }
                    else
                    {
                        if (isOptimized)
                        {
                            log.Add(new StepTracingLog(boards, $"Лучи пересеклись при трассировке {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле"));
                        }
                    }

                    var currentPos = collisionPosBeamsA;

                    do
                    {
                        var bufCellState = currentDRP[currentPos.Row, currentPos.Column].State;

                        currentDRP[currentPos.Row, currentPos.Column].State  = CellState.Wire;
                        currentDRP[currentPos.Row, currentPos.Column].Weight = -1;

                        currentPos = getNextPosByCurrentArrow(currentPos, bufCellState);
                    } while (currentDRP[currentPos.Row, currentPos.Column].State != CellState.PointA);


                    currentPos = collisionPosBeamsB;

                    do
                    {
                        var bufCellState = currentDRP[currentPos.Row, currentPos.Column].State;

                        currentDRP[currentPos.Row, currentPos.Column].State  = CellState.Wire;
                        currentDRP[currentPos.Row, currentPos.Column].Weight = -1;

                        currentPos = getNextPosByCurrentArrow(currentPos, bufCellState);
                    } while (currentDRP[currentPos.Row, currentPos.Column].State != CellState.PointB);


                    // очищаем всё дрп от стрелочек
                    for (int i = 0; i < currentDRP.RowsCount; i++)
                    {
                        for (int j = 0; j < currentDRP.ColsCount; j++)
                        {
                            if (currentDRP[i, j].isArrow)
                            {
                                currentDRP[i, j].State  = CellState.Empty;
                                currentDRP[i, j].Weight = -1;
                            }
                        }
                    }

                    log.Add(new StepTracingLog(boards, $"Определяем точки, где будет проходить проводник №{boardDRPs.Count - 1} в {boardNum + 1} узле"));

                    for (int i = 0; i < currentDRP.RowsCount; i++)
                    {
                        for (int j = 0; j < currentDRP.ColsCount; j++)
                        {
                            // объявляем соседей, от них нам нужно будет только состояние
                            Cell leftCell   = new Cell();
                            Cell rightCell  = new Cell();
                            Cell topCell    = new Cell();
                            Cell bottomCell = new Cell();

                            // блок, который присвоит пустое состояние ячейке, если она находится вне дрп, если находится в дрп, то присвоит нужную позицию
                            if (j > 0)
                            {
                                leftCell = currentDRP[i, j - 1];
                            }
                            else
                            {
                                leftCell.State = CellState.Empty;
                            }

                            if (j < currentDRP.ColsCount - 1)
                            {
                                rightCell = currentDRP[i, j + 1];
                            }
                            else
                            {
                                rightCell.State = CellState.Empty;
                            }

                            if (i > 0)
                            {
                                topCell = currentDRP[i - 1, j];
                            }
                            else
                            {
                                topCell.State = CellState.Empty;
                            }

                            if (i < currentDRP.RowsCount - 1)
                            {
                                bottomCell = currentDRP[i + 1, j];
                            }
                            else
                            {
                                bottomCell.State = CellState.Empty;
                            }
                            // конец блока

                            var currentCell = currentDRP[i, j];

                            // если текущая ячейка должна быть каким-то кабелем
                            // определяем значения ячеек вокруг и на основе этих данных узнаём какой имеено должен быть кабель
                            // идущим вертикально или слева вверх или горизонтальным и т.д.
                            if (currentCell.State == CellState.Wire)
                            {
                                // если есть кабель сверху и кабель в ячейке снизу, то в текущей ячейке должен стоять вертикальный проводник
                                if (topCell.isConnectible && bottomCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireVertical;
                                } // и т.д. для остальных видов проводника
                                else if (leftCell.isConnectible && rightCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireHorizontal;
                                }
                                else if (topCell.isConnectible && leftCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireTopLeft;
                                }
                                else if (topCell.isConnectible && rightCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireTopRight;
                                }
                                else if (bottomCell.isConnectible && leftCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireBottomLeft;
                                }
                                else if (bottomCell.isConnectible && rightCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireBottomRight;
                                }
                            }
                        }
                    }

                    // заменяем буквы просто контактами
                    currentDRP[startPos.Row, startPos.Column].State = CellState.Contact;
                    currentDRP[endPos.Row, endPos.Column].State     = CellState.Contact;
                    log.Add(new StepTracingLog(boards, $"Построили на базе точек проводник №{boardDRPs.Count - 1} в {boardNum + 1} узле"));
                }
            }

            return(log);
        }
        private List <StepCompositionLog> DoComposition()
        {
            var steps = new List <StepCompositionLog>();

            string err_msg = "";

            switch (ComboBox_Method.SelectedIndex)
            {
            case 0:
                steps = PosledGypergraph.Compose(tbCountOfElements.Value ?? 10, tbLimitsOfWires.Value ?? 100, out err_msg);
                break;

            case 1:
                steps = PosledMultigraph.Compose(tbCountOfElements.Value ?? 10, tbLimitsOfWires.Value ?? 100, out err_msg);
                break;

            case 2:
                steps = IterGypergraph.Compose(out err_msg);
                break;

            case 3:
                steps = IterMultigraphNew.Compose(out err_msg);
                break;

            case 4:
                steps = TestComposition.Compose(tbCountOfElements.Value ?? 10, tbLimitsOfWires.Value ?? 100, out err_msg);
                break;
            }

            // если не было ошибки - сериализуем результат
            if (err_msg == "")
            {
                if (steps.Count != 0)
                {
                    var result = new CompositionResult();
                    result.BoardsElements = steps.Last().BoardsList;

                    var sch = ApplicationData.ReadScheme(out err_msg);

                    if (err_msg != "")
                    {
                        MessageBox.Show(err_msg, "Revolution CAD", MessageBoxButton.OK, MessageBoxImage.Error);
                        return(null);
                    }

                    result.CreateBoardsWires(sch, out err_msg);

                    if (err_msg != "")
                    {
                        MessageBox.Show(err_msg, "Revolution CAD", MessageBoxButton.OK, MessageBoxImage.Error);
                        return(null);
                    }

                    // формируем новую матрицу R на основе сформированных проводов, которые были разделены по платам
                    result.MatrixR_AfterComposition = ApplicationData.CreateMatrixR(result.BoardsWires, sch.MatrixR.RowsCount, sch.MatrixR.ColsCount);

                    ApplicationData.WriteComposition(result, out err_msg);

                    if (err_msg != "")
                    {
                        MessageBox.Show(err_msg, "Revolution CAD", MessageBoxButton.OK, MessageBoxImage.Error);
                        return(null);
                    }

                    string msg;
                    if (ApplicationData.IsFileExists(".plc", out msg))
                    {
                        File.Delete($"{ApplicationData.FileName}.plc");
                    }

                    if (ApplicationData.IsFileExists(".trs", out msg))
                    {
                        File.Delete($"{ApplicationData.FileName}.trs");
                    }

                    if (ApplicationData.IsFileExists(".lay", out msg))
                    {
                        File.Delete($"{ApplicationData.FileName}.lay");
                    }

                    mw.MatrControl.UpdateMatrices();
                    mw.PlaceControl.Update();
                    mw.TraceControl.Update();
                    mw.LayerControl.Update();
                }
            }
            if (err_msg != "")
            {
                MessageBox.Show(err_msg, "Revolution CAD", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return(steps);
        }
Beispiel #44
0
 void EndingAfterMiddleBoss()
 {
     EndingAfterBoss(ApplicationData.GetLocaleText(LocaleType.MiddleEndingAfterBoss));
 }
Beispiel #45
0
        /// <summary>
        /// Initializes a new instance of the SettingsViewModel class.
        /// </summary>
        public SettingsViewModel(ApplicationData applicationData)
        {
            _applicationData = applicationData;

            Init();
        }
Beispiel #46
0
        private IDictionary <string, string> GetTextLocalizedData(ApplicationData application, string language,
                                                                  CultureInfo culture)
        {
            var state        = _states.Get(language, application.StateId).Select(x => x.Value).FirstOrDefault();
            var countryName  = _countries.All(language).First(x => x.Id == application.CountryId).Name;
            var cityName     = _cities.All(language).First(x => x.Id == application.TransitCityId).Name;
            var value        = LocalizationHelper.GetValueString(application.Value, application.CurrencyId, culture);
            var deliveryBill = _files.GetNames(application.Id, ApplicationFileType.DeliveryBill).Select(x => x.Name).ToArray();
            var invoice      = _files.GetNames(application.Id, ApplicationFileType.Invoice).Select(x => x.Name).ToArray();
            var packing      = _files.GetNames(application.Id, ApplicationFileType.Packing).Select(x => x.Name).ToArray();
            var swift        = _files.GetNames(application.Id, ApplicationFileType.Swift).Select(x => x.Name).ToArray();
            var torg12       = _files.GetNames(application.Id, ApplicationFileType.Torg12).Select(x => x.Name).ToArray();
            var t1           = _files.GetNames(application.Id, ApplicationFileType.T1).Select(x => x.Name).ToArray();
            var ex1          = _files.GetNames(application.Id, ApplicationFileType.Ex1).Select(x => x.Name).ToArray();

            var localizedData = new Dictionary <string, string>();

            Add(localizedData, "AddressLoad", application.AddressLoad);
            Add(localizedData, "FactoryName", application.FactoryName);
            Add(localizedData, "Id", application.Id.ToString(culture));
            Add(localizedData, "Count", application.Count.HasValue ? application.Count.Value.ToString(culture) : null);
            Add(localizedData, "MarkName", application.MarkName);
            Add(localizedData, "Invoice", application.Invoice);
            Add(localizedData, "CountryName", countryName);
            Add(localizedData, "CreationTimestamp", LocalizationHelper.GetDate(application.CreationTimestamp, culture));
            Add(localizedData, "Value", value);
            Add(localizedData, "Weight", application.Weight.HasValue ? application.Weight.Value.ToString(culture) : null);
            Add(localizedData, "AirWaybill", application.AirWaybill);
            Add(localizedData, "AirWaybillDateOfArrival",
                LocalizationHelper.GetDate(application.AirWaybillDateOfArrival, culture));
            Add(localizedData, "AirWaybillDateOfDeparture",
                LocalizationHelper.GetDate(application.AirWaybillDateOfDeparture, culture));
            Add(localizedData, "AirWaybillGTD", application.AirWaybillGTD);
            Add(localizedData, "Characteristic", application.Characteristic);
            Add(localizedData, "ClientNic", application.ClientNic);
            Add(localizedData, "DateOfCargoReceipt", LocalizationHelper.GetDate(application.DateOfCargoReceipt, culture));
            Add(localizedData, "DaysInWork", application.GetDaysInWork().ToString(culture));
            Add(localizedData, "DeliveryBillFiles", string.Join(", ", deliveryBill));
            Add(localizedData, "DeliveryType", LocalizationHelper.GetDeliveryType(application.TransitDeliveryType, culture));
            Add(localizedData, "DisplayNumber", application.GetApplicationDisplay());
            Add(localizedData, "FactoryContact", application.FactoryContact);
            Add(localizedData, "FactoryEmail", application.FactoryEmail);
            Add(localizedData, "FactoryPhone", application.FactoryPhone);
            Add(localizedData, "InvoiceFiles", string.Join(", ", invoice));
            Add(localizedData, "LegalEntity", application.ClientLegalEntity);
            Add(localizedData, "Pickup",
                application.IsPickup
                                                ? Tracker.Core.Resources.Entities.ResourceManager.GetString("Pickup", culture)
                                                : "");
            Add(localizedData, "MethodOfDelivery", LocalizationHelper.GetMethodOfDelivery(application.MethodOfDelivery, culture));
            Add(localizedData, "MethodOfTransit",
                LocalizationHelper.GetMethodOfTransit(application.TransitMethodOfTransit, culture));
            Add(localizedData, "PackingFiles", string.Join(", ", packing));
            Add(localizedData, "StateChangeTimestamp", LocalizationHelper.GetDate(application.StateChangeTimestamp, culture));
            Add(localizedData, "StateName", state != null ? state.LocalizedName : null);
            Add(localizedData, "SwiftFiles", string.Join(", ", swift));
            Add(localizedData, "TermsOfDelivery", application.TermsOfDelivery);
            Add(localizedData, "Torg12Files", string.Join(", ", torg12));
            Add(localizedData, "T1Files", string.Join(", ", t1));
            Add(localizedData, "Ex1Files", string.Join(", ", ex1));
            Add(localizedData, "TransitAddress", application.TransitAddress);
            Add(localizedData, "CarrierName", application.CarrierName);
            Add(localizedData, "CarrierContact", application.CarrierContact);
            Add(localizedData, "CarrierAddress", application.CarrierAddress);
            Add(localizedData, "CarrierPhone", application.CarrierPhone);
            Add(localizedData, "CarrierEmail", application.CarrierEmail);
            Add(localizedData, "TransitCity", cityName);
            Add(localizedData, "TransitPhone", application.TransitPhone);
            Add(localizedData, "TransitRecipientName", application.TransitRecipientName);
            Add(localizedData, "TransitReference", application.TransitReference);
            Add(localizedData, "TransitWarehouseWorkingTime", application.TransitWarehouseWorkingTime);
            Add(localizedData, "Volume", application.Volume.ToString("N2", culture));
            Add(localizedData, "WarehouseWorkingTime", application.WarehouseWorkingTime);
            Add(localizedData, "SenderName", application.SenderName);
            Add(localizedData, "SenderContact", application.SenderContact);
            Add(localizedData, "SenderPhone", application.SenderPhone);
            Add(localizedData, "SenderAddress", application.SenderAddress);
            Add(localizedData, "SenderEmail", application.SenderEmail);
            Add(localizedData, "ForwarderName", application.ForwarderName);
            Add(localizedData, "CountInInvoce", application.CountInInvoce.ToString());
            Add(localizedData, "DocumentWeight", application.DocumentWeight.ToString());
            Add(localizedData, "MRN", application.MRN);

            return(localizedData);
        }
Beispiel #47
0
 private void RoamingDataChanged(ApplicationData sender, object args)
 {
     LoadRoamingSettings();
     instance.OnSettingsChanged();
 }
Beispiel #48
0
        /// <summary>
        /// Метод для трассировки
        /// </summary>
        /// <returns>Список логов шагов</returns>
        public static List <StepTracingLog> Trace(Scheme sch, PlacementResult plc, bool isOptimized, out string err)
        {
            // обязательно создаём лог действий
            var log = new List <StepTracingLog>();

            // при возникновении критической ошибки её нужно занести в эту переменную и сделать return null
            err = "";

            // формируем список плат, в котором хранится список слоёв (для каждого проводника свой слой ДРП)
            var boards = new List <List <Matrix <Cell> > >();

            // считываем список плат, в каждой плате хранится список проводников (Wire) соединяют всего 2 контакта
            List <List <Wire> > boardsWiresPositions = plc.BoardsWiresPositions;

            // запускаем цикл по платам
            for (int boardNum = 0; boardNum < boardsWiresPositions.Count; boardNum++)
            {
                // получаем список проводов, которые необходимо развести на этой плате
                // элемент списка объект класса Wire, который хранит координаты точки А и Б на ДРП
                var boardWiresPositions = boardsWiresPositions[boardNum];

                // список ДРП текущей платы, в который будет заносится ДРП для каждого провода
                var boardDRPs = new List <Matrix <Cell> >();

                // добавляем этот список в список всех плат
                boards.Add(boardDRPs);

                // первым слоем будет являтся ДРП на котором просто отмечены места контактов платы
                boardDRPs.Add(plc.BoardsDRPs[boardNum]);

                // запускаем цикл по проводам
                foreach (var wire in boardWiresPositions)
                {
                    // ДРП для провода формируем на основе шаблона ДРП, на котором просто отмечены контакты. Оно уже имеет необходимые размеры.
                    var currentDRP = new Matrix <Cell>(plc.BoardsDRPs[boardNum].RowsCount, plc.BoardsDRPs[boardNum].ColsCount);

                    // добавляем это ДРП в список ДРП платы
                    boardDRPs.Add(currentDRP);

                    // заполняем ДРП пустыми ячейками
                    for (int i = 0; i < currentDRP.RowsCount; i++)
                    {
                        for (int j = 0; j < currentDRP.ColsCount; j++)
                        {
                            currentDRP[i, j] = new Cell();
                        }
                    }

                    // дрп, в котором будут объединены все слои с проводами (для определения гдле занята ячейка - где нет)
                    Matrix <Cell> fullDrp;

                    // получаем из провода стартовую и конечную позицию
                    var startPos = wire.A.PositionContact;
                    var endPos   = wire.B.PositionContact;

                    // помечаем буквами стартовую и конечную позицию на текущем слое провода
                    currentDRP[startPos.Row, startPos.Column].State = CellState.PointA;
                    currentDRP[endPos.Row, endPos.Column].State     = CellState.PointB;

                    log.Add(new StepTracingLog(boards, $"Начинаем трассировку {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле"));

                    int currentWeight = 0;

                    // у начальной позиции вес 0
                    currentDRP[startPos.Row, startPos.Column].Weight = currentWeight;

                    // объединяем все слои
                    fullDrp = ApplicationData.MergeLayersDRPs(boardDRPs);

                    // и получаем незанятых соседей для начальной точки
                    var neighbors = getNeighbors(fullDrp, startPos);

                    // запускаем цикл пока не будет найдено ни одного незанятого соседа или в списке соседей окажется точка Б
                    do
                    {
                        // увеличиваем вес
                        currentWeight = (currentWeight + 1) % 3;

                        // запускаем цикл по всем незанятым соседним ячейкам
                        foreach (var neighbor in neighbors)
                        {
                            // распространяем волну
                            currentDRP[neighbor.Row, neighbor.Column].Weight = currentWeight;
                            currentDRP[neighbor.Row, neighbor.Column].State  = CellState.Wave;
                            fullDrp[neighbor.Row, neighbor.Column].Weight    = currentWeight;
                            fullDrp[neighbor.Row, neighbor.Column].State     = CellState.Wave;
                        }

                        if (!isOptimized)
                        {
                            log.Add(new StepTracingLog(boards, $"Распроcтраняем волну с весом {currentWeight} для {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле"));
                        }


                        // и получаем список незанятых соседей для ячеек текущей волны
                        neighbors = getNeighbors(fullDrp, neighbors);
                    } while (!neighbors.Any(x => x.Equals(endPos)) && neighbors.Count > 0);

                    // если незанятых соседей не оказалось, значит трассировка невозможна
                    if (neighbors.Count == 0)
                    {
                        // очищаем текущее дрп
                        for (int i = 0; i < currentDRP.RowsCount; i++)
                        {
                            for (int j = 0; j < currentDRP.ColsCount; j++)
                            {
                                if (currentDRP[i, j].State == CellState.Wave)
                                {
                                    currentDRP[i, j].State = CellState.Empty;
                                }
                                currentDRP[i, j].Weight = -1;
                            }
                        }
                        // оставляем только 2 контакта, которые должны быть соеденены
                        currentDRP[startPos.Row, startPos.Column].State = CellState.Contact;
                        currentDRP[endPos.Row, endPos.Column].State     = CellState.Contact;
                        log.Add(new StepTracingLog(boards, $"Невозможно выполнить трассировку {boardDRPs.Count - 1}-го проводника в {boardNum + 1} узле"));
                        continue;
                    }

                    if (isOptimized)
                    {
                        log.Add(new StepTracingLog(boards, $"Волна {boardDRPs.Count - 1}-го проводника достигла точки Б в {boardNum + 1} узле"));
                    }


                    // теперь начинаем обратный крестовый поход от точки Б
                    neighbors = new List <Position>();
                    neighbors.Add(endPos);

                    Position currentPos = endPos.Clone();
                    fullDrp = ApplicationData.MergeLayersDRPs(boardDRPs);
                    do
                    {
                        foreach (var neighbor in neighbors)
                        {
                            // находим в списке соседей первую ячейку с волной необходимого веса
                            if (currentDRP[neighbor.Row, neighbor.Column].Weight == currentWeight)
                            {
                                // помечаем что в этой ячейке будет находится проводник, но какой имеено определим ниже
                                currentDRP[neighbor.Row, neighbor.Column].State = CellState.Wire;
                                fullDrp[neighbor.Row, neighbor.Column].State    = CellState.Wire;
                                currentPos = neighbor.Clone();
                                break;
                            }
                        }

                        // на каждом шаге уменьшаем вес
                        currentWeight = (currentWeight + 2) % 3;
                        // и получаем список волновых соседей
                        neighbors = getNeighborsOnlyWave(fullDrp, currentPos);
                    } while (!neighbors.Any(x => x.Equals(startPos)));

                    // очищаем всё дрп от веса и ячеек с волной
                    for (int i = 0; i < currentDRP.RowsCount; i++)
                    {
                        for (int j = 0; j < currentDRP.ColsCount; j++)
                        {
                            currentDRP[i, j].Weight = -1;
                            if (currentDRP[i, j].State == CellState.Wave)
                            {
                                currentDRP[i, j].State = CellState.Empty;
                            }
                        }
                    }

                    log.Add(new StepTracingLog(boards, $"Волна достигла точки Б. Определяем точки, где будет проходить проводник №{boardDRPs.Count - 1} в {boardNum + 1} узле"));

                    // начинаем долгую и мучительную спец операцию по определению какой формы проводник должен стоять в ячейке
                    // запускаем цикл по всем ячейкам дрп
                    for (int i = 0; i < currentDRP.RowsCount; i++)
                    {
                        for (int j = 0; j < currentDRP.ColsCount; j++)
                        {
                            // объявляем соседей, от них нам нужно будет только состояние
                            Cell leftCell   = new Cell();
                            Cell rightCell  = new Cell();
                            Cell topCell    = new Cell();
                            Cell bottomCell = new Cell();

                            // блок, который присвоит пустое состояние ячейке, если она находится вне дрп, если находится в дрп, то присвоит нужную позицию
                            if (j > 0)
                            {
                                leftCell = currentDRP[i, j - 1];
                            }
                            else
                            {
                                leftCell.State = CellState.Empty;
                            }

                            if (j < currentDRP.ColsCount - 1)
                            {
                                rightCell = currentDRP[i, j + 1];
                            }
                            else
                            {
                                rightCell.State = CellState.Empty;
                            }

                            if (i > 0)
                            {
                                topCell = currentDRP[i - 1, j];
                            }
                            else
                            {
                                topCell.State = CellState.Empty;
                            }

                            if (i < currentDRP.RowsCount - 1)
                            {
                                bottomCell = currentDRP[i + 1, j];
                            }
                            else
                            {
                                bottomCell.State = CellState.Empty;
                            }
                            // конец блока

                            var currentCell = currentDRP[i, j];

                            // если текущая ячейка должна быть каким-то кабелем
                            // определяем значения ячеек вокруг и на основе этих данных узнаём какой имеено должен быть кабель
                            // идущим вертикально или слева вверх или горизонтальным и т.д.
                            if (currentCell.State == CellState.Wire)
                            {
                                // если есть кабель сверху и кабель в ячейке снизу, то в текущей ячейке должен стоять вертикальный проводник
                                if (topCell.isConnectible && bottomCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireVertical;
                                }
                                else if (leftCell.isConnectible && rightCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireHorizontal;
                                }
                                else if (topCell.isConnectible && leftCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireTopLeft;
                                }
                                else if (topCell.isConnectible && rightCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireTopRight;
                                }
                                else if (bottomCell.isConnectible && leftCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireBottomLeft;
                                }
                                else if (bottomCell.isConnectible && rightCell.isConnectible)
                                {
                                    currentDRP[i, j].State = CellState.WireBottomRight;
                                }
                            }
                        }
                    }

                    // заменяем буквы просто контактами
                    currentDRP[startPos.Row, startPos.Column].State = CellState.Contact;
                    currentDRP[endPos.Row, endPos.Column].State     = CellState.Contact;
                    log.Add(new StepTracingLog(boards, $"Построили на базе точек проводник №{boardDRPs.Count - 1} в {boardNum + 1} узле"));
                }
            }
            return(log);
        }
 public ApplicationDataStorageHelper(ApplicationData appData, Toolkit.Helpers.IObjectSerializer?objectSerializer = null)
 {
     AppData    = appData ?? throw new ArgumentNullException(nameof(appData));
     Serializer = objectSerializer ?? new Toolkit.Helpers.SystemSerializer();
 }
Beispiel #50
0
    void Start()
    {
        ready       = false;
        menuvisible = false;
        //メソッドポインタ初期化
        actions = new userAction[] { moveToMapMode, moveTo3DMode, changeEclipseData, setCurrentLocation, setMapPoint, moveToCalibration, showHelpMessage };

        //時計
        clock = gameObject.GetComponent <Clock>();
        //選択クラス
        chooser = gameObject.GetComponent <EclipseDataChooser>();
        //地点の選択
        pointchooser = gameObject.GetComponent <ARPointChooser>();
        //画像の読み込み
        images = new Texture2D[imagepaths.Length];
        foreach (string path in imagepaths)
        {
            StartCoroutine("getTextureAsset", path);
        }
        //数字の読み込み
        numbers = new Texture2D[10];
        for (int i = 0; i < 10; i++)
        {
            StartCoroutine("getTextureAsset", "numero/" + i.ToString() + ".png");
        }
        //誘導サインを読み込む
        signboards = new Texture2D[signboardpaths.Length];
        for (int i = 0; i < signboardpaths.Length; i++)
        {
            StartCoroutine("getTextureAsset", signboardpaths[i]);
        }

        //点滅
        blink = true;

        //表示位置格納用Rect
        sunrect = new Rect();
        //カメラ
        maincam = Camera.main;
        //データから読みだした天体の位置格納用配列
        posdata = new double[7];

        //デバイスの回転の保存用
        camrotation = Quaternion.identity;

        //カメラ画像を表示するクラス
        GameObject quad = GameObject.Find("Quad");

        camview = quad.GetComponent <CameraView>();
        //アプリケーションの保存してあるデータ
        appdata = ApplicationData.getApplicationData(); horizontalFOV = appdata.HorizontalAngle;


        //画角の読み込み
        //キャリブレーションが実行された後
        if (Calibration.calibrated)
        {
            horizontalFOV           = Calibration.horizontal;
            verticalFOV             = Calibration.vertical;
            calibrated_orientation  = (int)Calibration.deviceOrientation;
            appdata.HorizontalAngle = horizontalFOV;
            appdata.VerticalAngle   = verticalFOV;
            appdata.Orientation     = calibrated_orientation;
            appdata.saveApplicationData();
            calibrated = true;
        }
        else
        {
            horizontalFOV          = appdata.HorizontalAngle;
            verticalFOV            = appdata.VerticalAngle;
            calibrated_orientation = appdata.Orientation;

            if (horizontalFOV == 0.0f | verticalFOV == 0.0f)
            {
                calibrated = false;
            }
            else
            {
                calibrated = true;
            }
        }

        //観測地点読み込み
        locationmode = MAP_LOCATION;
        longitude    = appdata.ARLongitude;
        latitude     = appdata.ARLatitude;

        Input.gyro.enabled = true;
        Input.location.Start();
        Input.compass.enabled = true;

        initFromEclipseDataHolder();
        //initEclipseData("20300601.json");
        //StartCoroutine("initEclipseDataFromAssetBundle", "20300601.json");

        //初回のヘルプ表示は終わっているか
        if (!appdata.hasARHelpShown)
        {
            showHelpMessage();
            appdata.hasARHelpShown = true;
            appdata.saveApplicationData();
        }
    }
Beispiel #51
0
 private void RoamingApplicationDataChanged(ApplicationData sender, object args)
 {
     RaisePropertyChanged(string.Empty);
 }
Beispiel #52
0
 public static bool IsRoamingStorageAvailable(this ApplicationData appData)
 {
     return(appData.RoamingStorageQuota == 0);
 }
Beispiel #53
0
 /// <summary>
 /// This constructor is for design purposes only.
 /// </summary>
 public SettingsViewModel()
 {
     _applicationData = new ApplicationData();
 }
        // field: {"Name":"something","Path":"/something","IsMultiValue":true,"Semantics":[],"Fields":[]}
        private string BuildFieldJson(XmlNode fieldNode, string parentPath, string typeOf, XmlNamespaceManager nsmgr)
        {
            string        name           = fieldNode.Attributes["name"].Value;
            string        path           = parentPath + "/" + name;
            string        fieldTypeOf    = typeOf;
            StringBuilder fieldSemantics = new StringBuilder();

            // if maxOccurs is anything else than 1, it is a multi value field
            bool isMultiValue = !fieldNode.Attributes["maxOccurs"].Value.Equals("1");

            // read semantic mapping from field so we can append it to the schema typeof
            XmlNode typeOfNode = fieldNode.SelectSingleNode("xsd:annotation/xsd:appinfo/tcm:ExtensionXml/mapping:typeof", nsmgr);

            if (typeOfNode != null)
            {
                fieldTypeOf = typeOf + "," + typeOfNode.InnerText;
            }

            // use field xml name as initial semantic mapping for field
            string property = String.Format("{0}:{1}", DefaultVocabularyPrefix, fieldNode.Attributes["name"].Value);

            // read semantic mapping from field and append if available
            XmlNode propertyNode = fieldNode.SelectSingleNode("xsd:annotation/xsd:appinfo/tcm:ExtensionXml/mapping:property", nsmgr);

            if (propertyNode != null)
            {
                property += "," + propertyNode.InnerText;
            }
            fieldSemantics.Append(BuildFieldSemanticsJson(property, fieldTypeOf));

            // handle embedded fields
            StringBuilder embeddedFields     = new StringBuilder();
            XmlNode       embeddedSchemaNode = fieldNode.SelectSingleNode("xsd:annotation/xsd:appinfo/tcm:EmbeddedSchema", nsmgr);

            if (embeddedSchemaNode != null)
            {
                string uri            = embeddedSchemaNode.Attributes["href", Constants.XlinkNamespace].Value;
                Schema embeddedSchema = (Schema)Engine.GetObject(uri);
                string embeddedTypeOf = String.Format("{0}:{1}", DefaultVocabularyPrefix, embeddedSchema.RootElementName);

                // append schema typeof from appdata for embedded schemas
                ApplicationData appData = embeddedSchema.LoadApplicationData(TypeOfAppDataId);
                if (appData != null)
                {
                    embeddedTypeOf += "," + Encoding.Unicode.GetString(appData.Data);
                }

                embeddedFields.Append(BuildSchemaFieldsJson(embeddedSchema, path, embeddedTypeOf, nsmgr, true));
            }

            // TODO: handle link fields
            //XmlAttribute typeAttribute = fieldNode.Attributes["type"];
            //if (typeAttribute != null)
            //{
            //    bool isSimpleLink = typeAttribute.Value.Equals("tcmi:SimpleLink");
            //    XmlNode allowedTargetSchemasNode = fieldNode.SelectSingleNode("xsd:annotation/xsd:appinfo/tcm:AllowedTargetSchemas", nsmgr);
            //    if (allowedTargetSchemasNode != null)
            //    {
            //        foreach (XmlNode allowedTargetSchemaNode in allowedTargetSchemasNode.SelectNodes("tcm:TargetSchema", nsmgr))
            //        {
            //            string uri = allowedTargetSchemaNode.Attributes["href", "http://www.w3.org/1999/xlink"].Value;
            //            Schema allowedTargetSchema = (Schema)MEngine.GetObject(uri);
            //
            //        }
            //    }
            //    else
            //    {
            //        // if there are no allowed target schemas, all schemas are allowed...
            //    }
            //}
            //else
            //{
            //    // if there is no type attribute, it is not a simple type so look for <xsd:complexType> inside the element
            //}

            return(String.Format("{{\"Name\":{0},\"Path\":{1},\"IsMultiValue\":{2},\"Semantics\":[{3}],\"Fields\":[{4}]}}", JsonEncode(name), JsonEncode(path), JsonEncode(isMultiValue), fieldSemantics, embeddedFields));
        }
Beispiel #55
0
 public HomeController(ApplicationData applicationData)
 {
     _applicationData = applicationData;
 }
        private Dictionary <string, List <string> > ReadMappingsData()
        {
            bool containsDefaultVocabulary = false;

            // generate a list of vocabulary prefix and name from appdata
            Dictionary <string, List <string> > res = new Dictionary <string, List <string> > {
                { VocabulariesConfigName, new List <string>() }
            };
            ApplicationData globalAppData = Engine.GetSession().SystemManager.LoadGlobalApplicationData(VocabulariesAppDataId);

            if (globalAppData != null)
            {
                XElement vocabulariesXml = XElement.Parse(Encoding.Unicode.GetString(globalAppData.Data));
                foreach (XElement vocabulary in vocabulariesXml.Elements())
                {
                    string prefix = vocabulary.Attribute("prefix").Value;
                    res[VocabulariesConfigName].Add(String.Format("{{\"Prefix\":{0},\"Vocab\":{1}}}", JsonEncode(prefix), JsonEncode(vocabulary.Attribute("name").Value)));
                    if (prefix.Equals(DefaultVocabularyPrefix))
                    {
                        containsDefaultVocabulary = true;
                    }
                }
            }
            // add default vocabulary if it is not there already
            if (!containsDefaultVocabulary)
            {
                res[VocabulariesConfigName].Add(String.Format("{{\"Prefix\":{0},\"Vocab\":{1}}}", JsonEncode(DefaultVocabularyPrefix), JsonEncode(DefaultVocabulary)));
            }

            // generate a list of schema + id, separated by module
            RepositoryItemsFilter schemaFilter = new RepositoryItemsFilter(Engine.GetSession())
            {
                Recursive = true,
                ItemTypes = new [] { ItemType.Schema },
                // NOTE: including SchemaPurpose.Metadata for Page Metadata
                SchemaPurposes = new [] { SchemaPurpose.Component, SchemaPurpose.Multimedia, SchemaPurpose.Metadata },
                BaseColumns    = ListBaseColumns.Extended
            };

            res.Add(SchemasConfigName, new List <string>());
            foreach (Schema schema in GetPublication().GetItems(schemaFilter).Cast <Schema>())
            {
                string rootElementName = schema.RootElementName;
                if (String.IsNullOrEmpty(rootElementName))
                {
                    // multimedia/metadata schemas don't have a root element name, so lets use its title without any invalid characters
                    rootElementName = Regex.Replace(schema.Title.Trim(), InvalidCharactersPattern, String.Empty);
                }
                // add schema typeof using tridion standard implementation vocabulary prefix
                string        typeOf          = String.Format("{0}:{1}", DefaultVocabularyPrefix, rootElementName);
                StringBuilder schemaSemantics = new StringBuilder();
                // append schema typeof from appdata
                ApplicationData appData = schema.LoadApplicationData(TypeOfAppDataId);
                if (appData != null)
                {
                    typeOf += "," + ExtractTypeOfAppData(appData);
                }
                schemaSemantics.Append(BuildSchemaSemanticsJson(typeOf));

                // TODO: serialize schema fields xml to json in a smart way
                // field: {"Name":"something","Path":"/something","IsMultiValue":true,"Semantics":[],"Fields":[]}
                // field semantics: {"Prefix":"s","Entity";"Article","Property":"headline"}
                StringBuilder fields = new StringBuilder();

                // load namespace manager with schema namespaces
                XmlNamespaceManager nsmgr = SchemaNamespaceManager(schema.Xsd.OwnerDocument.NameTable);

                // build field elements from schema
                string path = "/" + rootElementName;
                fields.Append(BuildSchemaFieldsJson(schema, path, typeOf, nsmgr));

                res[SchemasConfigName].Add(String.Format("{{\"Id\":{0},\"RootElement\":{1},\"Fields\":[{2}],\"Semantics\":[{3}]}}", JsonEncode(schema.Id.ItemId), JsonEncode(rootElementName), fields, schemaSemantics));
            }

            // get region mappings for all templates
            Dictionary <string, List <string> > regions = BuildRegionMappings();

            res.Add(RegionConfigName, new List <string>());

            foreach (KeyValuePair <string, List <string> > region in regions)
            {
                StringBuilder allowedComponentTypes = new StringBuilder();
                bool          first = true;
                foreach (string componentType in region.Value)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        allowedComponentTypes.Append(",");
                    }
                    allowedComponentTypes.Append(componentType);
                }
                res[RegionConfigName].Add(String.Format("{{\"Region\":{0},\"ComponentTypes\":[{1}]}}", JsonEncode(region.Key), allowedComponentTypes));
            }

            return(res);
        }
Beispiel #57
0
        /// <summary>
        /// Initializes a new instance of the SettingsViewModel class.
        /// </summary>
        public ProcessesViewModel(ApplicationData applicationData)
        {
            _applicationData = applicationData;

            Init();
        }
Beispiel #58
0
        public bool Login()
        {
            string OAuthVerifier      = string.Empty;
            string OAuthenticityToken = string.Empty;
            string OAuthToken         = string.Empty;
            string PinToken           = string.Empty;
            string InviteUrl          = string.Empty;

            bool IsAccountCreated = false;

            try
            {
                string ts = GenerateTimeStamp();

                InviteUrl = "http://pinterest.com/invited/?email=" + PinEmail + "&invite=" + InviteCode;
                InviteUrl = "http://pinterest.com/invited/?invite=" + InviteCode;

                int intProxyPort = 80;
                if (ApplicationData.ValidateNumber(this.proxyPort))
                {
                    intProxyPort = int.Parse(this.proxyPort);
                }

                string TwitterPageContent = httpHelper.getHtmlfromUrlProxy(new Uri("https://twitter.com/"), "", this.proxyAddress, intProxyPort, this.proxyUsername, this.proxyPassword, this.userAgent);
                string BootPageContent    = httpHelper.getHtmlfromUrl(new Uri("https://twitter.com/account/bootstrap_data?r=0.9414130715097342"), "https://twitter.com/", "", this.userAgent);

                //string PostData = "session%5Busername_or_email%5D=" + TwitterUsername + "&session%5Bpassword%5D=" + TwitterPassword  + "&scribe_log=%5B%22%7B%5C%22event_name%5C%22%3A%5C%22web%3Afront%3Alogin_callout%3Aform%3A%3Alogin_click%5C%22%2C%5C%22noob_level%5C%22%3Anull%2C%5C%22internal_referer%5C%22%3Anull%2C%5C%22user_id%5C%22%3A0%2C%5C%22page%5C%22%3A%5C%22front%5C%22%2C%5C%22_category_%5C%22%3A%5C%22client_event%5C%22%2C%5C%22ts%5C%22%3A" + ts + "%7D%22%5D&redirect_after_login="******"https://twitter.com/sessions?phx=1"), PostData, "https://twitter.com/", "" , this.userAgent);

                //string ts = GenerateTimeStamp();
                string get_twitter_first = string.Empty;
                try
                {
                    get_twitter_first = httpHelper.getHtmlfromUrlProxy(new Uri("https://twitter.com/"), "", proxyAddress, 0, proxyUsername, proxyPassword, "");
                }
                catch (Exception ex)
                {
                    //string get_twitter_first = globusHttpHelper1.getHtmlfromUrlp(new Uri("http://twitter.com/"), string.Empty, string.Empty);
                    //Thread.Sleep(1000);
                    get_twitter_first = httpHelper.getHtmlfromUrlProxy(new Uri("https://twitter.com/"), "", proxyAddress, 0, proxyUsername, proxyPassword, "");
                }

                string postAuthenticityToken = "";

                int startIndx = get_twitter_first.IndexOf("postAuthenticityToken");
                if (startIndx > 0)
                {
                    int indexstart = startIndx + "postAuthenticityToken".Length + 3;
                    int endIndx    = get_twitter_first.IndexOf("\"", startIndx);

                    postAuthenticityToken = get_twitter_first.Substring(startIndx, endIndx - startIndx).Replace(",", "");

                    if (postAuthenticityToken.Contains("postAuthenticityToken"))
                    {
                        try
                        {
                            string[] getOuthentication = System.Text.RegularExpressions.Regex.Split(get_twitter_first, "\"postAuthenticityToken\":\"");
                            string[] authenticity      = System.Text.RegularExpressions.Regex.Split(getOuthentication[1], ",");

                            if (authenticity[0].IndexOf("\"") > 0)
                            {
                                int    indexStart1 = authenticity[0].IndexOf("\"");
                                string start       = authenticity[0].Substring(0, indexStart1);
                                postAuthenticityToken = start.Replace("\"", "").Replace(":", "");
                            }
                        }
                        catch { };
                    }
                }
                else
                {
                    string[] array = System.Text.RegularExpressions.Regex.Split(get_twitter_first, "<input type=\"hidden\"");
                    foreach (string item in array)
                    {
                        if (item.Contains("authenticity_token"))
                        {
                            int startindex = item.IndexOf("value=\"");
                            if (startindex > 0)
                            {
                                string start    = item.Substring(startindex).Replace("value=\"", "");
                                int    endIndex = start.IndexOf("\"");
                                string end      = start.Substring(0, endIndex);
                                postAuthenticityToken = end;
                                break;
                            }
                        }
                    }
                }

                string get_twitter_second = httpHelper.postFormData(new Uri("https://twitter.com/scribe"), "log%5B%5D=%7B%22event_name%22%3A%22web%3Amobile_gallery%3Agallery%3A%3A%3Aimpression%22%2C%22noob_level%22%3Anull%2C%22internal_referer%22%3Anull%2C%22context%22%3A%22mobile_gallery%22%2C%22event_info%22%3A%22mobile_app_download%22%2C%22user_id%22%3A0%2C%22page%22%3A%22mobile_gallery%22%2C%22_category_%22%3A%22client_event%22%2C%22ts%22%3A" + ts + "%7D", "https://twitter.com/?lang=en&logged_out=1#!/download", "", ""); //globusHttpHelper.getHtmlfromUrl(new Uri("https://twitter.com/account/bootstrap_data?r=0.21632839148912897"), "https://twitter.com/", string.Empty);

                string get2nd = httpHelper.getHtmlfromUrlProxy(new Uri("http://twitter.com/account/bootstrap_data?r=0.21632839148912897"), "https://twitter.com/", proxyAddress, 0, proxyUsername, proxyPassword, "");

                string get_api = httpHelper.getHtmlfromUrl(new Uri("http://api.twitter.com/receiver.html"), "https://twitter.com/", "", "");


                //Old postdata
                //string postData = "session%5Busername_or_email%5D=" + Username + "&session%5Bpassword%5D=" + Password + "&scribe_log=%5B%22%7B%5C%22event_name%5C%22%3A%5C%22web%3Afront%3Alogin_callout%3Aform%3A%3Alogin_click%5C%22%2C%5C%22noob_level%5C%22%3Anull%2C%5C%22internal_referer%5C%22%3Anull%2C%5C%22user_id%5C%22%3A0%2C%5C%22page%5C%22%3A%5C%22front%5C%22%2C%5C%22_category_%5C%22%3A%5C%22client_event%5C%22%2C%5C%22ts%5C%22%3A" + ts + "%7D%22%5D&redirect_after_login="******"session%5Busername_or_email%5D=" + TwitterUsername + "&session%5Bpassword%5D=" + TwitterPassword + "&scribe_log=&redirect_after_login=&authenticity_token=" + postAuthenticityToken + "";

                string response_Login = httpHelper.postFormData(new Uri("https://twitter.com/sessions"), postData, "https://twitter.com/", "", "");


                string AfterPostPageContent = httpHelper.getHtmlfromUrl(new Uri("https://twitter.com/"), "https://twitter.com/", "", this.userAgent);

                if (AfterPostPageContent.Contains("signout-button"))
                {
                    string InvitePageContent = httpHelper.getHtmlfromUrl(new Uri(InviteUrl), "", "", this.userAgent);

                    if (InvitePageContent.Contains("This invite code is not valid"))
                    {
                        IsAccountCreated = false;
                        Log("[ " + DateTime.Now + " ] => [ This invite code is not valid " + PinEmail + " ]");
                        return(IsAccountCreated);
                    }

                    string InvitedPageContent = httpHelper.getHtmlfromUrl(new Uri("http://pinterest.com/twitter/?invited=1"), InviteUrl, "", this.userAgent);

                    if (InvitedPageContent.Contains("Logout"))
                    {
                        IsAccountCreated = true;
                        Log("[ " + DateTime.Now + " ] => [ This twitter account allready added with pinterest " + TwitterUsername + " ]");
                        return(IsAccountCreated);
                    }

                    Uri ResponseUri = httpHelper.GetResponseData();


                    if (!string.IsNullOrEmpty(ResponseUri.OriginalString))
                    {
                        if (ResponseUri.OriginalString.Contains("verify_captcha/?"))
                        {
                            //List<string> lstData = GetCapctha();
                            //string challenge = string.Empty;
                            //string response = string.Empty;


                            //challenge = lstData[0].ToString();
                            //response = lstData[1].ToString();
                            //response = response.Replace(" ", "+");
                            //string postUrl = "http://pinterest.com/verify_captcha/?src=register&return=%2Fwelcome%2F";
                            //string postData = "challenge=" + challenge + "&response=" + response;

                            //string POstResponse = httpHelper.postFormData(new Uri(postUrl), postData, "", string.Empty);

                            //string pageSrcWelcome = httpHelper.getHtmlfromUrl(new Uri("http://pinterest.com/welcome/"), postUrl, "");
                        }
                        if (ResponseUri.OriginalString.Contains("http://pinterest.com/twitter/?oauth_token"))
                        {
                            OAuthVerifier = ResponseUri.OriginalString;

                            int    FirstPointToken     = InvitedPageContent.IndexOf("csrfmiddlewaretoken");
                            string FirstTokenSubString = InvitedPageContent.Substring(FirstPointToken);

                            int SecondPointToken = FirstTokenSubString.IndexOf("/>");
                            PinToken = FirstTokenSubString.Substring(0, SecondPointToken).Replace("csrfmiddlewaretoken", string.Empty).Replace("value=", string.Empty).Replace("'", string.Empty).Trim();
                        }
                        if (ResponseUri.OriginalString.Contains("api.twitter.com/oauth/authenticate?oauth_token="))
                        {
                            int FirstAuthenticityPoint = InvitedPageContent.IndexOf("authenticity_token\" type=\"hidden\"");

                            string FirstSubAuthenticity = InvitedPageContent.Substring(FirstAuthenticityPoint);
                            OAuthenticityToken = FirstSubAuthenticity.Substring(FirstSubAuthenticity.IndexOf("value="), (FirstSubAuthenticity.IndexOf("/></div>")) - (FirstSubAuthenticity.IndexOf("value="))).Replace("value=", string.Empty).Replace("\"", string.Empty).Trim();

                            OAuthToken = ResponseUri.OriginalString.Replace("https://api.twitter.com/oauth/authenticate?oauth_token=", string.Empty).Replace("http://api.twitter.com/oauth/authenticate?oauth_token=", string.Empty);

                            string AcceptPostData = "authenticity_token=" + OAuthenticityToken + "&oauth_token=" + OAuthToken;

                            string OauthUrl = "https://twitter.com/oauth/authenticate?oauth_token=" + OAuthToken;

                            string AcceptedPageContent = httpHelper.postFormData(new Uri("https://twitter.com/oauth/authenticate"), AcceptPostData, OauthUrl, string.Empty, this.userAgent);

                            int FirstOAuthVerifierPoint = AcceptedPageContent.IndexOf("http://pinterest.com/twitter/?oauth_token=");

                            string FirstSuboAuth = AcceptedPageContent.Substring(FirstOAuthVerifierPoint);

                            OAuthVerifier = FirstSuboAuth.Substring(0, FirstSuboAuth.IndexOf(">")).Replace("\"", string.Empty).Trim();//.Replace("&oauth_verifier=", string.Empty).Trim();

                            string PinterestRegistrationPageContent = httpHelper.getHtmlfromUrl(new Uri(OAuthVerifier), string.Empty, string.Empty, this.userAgent);

                            if (!PinterestRegistrationPageContent.Contains("Oops! We are having some issues talking to Twitter. Please try again later"))
                            {
                                int    FirstPointToken     = PinterestRegistrationPageContent.IndexOf("csrfmiddlewaretoken");
                                string FirstTokenSubString = PinterestRegistrationPageContent.Substring(FirstPointToken);

                                int SecondPointToken = FirstTokenSubString.IndexOf("/>");
                                PinToken = FirstTokenSubString.Substring(0, SecondPointToken).Replace("csrfmiddlewaretoken", string.Empty).Replace("value=", string.Empty).Replace("'", string.Empty).Trim();
                            }
                            else
                            {
                                Log("[ " + DateTime.Now + " ] => [ We are having some issues talking to Twitter. Please try again later ]");
                                return(false);
                            }
                        }


                        //Checking For User Name
                        string CheckUserNameUrl = "http://pinterest.com/check_username/?check_username="******"&csrfmiddlewaretoken=" + PinToken;
                        string User             = httpHelper.getHtmlfromUrl(new Uri(CheckUserNameUrl), OAuthVerifier, PinToken, this.userAgent);

                        if (User.Contains("username is already"))
                        {
                            int num = RandomNumberGenerator.GenerateRandom(100, 1000);

                            PinUserName = PinUserName + num.ToString();

                            //Checking For User Name
                            CheckUserNameUrl = "http://pinterest.com/check_username/?check_username="******"&csrfmiddlewaretoken=" + PinToken;
                            User             = httpHelper.getHtmlfromUrl(new Uri(CheckUserNameUrl), OAuthVerifier, PinToken, this.userAgent);
                        }

                        ////Checking For User Name
                        //string CheckEmailUrl = "http://pinterest.com/check_username/?check_email=" + PinEmail + "&csrfmiddlewaretoken=" + PinToken;
                        //string Email = httpHelper.getHtmlfromUrl(new Uri(CheckEmailUrl), OAuthVerifier, PinToken);

                        //if (!Email.Contains("success"))
                        //{
                        //    //IsPinLoggedIn = true;
                        //    Log("This email not valid " + PinEmail);
                        //    return;
                        //}
                        string RegistrationPostData = "username="******"&email=" + PinEmail + "&password="******"&invite=" + InviteCode.Replace(" ", "").Replace("http://email.pinterest.com/wf/click&upn=", "") + "&twitter=1&csrfmiddlewaretoken=" + PinToken + "&user_image=http%3A%2F%2Fimg.tweetimag.es%2Fi%2FSocioPro_o";

                        string RegistredPageContent = httpHelper.postFormData(new Uri("http://pinterest.com/register/"), RegistrationPostData, OAuthVerifier, string.Empty, this.userAgent);

                        if (RegistredPageContent.Contains("recaptcha/api/js/recaptcha"))
                        {
                            List <string> lstData   = GetCapctha();
                            string        challenge = string.Empty;
                            string        response  = string.Empty;


                            challenge = lstData[0].ToString();
                            response  = lstData[1].ToString();
                            response  = response.Replace(" ", "+");
                            string postUrl   = "http://pinterest.com/verify_captcha/?src=register&return=/welcome/";
                            string postData1 = "challenge=" + challenge + "&response=" + response;

                            string POstResponse = httpHelper.postFormData(new Uri(postUrl), postData1, OAuthVerifier, PinToken, this.userAgent);

                            RegistredPageContent = httpHelper.getHtmlfromUrl(new Uri("http://pinterest.com/welcome/"), "", "", this.userAgent);
                        }
                        if (RegistredPageContent.Contains("architecture"))
                        {
                            IsAccountCreated = true;
                            Log("[ " + DateTime.Now + " ] => [ Account Created " + PinUserName + " ]");
                        }
                        else
                        {
                            IsAccountCreated = false;
                            Log("[ " + DateTime.Now + " ] => [ Account Not Created " + PinUserName + " ]");
                            return(IsAccountCreated);
                        }

                        string WelcomPageContent = httpHelper.postFormData(new Uri("http://pinterest.com/welcome/"), "", OAuthVerifier, PinToken, this.userAgent);

                        //Changed By  Gargi On 22nd May 2012 --> request from fiddler changed
                        //string CategoryPostData = "categories=architecture&user_follow=true";

                        string CategoryPostData = "categories=art%2Ccars_motorcycles%2Cdesign%2Cdiy_crafts%2Ceducation%2Carchitecture%2Cfitness";

                        string CategoryPageContent = httpHelper.postFormData(new Uri("http://pinterest.com/welcome/"), CategoryPostData, "http://pinterest.com/welcome/", PinToken, this.userAgent);

                        if (CategoryPageContent.Contains("success"))
                        {
                            IsAccountCreated = true;
                            Log("[ " + DateTime.Now + " ] => [ Initial Category Added " + PinUserName + " ]");
                        }

                        string AllowUserPostData = "follow_users%5B%5D=sharp&follow_users%5B%5D=neillehepworth&follow_users%5B%5D=miamalm&follow_users%5B%5D=kiluka&follow_users%5B%5D=gaileguevara&follow_users%5B%5D=jellway&follow_users%5B%5D=richard_larue&follow_users%5B%5D=rayestudio&follow_users%5B%5D=jdraper&follow_users%5B%5D=shashashasha";
                        //if (string.IsNullOrEmpty(ApplicationData.UsersToFollow))
                        //{
                        //    AllowUserPostData = "follow_users%5B%5D=sharp&follow_users%5B%5D=neillehepworth&follow_users%5B%5D=miamalm&follow_users%5B%5D=kiluka&follow_users%5B%5D=gaileguevara&follow_users%5B%5D=jellway&follow_users%5B%5D=richard_larue&follow_users%5B%5D=rayestudio&follow_users%5B%5D=jdraper&follow_users%5B%5D=shashashasha";
                        //}
                        //else
                        //{
                        //    AllowUserPostData = ApplicationData.UsersToFollow;
                        //}

                        string AlloweduserPostData = httpHelper.postFormData(new Uri("http://pinterest.com/welcome/"), AllowUserPostData, "http://pinterest.com/welcome/", PinToken, this.userAgent);

                        if (AlloweduserPostData.Contains("success"))
                        {
                            IsAccountCreated = true;
                            Log("[ " + DateTime.Now + " ] => [ Intial User Added " + PinUserName + " ]");
                        }

                        string BordPostData = "board_names%5B%5D=Products+I+Love&board_names%5B%5D=Favorite+Places+%26+Spaces&board_names%5B%5D=Books+Worth+Reading&board_names%5B%5D=My+Style&board_names%5B%5D=For+the+Home";

                        string BoardPostedPageContent = httpHelper.postFormData(new Uri("http://pinterest.com/welcome/"), BordPostData, "http://pinterest.com/welcome/", PinToken, this.userAgent);

                        if (BoardPostedPageContent.Contains("success"))
                        {
                            IsAccountCreated = true;
                            Log("[ " + DateTime.Now + " ] => [ Intial Board Added " + PinUserName + " ]");
                        }
                    }

                    return(IsAccountCreated);
                }
                else
                {
                    Log("[ " + DateTime.Now + " ] => [ Twitter Account Not Logged In :" + TwitterUsername + " ]");
                    return(IsAccountCreated);
                }
            }
            catch (Exception ex)
            {
                //Log("Error " + ex.Message);
                return(IsAccountCreated);
            }
        }
        private async Task <bool> ExportToMusicFormat(StorageFile fileTarget, SpeechSynthesisStream synthStream)
        {
            bool success = false;

            Debug.WriteLine(fileTarget.FileType + " selected");

            // Set encoding profiles
            _profile = null;
            AudioEncodingQuality audioEncodingProfile = AudioEncodingQuality.High;

            if (fileTarget.FileType == ".wma")
            {
                _profile = MediaEncodingProfile.CreateWma(audioEncodingProfile);
            }
            else if (fileTarget.FileType == ".mp3")
            {
                _profile = MediaEncodingProfile.CreateMp3(audioEncodingProfile);
            }
            else if (fileTarget.FileType == ".m4a")
            {
                _profile = MediaEncodingProfile.CreateM4a(audioEncodingProfile);
            }
            else
            {
                Debug.WriteLine("Can't select a media encoding profile");
                return(success);
            }

            // Write temporary Wav to Temp-storage
            ApplicationData appData = ApplicationData.Current;
            StorageFile     source  = await appData.TemporaryFolder.CreateFileAsync("temporary.wav", CreationCollisionOption.ReplaceExisting);

            try
            {
                using (var reader = new DataReader(synthStream))
                {
                    await reader.LoadAsync((uint)synthStream.Size);

                    IBuffer buffer = reader.ReadBuffer((uint)synthStream.Size);
                    await FileIO.WriteBufferAsync(source, buffer);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Couldn't prepare wav for transcoding");
                Debug.WriteLine(ex);
            }


            // Prepare transcoding files
            var preparedTranscoderResult = await _transcoder.PrepareFileTranscodeAsync(source, fileTarget, _profile);

            if (preparedTranscoderResult.CanTranscode)
            {
                // Set task for transcoding
                await preparedTranscoderResult.TranscodeAsync().AsTask(_cts.Token);

                // Set Music-properties
                MusicProperties fileProperties = await fileTarget.Properties.GetMusicPropertiesAsync();

                fileProperties.Title  = fileTarget.DisplayName;
                fileProperties.Artist = "Talkinator";
                await fileProperties.SavePropertiesAsync();

                // Prepare notification
                // Add the file to app MRU and possibly system MRU
                //RecentStorageItemVisibility visibility = SystemMRUCheckBox.IsChecked.Value ? RecentStorageItemVisibility.AppAndSystem : RecentStorageItemVisibility.AppOnly;
                //rootPage.mruToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Name, visibility);

                //RecentStorageItemVisibility visibility = RecentStorageItemVisibility.AppOnly;
                //StorageApplicationPermissions.FutureAccessList.Add(fileTarget, fileTarget.DisplayName);



                StorageFolder parentFolder = await fileTarget.GetParentAsync();

                FolderLauncherOptions launcherOptions = new FolderLauncherOptions();
                launcherOptions.ItemsToSelect.Add(fileTarget);
                await Launcher.LaunchFolderAsync(parentFolder, launcherOptions);



                // Report completed
                success = true;
                Debug.WriteLine(fileTarget.FileType + " export completed");
            }
            else
            {
                Debug.WriteLine(preparedTranscoderResult.FailureReason);
            }

            return(success);
        }
        public void SaveDefaultAuthenticationProviderAndSaveAndReloadsCorrectly()
        {
            GeneratedHierarchy.Load();

            AddConfigurationSectionCommand cmd = new AddConfigurationSectionCommand(Host, typeof(SecuritySettingsNode), SecuritySettings.SectionName);

            cmd.Execute(GeneratedApplicationNode);

            SecuritySettingsNode securitySettingsNode = GeneratedHierarchy.FindNodeByType(typeof(SecuritySettingsNode)) as SecuritySettingsNode;

            Assert.IsNotNull(securitySettingsNode);
            AuthenticationProviderCollectionNode authenticationProviderCollectionNode = GeneratedHierarchy.FindNodeByType(securitySettingsNode, typeof(AuthenticationProviderCollectionNode)) as AuthenticationProviderCollectionNode;

            Assert.IsNotNull(authenticationProviderCollectionNode);

            AddChildNodeCommand addChildNodeCommand = new AddChildNodeCommand(Host, typeof(DbAuthenticationProviderNode));

            addChildNodeCommand.Execute(authenticationProviderCollectionNode);
            Assert.AreEqual(typeof(DbAuthenticationProviderNode), addChildNodeCommand.ChildNode.GetType());
            DbAuthenticationProviderNode dbAuthenticationProviderNode = (DbAuthenticationProviderNode)addChildNodeCommand.ChildNode;

            securitySettingsNode.DefaultAuthenticationInstance = (AuthenticationProviderNode)addChildNodeCommand.ChildNode;

            addChildNodeCommand = new AddChildNodeCommand(Host, typeof(HashAlgorithmProviderNode));
            CryptographySettingsNode cryptographySettingsNode = GeneratedHierarchy.FindNodeByType(typeof(CryptographySettingsNode)) as CryptographySettingsNode;

            Assert.IsNotNull(cryptographySettingsNode);
            HashProviderCollectionNode hashProviderCollectionNode = GeneratedHierarchy.FindNodeByType(typeof(HashProviderCollectionNode)) as HashProviderCollectionNode;

            Assert.IsNotNull(hashProviderCollectionNode);
            addChildNodeCommand.Execute(hashProviderCollectionNode);
            Assert.AreEqual(typeof(HashAlgorithmProviderNode), addChildNodeCommand.ChildNode.GetType());

            dbAuthenticationProviderNode.HashProvider = (HashProviderNode)addChildNodeCommand.ChildNode;

            DatabaseSettingsNode databaseSettingsNode = GeneratedHierarchy.FindNodeByType(typeof(DatabaseSettingsNode)) as DatabaseSettingsNode;

            Assert.IsNotNull(databaseSettingsNode);
            InstanceCollectionNode instanceCollectionNode = GeneratedHierarchy.FindNodeByType(databaseSettingsNode, typeof(InstanceCollectionNode)) as InstanceCollectionNode;

            Assert.IsNotNull(instanceCollectionNode);
            Assert.IsTrue(instanceCollectionNode.Nodes.Count > 0);
            InstanceNode instanceNode = (InstanceNode)instanceCollectionNode.Nodes[0];

            dbAuthenticationProviderNode.Database = instanceNode;

            ValidateNodeCommand validateNodeCommand = new ValidateNodeCommand(Host);

            validateNodeCommand.Execute(GeneratedApplicationNode);
            Assert.AreEqual(0, ConfigurationErrorsCount);

            SaveApplicationConfigurationNodeCommand saveCmd = new SaveApplicationConfigurationNodeCommand(Host);

            saveCmd.Execute(GeneratedApplicationNode);

            ApplicationConfigurationNode applicationConfigurationNode = new ApplicationConfigurationNode(ApplicationData.FromCurrentAppDomain());
            IUIHierarchy hierarchy = CreateHierarchyAndAddToHierarchyService(applicationConfigurationNode, CreateDefaultConfiguration());

            HierarchyService.SelectedHierarchy = hierarchy;
            hierarchy.Open();
        }