public bool AddShutterEstimate(shutters shutter)
        {
            System.Xml.Linq.XElement customerLocationPics = new System.Xml.Linq.XElement("root");

            foreach (var r in shutter.CustomerLocationPics)
            {
                var varPics = new System.Xml.Linq.XElement("pics", new System.Xml.Linq.XElement("pic", r.LocationPicture));

                customerLocationPics.Add(varPics);
            }

            shutter.locationpicture = customerLocationPics.ToString();

            System.Xml.Linq.XElement shutterAccessoriesList = new System.Xml.Linq.XElement("root");

            foreach (var r in shutter.ShutterAccessories)
            {
                if (r.accessories != null)
                {
                    var varPics = new System.Xml.Linq.XElement("accessories", new System.Xml.Linq.XElement("accessorie", "<![CDATA[" + r.accessories + "]]> "),
                                                               new System.Xml.Linq.XElement("qty", r.quantity));

                    shutterAccessoriesList.Add(varPics);
                }
            }
            shutter.ShutterAccessorie = shutterAccessoriesList.ToString();

            return(shuttersDAL.Instance.AddShutterEstimate(shutter));
        }
        /// <exception cref="System.ArgumentNullException" />
        /// <exception cref="System.Net.WebException" />
        public static System.Xml.Linq.XDocument GetMsg(int threadId, int commeAmount, int userId, Uri commeServer, System.Net.CookieContainer cookie)
        {
            if(commeServer == null)
                throw new ArgumentNullException("commeServer", "nullにする事は出来ません。");

            var reqXml = new System.Xml.Linq.XElement(
                "thread",
                //new System.Xml.Linq.XAttribute("no_compress", 0),
                new System.Xml.Linq.XAttribute("fork", "0"),//投票者コメント:1
                new System.Xml.Linq.XAttribute("user_id", userId),
                //new System.Xml.Linq.XAttribute("when", 0),
                new System.Xml.Linq.XAttribute("res_from", commeAmount),
                new System.Xml.Linq.XAttribute("version", "20061206"),
                new System.Xml.Linq.XAttribute("thread", threadId));
            var reqMsg = reqXml.ToString();

            try
            {
                using (var strm = HttpConect(commeServer, reqMsg, cookie))
                using (var reader = new System.IO.StreamReader(strm))
                    return System.Xml.Linq.XDocument.Load(reader);
            }
            catch (System.Net.WebException e)
            {
                throw new System.Net.WebException("コメントサーバへの接続に失敗しました。", e);
            }
        }
예제 #3
0
        public string toXml()
        {
            System.Xml.Linq.XElement element = new System.Xml.Linq.XElement("Config");
            element.SetElementValue("TypeJson", TypeJson);
            element.SetElementValue("AutoOn", AutoOn);

            //RPC.Serialize.ParamsSerializeUtil.Serialize(this);
            return(element.ToString());
        }
예제 #4
0
        /// <summary>
        /// 必须重写这个方法,返回的数据就真正保存到txt的数据
        /// </summary>
        /// <returns>字符串信息</returns>
        public override string ToSaveString( )
        {
            // 此处举例采用xml格式存储
            System.Xml.Linq.XElement element = new System.Xml.Linq.XElement("Settings");

            element.Add(new System.Xml.Linq.XElement(nameof(IpAddress), IpAddress));
            element.Add(new System.Xml.Linq.XElement(nameof(Port), Port.ToString( )));

            return(element.ToString( ));
        }
예제 #5
0
        public void ConfigurationData_returns_correct_xml()
        {
            IConfigurationData <IAction> data = new TestConfigurationData()
            {
                Id = "123"
            };

            System.Xml.Linq.XElement element = data.GetXml();
            Assert.AreEqual(@"<Test Id=""123"" />", element.ToString());
        }
        public void XElement_3137()
        {
            CultureInfo current = Thread.CurrentThread.CurrentCulture;

            try {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                var element1 = new System.Xml.Linq.XElement("Property1", new System.Xml.Linq.XAttribute("type", "number"), 1.2343445);
                Assert.That(element1.ToString(), Is.EqualTo("<Property1 type=\"number\">1.2343445</Property1>"), "en-US");

                Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
                // this was already working because the element was created with en-US
                Assert.That(element1.ToString(), Is.EqualTo("<Property1 type=\"number\">1.2343445</Property1>"), "de-DE/1");
                // however creating a new, identical, element under de-DE return*ed* a different string
                var element2 = new System.Xml.Linq.XElement("Property1", new System.Xml.Linq.XAttribute("type", "number"), 1.2343445);
                Assert.That(element2.ToString(), Is.EqualTo("<Property1 type=\"number\">1.2343445</Property1>"), "de-DE/2");
            }
            finally {
                Thread.CurrentThread.CurrentCulture = current;
            }
        }
예제 #7
0
 private static string FormatXmlString(string xmlString)
 {
     if (string.IsNullOrEmpty(xmlString))
     {
         return(xmlString);
     }
     else
     {
         System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);
         return(element.ToString());
     }
 }
 public JsonResult AddUpdatePatient(Dictionary <string, string> formdata)
 {
     try
     {
         System.Xml.Linq.XElement el = new System.Xml.Linq.XElement("PatientInfo", formdata.Select(kv => new System.Xml.Linq.XElement(kv.Key, kv.Value)));
         var      xml      = el.ToString();
         XMlClass xMLClass = new XMlClass
         {
             PatietXML = xml,
         };
         _patientDAL.InsertUpdatePatient(xMLClass, "sp_InsertPatient");
         return(Json("Data Saved Successfully"));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #9
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            string fileNameWithoutExtension;

            FileInfo[] files = directoryInfo.GetFiles("*.docx");
            foreach (FileInfo file in files)
            {
                try
                {
                    fileNameWithoutExtension = file.Name.Split('.').FirstOrDefault();

                    GenerateLog($"Convertendo arquivo {file.Name}.");
                    using (var source = Package.Open(inputPath + file.Name))
                    {
                        using (var document = WordprocessingDocument.Open(source))
                        {
                            System.Xml.Linq.XElement html = HtmlConverter.ConvertToHtml(document, new HtmlConverterSettings());
                            using (var writer = File.CreateText(outputPath + fileNameWithoutExtension + ".html"))
                                writer.WriteLine(html.ToString());
                        }
                    }

                    string htmlIn = File.ReadAllText(outputPath + fileNameWithoutExtension + ".html");
                    using (var pdfzim = PdfGenerator.GeneratePdf(htmlIn, PdfSharp.PageSize.A4))
                    {
                        GenerateLog($"Salvando arquivo {fileNameWithoutExtension}.pdf ...");
                        pdfzim.Save(outputPath + fileNameWithoutExtension + ".pdf");
                        GenerateLog($"Arquivo {fileNameWithoutExtension}.pdf gerado com sucesso!");
                    }
                }
                catch (Exception ex)
                {
                    GenerateLog($"Erro na geração do arquivo {file.Name}");
                }
            }

            if (files == null || files.Count() == 0)
            {
                GenerateLog("Não foram localizados arquivos para conversão.");
            }
        }
예제 #10
0
        protected void HandleDurak(object sender, EventArgs e)
        {
            IETTService.ibbSoapClient HatService = new IETTService.ibbSoapClient();
            System.Xml.Linq.XElement  xElement   = HatService.DurakDetay_GYY(txtGetDurak.Value);

            string XmlToString = xElement.ToString();

            StringReader ReaderXml = new StringReader(XmlToString);

            DataSet DataSetFromXml = new DataSet();

            DataSetFromXml.ReadXml(ReaderXml);

            if (DataSetFromXml.Tables.Count != 0)
            {
                DataTable dt = DataSetFromXml.Tables[0];
                txtresult.InnerHtml = ConvertDataTableToHtml(dt);
            }
            else
            {
                txtresult.InnerHtml = "Böyle bir Otobüs bilgisi bulunmamaktadır.";
            }
        }
예제 #11
0
        public override void ReadXml(System.Xml.Linq.XElement element)
        {
            base.ReadXml(element);
            var algorithm = element.ReadString("Algorithm");

            if (string.IsNullOrEmpty(algorithm))
            {
                throw new Exception("When reading the IntersectionPoint, the Algorithm attribute "
                                    + "was not specified. This point will not be created. Full text:\n"
                                    + element.ToString());
            }
            var method = typeof(IntersectionAlgorithms).GetMethod(algorithm);

            if (method == null)
            {
                throw new Exception(string.Format("When reading the IntersectionPoint, the Algorithm method "
                                                  + "'{0}' wasn't found.", algorithm));
            }
            var @delegate = Delegate.CreateDelegate(typeof(Func <IFigure, IFigure, Point>), method);

            Algorithm = @delegate as Func <IFigure, IFigure, Point>;
            this.RecalculateAndUpdateVisual();
        }
예제 #12
0
 public static string RemoveAllNamespaces(string xmlDocument)
 {
     //  Firstly remove all our known namespace values using simple string.Replace
     xmlDocument = Base.RemoveXmlNamespaces(xmlDocument);
     //  To remove Namespaces we have to recreate the Element from the incoming structure
     //  Load up an XElement with the XML document contents
     System.Xml.Linq.XElement rootElement = System.Xml.Linq.XElement.Parse(xmlDocument);
     System.Xml.Linq.XElement rootElementWithNoNamespace = new System.Xml.Linq.XElement(rootElement.Name.LocalName);
     //  We want to retain Namespace attributes on the root (for LookupData anyway)
     //  Take any existing Namespace (and other attributes) on the top level Element
     foreach (System.Xml.Linq.XAttribute attribute in rootElement.Attributes())
     {
         rootElementWithNoNamespace.Add(attribute);
     }
     if (rootElement.HasElements)
     {
         foreach (System.Xml.Linq.XElement childElement in rootElement.Elements())
         {
             rootElementWithNoNamespace.Add(RemoveAllNamespaces(childElement));
         }
     }
     return rootElementWithNoNamespace.ToString();
 }
예제 #13
0
        private void SaveSettings()
        {
            System.Xml.Linq.XElement x = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("Settings"));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("HistoryCount"), nudHistory.Value));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("SlotCount"), nudSlots.Value));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("EmailAddress"), EmailAddress));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("UserName"), UserName));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("ServerAddress"), ServerAddress));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("ServerPassword"), Password));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("SMTPPort"), Port));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("EnableSSL"), enableSSL));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("SubjectLine"), SubjectLine));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("OpeningLine"), OpeningLine));
            x.Add(new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("ClosingLine"), ClosingLine));

            System.IO.FileInfo f = new System.IO.FileInfo("settings.xml");
            if (f.Exists)
                f.Delete();
            var str = f.Create();
            var buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(x.ToString());
            str.Write(buffer, 0, buffer.Length);
            str.Close();
            str.Dispose();

            Properties.Settings.Default.HistoryCount = nudHistory.Value;
            Properties.Settings.Default.SlotCount = nudSlots.Value;
            Properties.Settings.Default.Save();
        }
예제 #14
0
        public static void ComparePrimitiveValuesObjectAndString(object expected, Type expectedType, string actual, bool valueUri, SerializationFormatKind serializationKind, bool throwOnError)
        {
            object actualObject = DeserializeStringToObject(actual, expectedType, valueUri, serializationKind);
            string expectedStr  = "null";

            if (expected != null)
            {
                expectedStr = AstoriaUnitTests.Data.TypeData.XmlValueFromObject(expected);
            }

            string errorMessage = String.Format("Error Primitive Value of type:{0} not equal: \r\n\tExpected:\t{1} \r\n\tActual:\t{2}", expectedType.Name, expectedStr, actual);

            //Fixups
            if (expected != null && expectedType.Equals(typeof(string)))
            {
                if (actualObject != null)
                {
                    actualObject = (actualObject as string).Trim();
                }
                expected = (expected as string).Trim();
            }

            if (expectedType == typeof(System.Xml.Linq.XElement))
            {
                expectedStr = null;
                if (expected != null)
                {
                    System.Xml.Linq.XElement xElement = expected as System.Xml.Linq.XElement;
                    expectedStr = xElement.ToString();
                }
                AstoriaTestLog.AreEqual(expectedStr, actual, errorMessage);
            }
            else if (expectedType == typeof(Single) || expectedType == typeof(Double))
            {
                if (serializationKind == SerializationFormatKind.JSON)
                {
                    if (expectedType == typeof(Double))
                    {
                        Double d;
                        if (expected != null)
                        {
                            d           = Convert.ToDouble(expected);
                            expectedStr = d.ToString("r", System.Globalization.CultureInfo.InvariantCulture);
                        }
                        if (actual != null)
                        {
                            if (double.TryParse(actual, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out d))
                            {
                                actual = d.ToString("r", CultureInfo.InvariantCulture.NumberFormat);
                            }
                        }
                    }
                    else if (expectedType == typeof(Single))
                    {
                        Single s;
                        if (expected != null)
                        {
                            s           = Convert.ToSingle(expected);
                            expectedStr = s.ToString("r", System.Globalization.CultureInfo.InvariantCulture);
                        }
                        if (actual != null)
                        {
                            if (Single.TryParse(actual, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out s))
                            {
                                actual = s.ToString("r", CultureInfo.InvariantCulture.NumberFormat);
                            }
                        }
                    }
                }
                //Fixup
                if (expectedStr == "null")
                {
                    expectedStr = null;
                }
                if (expectedStr != null && actual != null)
                {
                    expectedStr = expectedStr.Trim();
                    actual      = actual.Trim();
                }
                if (throwOnError)
                {
                    if (expectedStr != null)
                    {
                        AstoriaTestLog.Compare(expectedStr.Equals(actual), errorMessage);
                    }
                    else
                    {
                        AstoriaTestLog.Compare(actual == null, errorMessage);
                    }
                }
                else
                {
                    AstoriaTestLog.AreEqual(expectedStr, actual, errorMessage);
                }
            }
#if !ClientSKUFramework
            //For some reason byte[] comparision is not working correctly
            else if ((expectedType == typeof(byte[]) || expectedType == typeof(System.Data.Linq.Binary)) && valueUri)
            {
                string expectedBytesStr = null;
                if (expected == null)
                {
                    expectedBytesStr = null;
                }
                else if (expectedType == typeof(byte[]))
                {
                    expectedBytesStr = (new System.Text.UTF8Encoding()).GetString((byte[])expected);
                }


                else if (expectedType == typeof(System.Data.Linq.Binary))
                {
                    System.Data.Linq.Binary binary = expected as System.Data.Linq.Binary;
                    expectedBytesStr = (new System.Text.UTF8Encoding()).GetString((byte[])binary.ToArray());
                }

                if (throwOnError)
                {
                    if (expected == null)
                    {
                        AstoriaTestLog.Compare(null == actual, errorMessage);
                    }
                    else
                    {
                        AstoriaTestLog.Compare(expectedBytesStr.Equals(actual), errorMessage);
                    }
                }
                else
                {
                    AstoriaTestLog.AreEqual(expectedBytesStr, actual, errorMessage);
                }
            }
#endif

            else if (expectedType == typeof(byte[]) && valueUri == false)
            {
                AreBytesEqual((byte[])expected, (byte[])actualObject, throwOnError);
            }
            else
            {
                if (throwOnError)
                {
                    bool objectsEqual = true;
                    if (expected == null)
                    {
                        if (actualObject != null)
                        {
                            objectsEqual = false;
                        }
                    }
                    else
                    {
                        objectsEqual = expected.Equals(actualObject);
                    }
                    AstoriaTestLog.Compare(objectsEqual, errorMessage);
                }
                else
                {
                    AstoriaTestLog.AreEqual(expected, actualObject, errorMessage);
                }
            }
        }
예제 #15
0
        public static bool Add(string key, System.Xml.Linq.XElement value, CacheItemPolicy policy)
        {
            if (defaultCache != null)
            {
                key = key.Replace(' ', '_');

                // if (policy.AbsoluteExpiration != null
                if (policy.SlidingExpiration.Ticks == 0)
                {
                    if (defaultCache.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value.ToString(), policy.AbsoluteExpiration.DateTime))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (defaultCache.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value.ToString(), policy.SlidingExpiration))
                    {
                        return(true);
                    }
                }
            }
            CDRLogger.Logger.LogInfo("Cache.Add failed: " + key);

            return(false);
        }
예제 #16
0
 public EventLog(System.Xml.Linq.XElement xe)
 {
     _event = xe.ToString();
     Console.WriteLine(xe);
 }
예제 #17
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

                try
                {
                    servicesManager = new WorkflowServicesManager(web.Context, web);
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                if (servicesManager != null)
                {
                    var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                    // Pre-load useful properties
                    web.EnsureProperty(w => w.Id);

                    // Provision Workflow Definitions
                    foreach (var definition in template.Workflows.WorkflowDefinitions)
                    {
                        // Load the Workflow Definition XAML
                        Stream xamlStream             = template.Connector.GetFileStream(definition.XamlPath);
                        System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);

                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
                        {
                            AssociationUrl          = definition.AssociationUrl,
                            Description             = definition.Description,
                            DisplayName             = definition.DisplayName,
                            FormField               = definition.FormField,
                            DraftVersion            = definition.DraftVersion,
                            Id                      = definition.Id,
                            InitiationUrl           = definition.InitiationUrl,
                            RequiresAssociationForm = definition.RequiresAssociationForm,
                            RequiresInitiationForm  = definition.RequiresInitiationForm,
                            RestrictToScope         = parser.ParseString(definition.RestrictToScope),
                            RestrictToType          = definition.RestrictToType != "Universal" ? definition.RestrictToType : null,
                            Xaml                    = xaml.ToString(),
                        };

                        //foreach (var p in definition.Properties)
                        //{
                        //    workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
                        //}

                        // Save the Workflow Definition
                        var definitionId = deploymentService.SaveDefinition(workflowDefinition);
                        web.Context.Load(workflowDefinition);
                        web.Context.ExecuteQueryRetry();

                        // Let's publish the Workflow Definition, if needed
                        if (definition.Published)
                        {
                            deploymentService.PublishDefinition(definitionId.Value);
                        }
                    }


                    // get existing subscriptions
                    var existingWorkflowSubscriptions = web.GetWorkflowSubscriptions();

                    foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                    {
                        // Check if the subscription already exists before adding it, and
                        // if already exists a subscription with the same name and with the same DefinitionId,
                        // it is a duplicate
                        string subscriptionName;
                        if (subscription.PropertyDefinitions.TryGetValue("SharePointWorkflowContext.Subscription.Name", out subscriptionName) &&
                            existingWorkflowSubscriptions.Any(s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId))
                        {
                            // Thus, skip it!
                            WriteWarning(string.Format("Workflow Subscription '{0}' already exists. Skipping...", subscription.Name), ProvisioningMessageType.Warning);
                            continue;
                        }
#if CLIENTSDKV15
                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name            = subscription.Name,
                            StatusFieldName = subscription.StatusFieldName,
                        };
#else
                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name = subscription.Name,
                            ParentContentTypeId = subscription.ParentContentTypeId,
                            StatusFieldName     = subscription.StatusFieldName,
                        };
#endif
                        foreach (var propertyDefinition in subscription.PropertyDefinitions
                                 .Where(d => d.Key == "TaskListId" ||
                                        d.Key == "HistoryListId" ||
                                        d.Key == "SharePointWorkflowContext.Subscription.Id" ||
                                        d.Key == "SharePointWorkflowContext.Subscription.Name"))
                        {
                            workflowSubscription.SetProperty(propertyDefinition.Key, parser.ParseString(propertyDefinition.Value));
                        }
                        if (!String.IsNullOrEmpty(subscription.ListId))
                        {
                            // It is a List Workflow
                            Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                            subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                        }
                        else
                        {
                            // It is a Site Workflow
                            subscriptionService.PublishSubscription(workflowSubscription);
                        }
                        web.Context.ExecuteQueryRetry();
                    }
                }
            }

            return(parser);
        }
예제 #18
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                var servicesManager     = new WorkflowServicesManager(web.Context, web);
                var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                // Provision Workflow Definitions
                foreach (var definition in template.Workflows.WorkflowDefinitions)
                {
                    // Load the Workflow Definition XAML
                    Stream xamlStream             = template.Connector.GetFileStream(definition.XamlPath);
                    System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);

                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
                    {
                        AssociationUrl          = definition.AssociationUrl,
                        Description             = definition.Description,
                        DisplayName             = definition.DisplayName,
                        FormField               = definition.FormField,
                        DraftVersion            = definition.DraftVersion,
                        Id                      = definition.Id,
                        InitiationUrl           = definition.InitiationUrl,
                        RequiresAssociationForm = definition.RequiresAssociationForm,
                        RequiresInitiationForm  = definition.RequiresInitiationForm,
                        RestrictToScope         = parser.ParseString(definition.RestrictToScope),
                        RestrictToType          = definition.RestrictToType != "Universal" ? definition.RestrictToType : null,
                        Xaml                    = xaml.ToString(),
                    };

                    //foreach (var p in definition.Properties)
                    //{
                    //    workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
                    //}

                    // Save the Workflow Definition
                    var definitionId = deploymentService.SaveDefinition(workflowDefinition);
                    web.Context.Load(workflowDefinition);
                    web.Context.ExecuteQueryRetry();

                    // Let's publish the Workflow Definition, if needed
                    if (definition.Published)
                    {
                        deploymentService.PublishDefinition(definitionId.Value);
                    }
                }

                foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                {
#if CLIENTSDKV15
                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                    {
                        DefinitionId  = subscription.DefinitionId,
                        Enabled       = subscription.Enabled,
                        EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                        EventTypes    = subscription.EventTypes,
                        ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                        Name            = subscription.Name,
                        StatusFieldName = subscription.StatusFieldName,
                    };
#else
                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                    {
                        DefinitionId  = subscription.DefinitionId,
                        Enabled       = subscription.Enabled,
                        EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                        EventTypes    = subscription.EventTypes,
                        ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                        Name = subscription.Name,
                        ParentContentTypeId = subscription.ParentContentTypeId,
                        StatusFieldName     = subscription.StatusFieldName,
                    };
#endif
                    foreach (var p in subscription.PropertyDefinitions
                             .Where(d => d.Key == "TaskListId" || d.Key == "HistoryListId"))
                    {
                        workflowSubscription.SetProperty(p.Key, parser.ParseString(p.Value));
                    }

                    if (!String.IsNullOrEmpty(subscription.ListId))
                    {
                        // It is a List Workflow
                        Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                        subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                    }
                    else
                    {
                        // It is a Site Workflow
                        subscriptionService.PublishSubscription(workflowSubscription);
                    }
                    web.Context.ExecuteQueryRetry();
                }
            }

            return(parser);
        }
예제 #19
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

                try
                {
                    servicesManager = new WorkflowServicesManager(web.Context, web);
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                if (servicesManager != null)
                {
                    var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                    // Pre-load useful properties
                    web.EnsureProperty(w => w.Id);

                    // Provision Workflow Definitions
                    foreach (var templateDefinition in template.Workflows.WorkflowDefinitions)
                    {
                        // Load the Workflow Definition XAML
                        Stream xamlStream             = template.Connector.GetFileStream(templateDefinition.XamlPath);
                        System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);

                        int retryCount    = 5;
                        int retryAttempts = 1;
                        int delay         = 2000;

                        while (retryAttempts <= retryCount)
                        {
                            try
                            {
                                // Create the WorkflowDefinition instance
                                Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
                                    new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
                                {
                                    AssociationUrl          = templateDefinition.AssociationUrl,
                                    Description             = templateDefinition.Description,
                                    DisplayName             = templateDefinition.DisplayName,
                                    FormField               = templateDefinition.FormField,
                                    DraftVersion            = templateDefinition.DraftVersion,
                                    Id                      = templateDefinition.Id,
                                    InitiationUrl           = templateDefinition.InitiationUrl,
                                    RequiresAssociationForm = templateDefinition.RequiresAssociationForm,
                                    RequiresInitiationForm  = templateDefinition.RequiresInitiationForm,
                                    RestrictToScope         = parser.ParseString(templateDefinition.RestrictToScope),
                                    RestrictToType          = templateDefinition.RestrictToType != "Universal" ? templateDefinition.RestrictToType : null,
                                    Xaml                    = xaml.ToString(),
                                };

                                //foreach (var p in definition.Properties)
                                //{
                                //    workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
                                //}

                                // Save the Workflow Definition
                                var newDefinition = deploymentService.SaveDefinition(workflowDefinition);
                                //web.Context.Load(workflowDefinition); //not needed
                                web.Context.ExecuteQueryRetry();

                                // Let's publish the Workflow Definition, if needed
                                if (templateDefinition.Published)
                                {
                                    deploymentService.PublishDefinition(newDefinition.Value);
                                    web.Context.ExecuteQueryRetry();
                                }

                                break; // no errors so exit loop
                            }
                            catch (Exception ex)
                            {
                                // check exception is due to connection closed issue
                                if (ex is ServerException && ((ServerException)ex).ServerErrorCode == -2130575223 &&
                                    ((ServerException)ex).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPException", StringComparison.InvariantCultureIgnoreCase) &&
                                    ((ServerException)ex).Message.Contains("A connection that was expected to be kept alive was closed by the server.")
                                    )
                                {
                                    WriteWarning(String.Format("Connection closed whilst adding Workflow Definition, trying again in {0}ms", delay), ProvisioningMessageType.Warning);

                                    Thread.Sleep(delay);

                                    retryAttempts++;
                                    delay = delay * 2; // double delay for next retry
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }


                    // get existing subscriptions
                    var existingWorkflowSubscriptions = web.GetWorkflowSubscriptions();

                    foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                    {
                        // Check if the subscription already exists before adding it, and
                        // if already exists a subscription with the same name and with the same DefinitionId,
                        // it is a duplicate
                        string subscriptionName;
                        if (subscription.PropertyDefinitions.TryGetValue("SharePointWorkflowContext.Subscription.Name", out subscriptionName) &&
                            existingWorkflowSubscriptions.Any(s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId))
                        {
                            // Thus, skip it!
                            WriteWarning(string.Format("Workflow Subscription '{0}' already exists. Skipping...", subscription.Name), ProvisioningMessageType.Warning);
                            continue;
                        }
#if ONPREMISES
                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name            = subscription.Name,
                            StatusFieldName = subscription.StatusFieldName,
                        };
#else
                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name = subscription.Name,
                            ParentContentTypeId = subscription.ParentContentTypeId,
                            StatusFieldName     = subscription.StatusFieldName,
                        };
#endif
                        foreach (var propertyDefinition in subscription.PropertyDefinitions
                                 .Where(d => d.Key == "TaskListId" ||
                                        d.Key == "HistoryListId" ||
                                        d.Key == "SharePointWorkflowContext.Subscription.Id" ||
                                        d.Key == "SharePointWorkflowContext.Subscription.Name" ||
                                        d.Key == "CreatedBySPD"))
                        {
                            workflowSubscription.SetProperty(propertyDefinition.Key, parser.ParseString(propertyDefinition.Value));
                        }
                        if (!String.IsNullOrEmpty(subscription.ListId))
                        {
                            // It is a List Workflow
                            Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                            subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                        }
                        else
                        {
                            // It is a Site Workflow
                            subscriptionService.PublishSubscription(workflowSubscription);
                        }
                        web.Context.ExecuteQueryRetry();
                    }
                }
            }

            return(parser);
        }
예제 #20
0
        public async Task <HttpResponseMessage> InsertOrUpdate(UpdateDataMartInstalledModelsDTO updateInfo)
        {
            // All installed models have the same datamart id.
            var datamartID = updateInfo.DataMartID;

            var datamart = await DataContext.Secure <DataMart>(Identity, PermissionIdentifiers.DataMart.Edit).FirstOrDefaultAsync(dm => dm.ID == datamartID);

            if (datamart == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to alter one or more DataMarts referenced."));
            }

            await DataContext.Entry(datamart).Collection(dm => dm.Models).LoadAsync();

            var modelsToDelete = datamart.Models.Where(m => !updateInfo.Models.Any(um => um.ModelID == m.ModelID)).ToArray();

            if (datamart.AdapterID.HasValue)
            {
                //if an adapter has been set on the datamart, make sure that QueryComposer is the only installed model,
                //add if missing, and remove any others.

                modelsToDelete    = datamart.Models.Where(m => m.ModelID != QueryComposerModelID).ToArray();
                updateInfo.Models = updateInfo.Models.Where(m => m.ModelID == QueryComposerModelID).ToArray();

                if (!updateInfo.Models.Any(m => m.ModelID == QueryComposerModelID))
                {
                    updateInfo.Models = new[]
                    {
                        new DataMartInstalledModelDTO
                        {
                            DataMartID = datamart.ID,
                            ModelID    = QueryComposerModelID,
                            Properties = "<Properties><Property Name=\"ModelID\" Value=\"" + datamart.AdapterID + "\" /></Properties>"
                        }
                    };
                }
            }

            if (modelsToDelete.Length > 0)
            {
                var modelsToDeleteID = modelsToDelete.Select(m => m.ModelID).ToArray();

                var datamartRequestTypeAcls = from a in DataContext.DataMartRequestTypeAcls
                                              where a.DataMartID == datamartID &&
                                              a.RequestType.Models.Any(m => modelsToDeleteID.Contains(m.DataModelID))
                                              select a;
                DataContext.DataMartRequestTypeAcls.RemoveRange(datamartRequestTypeAcls);

                var projectDatamartRequestTypeAcls = from a in DataContext.ProjectDataMartRequestTypeAcls
                                                     where a.DataMartID == datamartID &&
                                                     a.RequestType.Models.Any(m => modelsToDeleteID.Contains(m.DataModelID)) &&
                                                     !a.RequestType.Models.Any(m => !modelsToDeleteID.Contains(m.DataModelID))
                                                     select a;
                DataContext.ProjectDataMartRequestTypeAcls.RemoveRange(projectDatamartRequestTypeAcls);

                var projectRequestTypeAcls = from a in DataContext.ProjectRequestTypeAcls
                                             where a.RequestType.Models.Any(m => modelsToDeleteID.Contains(m.DataModelID)) &&
                                             a.Project.DataMarts.Any(dm => dm.DataMartID == datamartID) &&
                                             !a.Project.DataMarts.Any(dm => dm.DataMartID != datamartID &&
                                                                      dm.DataMart.Models.Any(m => modelsToDeleteID.Contains(m.ModelID)))
                                             select a;
                DataContext.ProjectRequestTypeAcls.RemoveRange(projectRequestTypeAcls);

                foreach (var md in modelsToDelete)
                {
                    datamart.Models.Remove(md);
                }
            }

            var modelID = updateInfo.Models.Select(m => m.ModelID).ToArray();
            var models  = await DataContext.DataModels.Where(m => modelID.Contains(m.ID)).ToArrayAsync();

            foreach (var im in updateInfo.Models)
            {
                var modelInfo = datamart.Models.FirstOrDefault(m => m.ModelID == im.ModelID);
                if (modelInfo == null)
                {
                    modelInfo = new DataMartInstalledModel
                    {
                        DataMartID = datamart.ID,
                        ModelID    = im.ModelID,
                        Properties = im.Properties
                    };
                    datamart.Models.Add(modelInfo);
                }
                else
                {
                    modelInfo.Properties = im.Properties;
                }

                var model = models.Single(m => m.ID == modelInfo.ModelID);
                if (model.QueryComposer)
                {
                    //make sure the ModelID property has been set to the datamart.AdapterID

                    if (string.IsNullOrEmpty(modelInfo.Properties))
                    {
                        modelInfo.Properties = "<Properties><Property Name=\"ModelID\" Value=\"" + datamart.AdapterID + "\" /></Properties>";
                    }
                    else
                    {
                        System.Xml.Linq.XElement doc = System.Xml.Linq.XElement.Parse(modelInfo.Properties);
                        var modelNode = doc.Descendants("Property").Where(n => n.Attributes("Name").Any(a => a.Value == "ModelID")).FirstOrDefault();
                        if (modelNode != null)
                        {
                            modelNode.Attribute("Value").Value = datamart.AdapterID.HasValue ? datamart.AdapterID.Value.ToString() : string.Empty;
                        }
                        else
                        {
                            doc.Add(new System.Xml.Linq.XElement("Property", new System.Xml.Linq.XAttribute("Name", "ModelID"), new System.Xml.Linq.XAttribute("Value", datamart.AdapterID)));
                        }

                        modelInfo.Properties = doc.ToString();
                    }
                }
            }

            await DataContext.SaveChangesAsync();

            return(Request.CreateResponse(HttpStatusCode.Accepted));
        }