private SoundInfo LoadSound(XElement soundNode, string basePath)
        {
            SoundInfo sound = new SoundInfo { Name = soundNode.RequireAttribute("name").Value };

            sound.Loop = soundNode.TryAttribute<bool>("loop");

            sound.Volume = soundNode.TryAttribute<float>("volume", 1);

            XAttribute pathattr = soundNode.Attribute("path");
            XAttribute trackAttr = soundNode.Attribute("track");
            if (pathattr != null)
            {
                sound.Type = AudioType.Wav;
                sound.Path = FilePath.FromRelative(pathattr.Value, basePath);
            }
            else if (trackAttr != null)
            {
                sound.Type = AudioType.NSF;

                int track;
                if (!trackAttr.Value.TryParse(out track) || track <= 0) throw new GameXmlException(trackAttr, "Sound track attribute must be an integer greater than zero.");
                sound.NsfTrack = track;

                sound.Priority = soundNode.TryAttribute<byte>("priority", 100);
            }
            else
            {
                sound.Type = AudioType.Unknown;
            }

            return sound;
        }
        public void Execute(ClientContext ctx, string listTitle, XElement schema, Action<Field> setAdditionalProperties = null)
        {
            var displayName = schema.Attribute("DisplayName").Value;
            Logger.Verbose($"Started executing {nameof(CreateColumnOnList)} for column '{displayName}' on list '{listTitle}'");

            var list = ctx.Web.Lists.GetByTitle(listTitle);
            var fields = list.Fields;
            ctx.Load(fields);
            ctx.ExecuteQuery();

            // if using internal names in code, remember to encode those before querying, e.g., 
            // space character becomes "_x0020_" as described here:
            // http://www.n8d.at/blog/encode-and-decode-field-names-from-display-name-to-internal-name/
            // We don't use the internal name here because it's limited to 32 chacters. This means
            // "Secondary site abcde" is the longest possible internal name when taken into account
            // the "_x0020_" character. Using a longer name will truncate the internal name to 32
            // characters. Thus querying on the complete, not truncated name, will always return no
            // results which causes the field get created repetedly.
            var field = fields.SingleOrDefault(f => f.Title == displayName);
            if (field != null)
            {
                Logger.Warning($"Column '{displayName}' already on list {listTitle}");
                return;
            }

            var newField = list.Fields.AddFieldAsXml(schema.ToString(), true, AddFieldOptions.DefaultValue);
            ctx.Load(newField);
            ctx.ExecuteQuery();

            if (setAdditionalProperties != null)
            {
                setAdditionalProperties(newField);
                newField.Update();
            }
        }
Example #3
1
        /// <summary>
        /// Get the entity GUID for a document element of the XML file (maybe the last GUID or the next 
        /// one... depends on some rules).
        /// </summary>
        public Guid GetGuid(XElement element, string languageFallback)
        {
            Guid entityGuid;

            var elementGuid = element.GetChildElementValue(DocumentNodeNames.EntityGuid);
            if (string.IsNullOrEmpty(elementGuid))
            {
                var elementLanguage = element.GetChildElementValue(DocumentNodeNames.EntityLanguage);
                if (elementLanguage == languageFallback || string.IsNullOrEmpty(elementLanguage))
                {   // If the element does not have a GUID and the element has data for the default
                    // language, create a new GUID
                    entityGuid = Guid.NewGuid();
                }
                else
                {
                    entityGuid = entityGuidLast;
                }
            }
            else
            {
                entityGuid = Guid.Parse(elementGuid);
            }

            entityGuidLast = entityGuid;
            return entityGuid;
        }
Example #4
1
        public void CreateFolders(Project currentProject, string schedule, string projectName, string relativePath)
        {
            //Create a File under Properties Folder which will contain information about all WebJobs
            //https://github.com/ligershark/webjobsvs/issues/6

            // Check if the WebApp is C# or VB
            string dir = GetProjectDirectory(currentProject);
            var propertiesFolderName = "Properties";
            if (currentProject.CodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVB)
            {
                propertiesFolderName = "My Project";
            }

            DirectoryInfo info = new DirectoryInfo(Path.Combine(dir, propertiesFolderName));

            string readmeFile = Path.Combine(info.FullName, "WebJobs.xml");

            // Copy File if it does not exit
            if (!File.Exists(readmeFile))
                AddReadMe(readmeFile);

            //Add a WebJob info to it
            XDocument doc = XDocument.Load(readmeFile);
            XElement root = new XElement("WebJob");
            root.Add(new XAttribute("Project", projectName));
            root.Add(new XAttribute("RelativePath", relativePath));
            root.Add(new XAttribute("Schedule", schedule));
            doc.Element("WebJobs").Add(root);
            doc.Save(readmeFile);
            currentProject.ProjectItems.AddFromFile(readmeFile);
        }
        public System.Xml.Linq.XElement ToPhysical(System.Xml.Linq.XElement udsService)
        {
            string name = udsService.Attribute("Name").Value;
            XElement x = new XElement("Service", new XAttribute("Name", name));
            XElement prop = new XElement("Property", new XAttribute("Name", "Definition"));
            x.Add(prop);

            XElement serv = new XElement("Service");
            prop.Add(serv);

            XElement sd = new XElement("ServiceDescription");
            serv.Add(sd);

            XElement handler = new XElement("Handler", new XAttribute("ExecType", "RemoteComponent"));
            sd.Add(handler);
            
            XElement udsDefinition = udsService.Element("Definition");
            foreach (XElement e in udsDefinition.Elements())
                sd.Add(e);

            XElement usage = new XElement("Usage");
            sd.Add(usage);

            XElement sh = new XElement("ServiceHelp");
            sh.Add(new XElement("Description"));
            sh.Add(new XElement("RequestSDDL"));
            sh.Add(new XElement("ResponseSDDL"));
            sh.Add(new XElement("Errors"));
            sh.Add(new XElement("RelatedDocumentServices"));
            sh.Add(new XElement("Samples"));
            serv.Add(sh);
            return x;
        }
        public IEnumerable<JObject> ReadElement(IAixmConverter converter, JObject currentObject, XElement element)
        {
            currentObject.AddToProperties("elevation", JObject.FromObject(element));

            //If not a feature return null;
            return Enumerable.Empty<JObject>();
        }
Example #7
1
        public void RunFromInput(string inputDir, string outputFile, string name)
        {
            // setup XML file
            XNamespace ns = "http://schemas.microsoft.com/wix/2006/wi";
            XElement componentGroup = new XElement(ns + "ComponentGroup", new XAttribute("Id", "Component_" + name));
            XElement directoryRef = new XElement(ns + "DirectoryRef", new XAttribute("Id", "Dir_" + name));

            // build content
            AddDirectory(inputDir, "Component_Generated_" + name, "Dir_Generated_" + name, ns, directoryRef, componentGroup);

            // save
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", ""),
                new XElement(ns + "Wix",
                    new XAttribute("xmlns", ns.NamespaceName),
                    new XComment(String.Format(
                        "Autogenerated at {0} for directory {1}",
                        DateTime.Now.ToString("dd MMM yyy HH:mm", System.Globalization.CultureInfo.InvariantCulture),
                        inputDir
                    )),
                    new XElement(ns + "Fragment", componentGroup),
                    new XElement(ns + "Fragment", directoryRef)
                )
            );
            doc.Save(outputFile);
            OutputStream.WriteLine("Done!");
        }
        public XElement Format(Scenario scenario, int id)
        {
            var header = new XElement(
                this.xmlns + "div",
                new XAttribute("class", "scenario-heading"),
                new XElement(this.xmlns + "h2", scenario.Name));

            var tags = RetrieveTags(scenario);
            if (tags.Length > 0)
            {
                var paragraph = new XElement(this.xmlns + "p", CreateTagElements(tags.OrderBy(t => t).ToArray(), this.xmlns));
                paragraph.Add(new XAttribute("class", "tags"));
                header.Add(paragraph);
            }

            header.Add(this.htmlDescriptionFormatter.Format(scenario.Description));

            return new XElement(
                this.xmlns + "li",
                new XAttribute("class", "scenario"),
                this.htmlImageResultFormatter.Format(scenario),
                header,
                new XElement(
                    this.xmlns + "div",
                    new XAttribute("class", "steps"),
                    new XElement(
                        this.xmlns + "ul",
                        scenario.Steps.Select(step => this.htmlStepFormatter.Format(step)))));
        }
Example #9
1
        public void AddNextObxElement(string value, XElement document, string observationResultStatus)
        {
            XElement obxElement = new XElement("OBX");
            XElement obx01Element = new XElement("OBX.1");
            XElement obx0101Element = new XElement("OBX.1.1", this.m_ObxCount.ToString());
            obx01Element.Add(obx0101Element);
            obxElement.Add(obx01Element);

            XElement obx02Element = new XElement("OBX.2");
            XElement obx0201Element = new XElement("OBX.2.1", "TX");
            obx02Element.Add(obx0201Element);
            obxElement.Add(obx02Element);

            XElement obx03Element = new XElement("OBX.3");
            XElement obx0301Element = new XElement("OBX.3.1", "&GDT");
            obx03Element.Add(obx0301Element);
            obxElement.Add(obx03Element);

            XElement obx05Element = new XElement("OBX.5");
            XElement obx0501Element = new XElement("OBX.5.1", value);
            obx05Element.Add(obx0501Element);
            obxElement.Add(obx05Element);

            XElement obx11Element = new XElement("OBX.11");
            XElement obx1101Element = new XElement("OBX.11.1", observationResultStatus);
            obx11Element.Add(obx1101Element);
            obxElement.Add(obx11Element);

            this.m_ObxCount++;
            document.Add(obxElement);
        }
        private static RegionDayOfWeek[] GetRegionDayOfWeeks(XElement weekDataElement, string elementName)
        {
            List<XElement> firstDaysCountElements = weekDataElement.Elements(elementName).ToList();
            if (firstDaysCountElements.Count > 0)
            {
                List<RegionDayOfWeek> firstDaysCounts = new List<RegionDayOfWeek>();
                foreach (XElement firstDaysCountElement in firstDaysCountElements)
                {
                    RegionDayOfWeek regionDayOfWeek = new RegionDayOfWeek();
                    regionDayOfWeek.DayOfWeek = GetDayOfWeek(firstDaysCountElement.Attribute("day").Value.ToString());
                    regionDayOfWeek.RegionIds = firstDaysCountElement.Attribute("territories").Value.ToString().Split(' ');

                    if (firstDaysCountElement.Attribute("alt") != null)
                    {
                        regionDayOfWeek.Alt = firstDaysCountElement.Attribute("alt").Value.ToString();
                    }

                    if (firstDaysCountElement.Attribute("references") != null)
                    {
                        regionDayOfWeek.References = firstDaysCountElement.Attribute("references").Value.ToString();
                    }

                    firstDaysCounts.Add(regionDayOfWeek);
                }

                return firstDaysCounts.ToArray();
            }

            return null;
        }
Example #11
1
        public static XElement ToXml(ConvolutionFilter filter)
        {
            var res = new XElement(TAG_NAME,
                new XAttribute("divisor", CommonFormatter.Format(filter.Divisor)),
                new XAttribute("bias", CommonFormatter.Format(filter.Bias))
            );

            var xMatrix = new XElement("matrix");
            for (var y = 0; y < filter.MatrixY; y++) {
                var xRow = new XElement("r");
                for (var x = 0; x < filter.MatrixX; x++) {
                    var xCol = new XElement("c") { Value = CommonFormatter.Format(filter.Matrix[y, x]) };
                    xRow.Add(xCol);
                }
                xMatrix.Add(xRow);
            }
            res.Add(xMatrix);

            res.Add(new XElement("color", XColorRGBA.ToXml(filter.DefaultColor)));
            if (filter.Reserved != 0) {
                res.Add(new XAttribute("reserved", filter.Reserved));
            }
            res.Add(new XAttribute("clamp", CommonFormatter.Format(filter.Clamp)));
            res.Add(new XAttribute("preserveAlpha", CommonFormatter.Format(filter.PreserveAlpha)));
            return res;
        }
Example #12
1
        public static TableCellStyle CreateFromXElement(XElement element)
        {
            TableCellStyle cellStyle = new TableCellStyle();
            cellStyle.PopulateFromXElement(element);

            return cellStyle;
        }
 public override XElement Serialize()
 {
     XElement thisElement = new XElement(GetType().Name);
     thisElement.Add(insideEquation.Serialize());
     thisElement.Add(outerEquation.Serialize());
     return thisElement;
 }
    public static GameObject buildObjectFromXML(XElement xmlObject)
    {
        string objectName = (xmlObject.Attribute("name") != null) ? ((string)xmlObject.Attribute("name")) : ("Unit Map Object");
        string sprite = "testTile_White_Black";

        return generateObject(objectName, sprite);
    }
        protected override XElement Validate(XElement item)
        {
            // Validate with XSD
            XElement xsdErrors = this.ValidateXSD(item, HttpContext.Current.Server.MapPath(@"~\Xslt\Senior\Senior.xsd"));
            if (xsdErrors != null && xsdErrors.Elements("Error").Count() > 0)
            {
                return xsdErrors;
            }

            // Validate with Stored Proc
            string result = string.Empty;
            using (Persistence oDB = new Persistence())
            {
                Persistence.ParameterCollection parameters = new Persistence.ParameterCollection();
                parameters.Add("InputXml");
                parameters[0].Value = item.ToString();
                oDB.Execute("Masters_ConnectionString", "ValidateSeniorData", parameters, out result);
            }

            if (!string.IsNullOrEmpty(result))
            {
                XElement spErrors = XElement.Parse(result);
                spErrors.Elements("Error").Where(e => string.IsNullOrEmpty(e.Value)).Remove();

                if (spErrors.Elements("Error").Count() > 0)
                {
                    return spErrors;
                }
            }

            // SUCCESS!
            return null;

        }
        public static string Build()
        {
            bool value = false;
            string message = "Fail!";
            XElement result = new XElement("Result");

            try
            {
                using (PlayerBussiness db = new PlayerBussiness())
                {
                    BestEquipInfo[] infos = db.GetCelebByDayBestEquip();
                    foreach (BestEquipInfo info in infos)
                    {
                        result.Add(FlashUtils.CreateBestEquipInfo(info));
                    }

                    value = true;
                    message = "Success!";
                }
            }
            catch (Exception ex)
            {
                log.Error("Load CelebByDayBestEquip is fail!", ex);
            }

            result.Add(new XAttribute("value", value));
            result.Add(new XAttribute("message", message));

            return csFunction.CreateCompressXml(result, "CelebForBestEquip", false);
        }
        protected override object GetValueFromXml(XElement root, XName name, PropertyInfo prop)
        {
            var isAttribute = false;

            // Check for the DeserializeAs attribute on the property
            var options = prop.GetAttribute<DeserializeAsAttribute>();

            if (options != null)
            {
                name = options.Name ?? name;
                isAttribute = options.Attribute;
            }

            if (isAttribute)
            {
                var attributeVal = GetAttributeByName(root, name);

                if (attributeVal != null)
                {
                    return attributeVal.Value;
                }
            }

            return base.GetValueFromXml(root, name, prop);
        }
        internal CharacterAttachmentBrand(CharacterAttachmentSlot slot, XElement element)
        {
            Slot = slot;

            // Set up strings
            var brandNameAttribute = element.Attribute("Name");
            if (brandNameAttribute != null)
                Name = brandNameAttribute.Value;

            var brandThumbnailAttribute = element.Attribute("Thumbnail");
            if (brandThumbnailAttribute != null)
                ThumbnailPath = brandThumbnailAttribute.Value;

            // Get attachments
            var slotAttachmentElements = element.Elements("Attachment");

            int count = slotAttachmentElements.Count();
            if (Slot.CanBeEmpty)
                count++;

            var slotAttachments = new CharacterAttachment[count];

            for (int i = 0; i < slotAttachmentElements.Count(); i++)
            {
                var slotAttachmentElement = slotAttachmentElements.ElementAt(i);

                slotAttachments[i] = new CharacterAttachment(Slot, slotAttachmentElement);
            }

            if (Slot.CanBeEmpty)
                slotAttachments[slotAttachmentElements.Count()] = new CharacterAttachment(Slot, null);

            Attachments = slotAttachments;
        }
        /// <summary>
        /// Injects Calibre's metadata into XHTML element (for metadata part)
        /// </summary>
        /// <param name="metadata"></param>
        public void InjectData(XElement metadata)
        {
            if (!string.IsNullOrEmpty(SeriesName))
            {
                XElement serie = new XElement(MetaName);
                serie.Add(new XAttribute("name", "calibre:series"));
                serie.Add(new XAttribute("content", SeriesName));
                metadata.Add(serie);
            }

            if (SeriesIndex != 0)
            {
                XElement serieIndex = new XElement(MetaName);
                serieIndex.Add(new XAttribute("name", "calibre:series_index"));
                serieIndex.Add(new XAttribute("content", SeriesIndex));
                metadata.Add(serieIndex);
            }

            if (!string.IsNullOrEmpty(TitleForSort))
            {
                XElement title4Sort = new XElement(MetaName);
                title4Sort.Add(new XAttribute("name", "calibre:title_sort"));
                title4Sort.Add(new XAttribute("content", TitleForSort));
                metadata.Add(title4Sort);
            }

            XElement date = new XElement(MetaName);
            date.Add(new XAttribute("name", "calibre:timestamp"));
            date.Add(new XAttribute("content", DateTime.UtcNow.ToString("O")));
            metadata.Add(date);
        }
 private void GenerateNamespaceMapping(XElement namespaces) {
     if (namespaces == null)
         return;
     foreach(XElement ns in namespaces.Elements(XName.Get("Namespace", Constants.TypedXLinqNs))) {
         namespaceMapping.Add((string)ns.Attribute(XName.Get("Schema")), (string)ns.Attribute(XName.Get("Clr")));
     }
 }
Example #21
1
        public static MusicInfo FromXml(XElement musicNode, string basePath)
        {
            MusicInfo music = new MusicInfo();

            var introNode = musicNode.Element("Intro");
            var loopNode = musicNode.Element("Loop");

            XAttribute trackAttr = musicNode.Attribute("nsftrack");

            if (introNode != null || loopNode != null)
            {
                music.Type = AudioType.Wav;
                if (introNode != null) music.IntroPath = FilePath.FromRelative(introNode.Value, basePath);
                if (loopNode != null) music.LoopPath = FilePath.FromRelative(loopNode.Value, basePath);
            }
            else if (trackAttr != null)
            {
                music.Type = AudioType.NSF;

                int track;
                if (!trackAttr.Value.TryParse(out track) || track <= 0) throw new GameXmlException(trackAttr, "Sound track attribute must be an integer greater than zero.");
                music.NsfTrack = track;
            }
            else
            {
                music.Type = AudioType.Unknown;
            }

            return music;
        }
Example #22
1
 public void setUpdateData(XElement updatedata)
 {
     // XElement in ein character Struct konvertieren
     e4dnd2obsidian.e4DndCharakter cnv = new e4dnd2obsidian.e4DndCharakter(updatedata);
     character chrdata = cnv.getCharakterData();
     state.SetUpdateData(this, chrdata);
 }
        public void GenerateXml_InterfaceDynamicallyImplemented()
        {
            var targetType = new InvolvedType (typeof (TargetClass3));

              var mixinConfiguration = MixinConfiguration.BuildNew ().ForClass<TargetClass3> ().AddMixin<Mixin4> ().BuildConfiguration ();
              targetType.ClassContext = new ReflectedObject (mixinConfiguration.ClassContexts.First ());
              targetType.TargetClassDefinition = new ReflectedObject (TargetClassDefinitionUtility.GetConfiguration (targetType.Type, mixinConfiguration));
              var mixinContext = targetType.ClassContext.GetProperty ("Mixins").First ();
              var mixinDefinition = targetType.TargetClassDefinition.CallMethod ("GetMixinByConfiguredType", mixinContext.GetProperty ("MixinType").To<Type> ());

              var assemblyIdentifierGenerator = new IdentifierGenerator<Assembly> ();

              var output = new TargetCallDependenciesReportGenerator (mixinDefinition, assemblyIdentifierGenerator,
                                                             _remotionReflector, _outputFormatter).GenerateXml ();

              var expectedOutput = new XElement ("TargetCallDependencies",
                                        new XElement ("Dependency",
                                                     new XAttribute ("assembly-ref", "0"),
                                                     new XAttribute ("namespace", "System"),
                                                     new XAttribute ("name", "IDisposable"),
                                                     new XAttribute ("is-interface", true),
                                                     new XAttribute ("is-implemented-by-target", false),
                                                     new XAttribute ("is-added-by-mixin", false),
                                                     new XAttribute ("is-implemented-dynamically", true)));

              XElementComparisonHelper.Compare (output, expectedOutput);
        }
 public void FixSize(XNamespace ab, XElement role, string name, string size)
 {
     foreach (var local in role.Elements(ab + "LocalResources"))
         foreach (var storage in local.Elements(ab + "LocalStorage"))
             if (storage.Attribute("name").Value == name)
                 storage.SetAttributeValue("sizeInMB", size);
 }
        public static void Main()
        {
            var context = new GeographyEntities();
            var countries = context.Countries;

            var countriesQuery = countries
                .Where(c => c.Monasteries.Any())
                .OrderBy(c => c.CountryName)
                .Select(c => new
                {
                    c.CountryName,
                    Monasteries = c.Monasteries
                        .OrderBy(m => m.Name)
                        .Select(m => m.Name)
                });

            // Build the output XML
            var xmlMonasteries = new XElement("monasteries");
            foreach (var country in countriesQuery)
            {
                var xmlCountry = new XElement("country");
                xmlCountry.Add(new XAttribute("name", country.CountryName));

                foreach (var monastery in country.Monasteries)
                {
                    xmlCountry.Add(new XElement("monastery", monastery));
                }

                xmlMonasteries.Add(xmlCountry);
            }
            Console.WriteLine(xmlMonasteries);

            var xmlDoc = new XDocument(xmlMonasteries);
            xmlDoc.Save(@"..\..\monasteries.xml");
        }
Example #26
0
        public DataSafe(string path, string name)
        {
            Ints = new IntGetter(this);
            Longs = new LongGetter(this);
            Bools = new BoolGetter(this);
            Strings = new StringGetter(this);
            Doubles = new DoubleGetter(this);

            path = path + Path.DirectorySeparatorChar + name;
            if(!path.EndsWith(".xml",true,System.Globalization.CultureInfo.CurrentCulture))
                path +=".xml";

            this.path = path;
            this.names = new HashSet<string>();
            if (!File.Exists(path))
            {
                data = new XElement(name);
                data.Save(path);
            }
            else
            {
                data = XElement.Load(path);
                foreach (XElement elem in data.Descendants())
                {
                    names.Add(elem.Name.ToString());
                }
            }
        }
Example #27
0
        public static ConvolutionFilter FromXml(XElement xFilter)
        {
            var xMatrix = xFilter.RequiredElement("matrix");
            var xReserved = xFilter.Attribute("reserved");

            var filter = new ConvolutionFilter {
                Divisor = xFilter.RequiredDoubleAttribute("divisor"),
                Bias = xFilter.RequiredDoubleAttribute("bias")
            };

            var xRows = xMatrix.Elements().ToList();
            var height = xRows.Count;
            var width = xMatrix.Elements().First().Elements().Count();

            filter.Matrix = new double[height, width];
            for (var y = 0; y < filter.MatrixY; y++) {
                var xRow = xRows[y];
                var xCols = xRow.Elements().ToList();
                for (var x = 0; x < filter.MatrixX; x++) {
                    var xCol = xCols[x];
                    filter.Matrix[y, x] = CommonFormatter.ParseDouble(xCol.Value);
                }
            }

            filter.DefaultColor = XColorRGBA.FromXml(xFilter.RequiredElement("color").Element("Color"));
            if (xReserved != null) {
                filter.Reserved = byte.Parse(xReserved.Value);
            }
            filter.Clamp = xFilter.RequiredBoolAttribute("clamp");
            filter.PreserveAlpha = xFilter.RequiredBoolAttribute("preserveAlpha");
            return filter;
        }
        static void Main()
        {
            var context = new GeographyEntities();
            var xmlDocInput = XDocument.Load("../../rivers-query.xml");
            var queryResults = new XElement("results");
            foreach (var queryElement in xmlDocInput.XPathSelectElements("/queries/query"))
            {
                var riversQuery = BuildRiversQuery(context, queryElement);
                var riversElement = new XElement("rivers");
                riversElement.Add(new XAttribute("total-count", riversQuery.Count().ToString()));
                var maxResultsAttribute = queryElement.Attribute("max-results");
                if (maxResultsAttribute != null)
                {
                    int maxResults = int.Parse(maxResultsAttribute.Value);
                    riversQuery = riversQuery.Take(maxResults);
                }
                var riverNames = riversQuery.Select(r => r.RiverName).ToList();
                foreach (var riverName in riverNames)
                {
                    riversElement.Add(new XElement("river", riverName));
                }
                riversElement.Add(new XAttribute("listed-count", riversQuery.Count().ToString()));
                queryResults.Add(riversElement);
            }

            Console.WriteLine(queryResults);
        }
        /// <summary>
        /// Initializes a new instance of the EnumDefinition class
        /// Populates this object with information extracted from the XML
        /// </summary>
        /// <param name="theNode">XML node describing the Enum object</param>
        /// <param name="manager">The data dictionary manager constructing this type.</param>
        public EnumDefinition(XElement theNode, DictionaryManager manager)
            : base(theNode, TypeId.EnumType)
        {
            // ByteSize may be set either directly as an integer or by inference from the Type field.
            // If no Type field is present then the type is assumed to be 'int'
            if (theNode.Element("ByteSize") != null)
            {
                SetByteSize(theNode.Element("ByteSize").Value);
            }
            else
            {
                string baseTypeName = theNode.Element("Type") != null ? theNode.Element("Type").Value : "int";

                BaseType = manager.GetElementType(baseTypeName);
                BaseType = DictionaryManager.DereferenceTypeDef(BaseType);

                FixedSizeBytes = BaseType.FixedSizeBytes.Value;
            }

            // Common properties are parsed by the base class.
            // Remaining properties are the Name/Value Literal elements
            List<LiteralDefinition> theLiterals = new List<LiteralDefinition>();
            foreach (var literalNode in theNode.Elements("Literal"))
            {
                theLiterals.Add(new LiteralDefinition(literalNode));
            }

            m_Literals = new ReadOnlyCollection<LiteralDefinition>(theLiterals);

            // Check the name. If it's null then make one up
            if (theNode.Element("Name") == null)
            {
                Name = String.Format("Enum_{0}", Ref);
            }
        }
 public override void DeSerialize(XElement xElement)
 {
     var elements = xElement.Elements().ToArray();
     insideEquation.DeSerialize(elements[0]);
     outerEquation.DeSerialize(elements[1]);
     CalculateSize();
 }
Example #31
0
        protected override object CreateAndFillObject(System.Xml.Linq.XElement propertyXml)
        {
            XElement mcdElement = propertyXml.Element("McdConfig").Element("Map");

            if (mcdElement == null)
            {
                return(null);
            }
            IMap   map      = null;
            string tempFile = AppDomain.CurrentDomain.BaseDirectory + "temp.mcd";

            try
            {
                XDocument doc = new XDocument();
                doc.Add(mcdElement);
                doc.Save(tempFile);
                map = MapFactory.LoadMapFrom(tempFile);
            }
            finally
            {
                File.Delete(tempFile);
            }
            return(map);
        }
Example #32
0
        private void Transit(System.Xml.Linq.XElement expression)
        {
            if (expression == null)
            {
                return;
            }

            if (expression.Elements().Any())
            {
                foreach (var element in expression.Elements())
                {
                    Transit(element);
                }
            }
            var attirbs = from attirb in expression.Attributes()
                          where attirb.Value == typeof(DTO).FullName
                          select attirb;

            foreach (var attrib in attirbs)
            {
                attrib.Value = typeof(Entity).FullName;
                //expression.ReplaceAttributes(new XAttribute("Name", typeof(Entity).FullName));
            }
        }
        public void AddToElement(SXL.XElement parent, int ix)
        {
            var el = XMLUtil.CreateVisioSchema2003Element("Para");

            el.SetAttributeValueInt("IX", ix);
            el.Add(this.IndFirst.ToXml("IndFirst"));
            el.Add(this.IndLeft.ToXml("IndLeft"));
            el.Add(this.IndRight.ToXml("IndRight"));

            el.Add(this.SpLine.ToXml("SpLine"));
            el.Add(this.SpBefore.ToXml("SpBefore"));
            el.Add(this.SpAfter.ToXml("SpAfter"));

            el.Add(this.HorzAlign.ToXml("HorzAlign"));
            el.Add(this.Bullet.ToXml("Bullet"));
            el.Add(this.BulletStr.ToXml("BulletStr"));
            el.Add(this.BulletFont.ToXml("BulletFont"));
            el.Add(this.LocalizeBulletFont.ToXml("LocalizeBulletFont"));
            el.Add(this.BulletFontSize.ToXml("BulletFontSize"));
            el.Add(this.TextPosAfterBullet.ToXml("TextPosAfterBullet"));
            el.Add(this.Flags.ToXml("Flags"));

            parent.Add(el);
        }
        public void TestTitleExistsUnderElement
        (
            XCRI.Validation.ContentValidation.ElementValidator ev,
            System.Xml.Linq.XElement element,
            int expectedFailures,
            int expectedSuccesses
        )
        {
            var v = new XCRI.Validation.ContentValidation.NumberValidator()
            {
                XPathSelector          = "count(./dc:title)",
                ExceptionMessage       = "All providers must contain a title, which should be the trading name.",
                FailedValidationStatus = XCRI.Validation.ContentValidation.ValidationStatus.Exception,
                Minimum          = 1,
                ValidationGroup  = "Structure",
                NamespaceManager = ev.NamespaceManager
            };

            ev.Validators.Add(v);
            var vr = ev
                     .Validate(element)
                     .Where(r => r.Message == v.ExceptionMessage);

            Assert.AreEqual <int>(1, vr.Count());
            ValidateResults
            (
                result: vr.ElementAt(0),
                expectedStatus: (0 == expectedFailures)
                    ? XCRI.Validation.ContentValidation.ValidationStatus.Passed
                    : XCRI.Validation.ContentValidation.ValidationStatus.Exception,
                expectedInstances: expectedFailures + expectedSuccesses,
                expectedFailedCount: expectedFailures,
                expectedSuccessfulCount: expectedSuccesses
            );
            ev.Validators.Clear();
        }
Example #35
0
 public static VA.Drawing.ColorRGB AttributeAsColor(this SXL.XElement el, string name,
                                                    VA.Drawing.ColorRGB def)
 {
     return(VA.Scripting.XmlUtil.GetAttributeValue(el, name, def, VA.Drawing.ColorRGB.ParseWebColor));
 }
Example #36
0
        internal void WriteFixedWidth(System.Xml.Linq.XElement CommandNode, DataTable Table, string outputStrmFilePath)
        {
            try
            {
                int StartAt = CommandNode.Attribute("StartAt") != null?int.Parse(CommandNode.Attribute("StartAt").Value) : 0;

                var positions = from c in CommandNode.Descendants("Position")
                                orderby int.Parse(c.Attribute("Start").Value) ascending
                                select new
                {
                    Name          = c.Attribute("Name").Value,
                    Start         = int.Parse(c.Attribute("Start").Value) - StartAt,
                    Length        = int.Parse(c.Attribute("Length").Value),
                    DefaultValue  = c.Attribute("DefaultValue") != null?c.Attribute("DefaultValue").Value : string.Empty, //optional,
                    Type          = c.Attribute("Type") != null?c.Attribute("Type").Value                 : string.Empty, //optional
                    ExistsInTable = Table.Columns.Contains(c.Attribute("Name").Value)
                };

                int lineLength = positions.Last().Start + positions.Last().Length;

                using (var stream = new StreamWriter(outputStrmFilePath, true))
                {
                    // Use stream
                    foreach (DataRow row in Table.Rows)
                    {
                        StringBuilder line = new StringBuilder(lineLength);
                        foreach (var p in positions)

                        {
                            //check if the column exists in the datatable
                            if (p.ExistsInTable)
                            {
                                if (!string.IsNullOrEmpty(p.DefaultValue))
                                {
                                    line.Insert(p.Start, (p.DefaultValue ?? "").ToString().PadRight(p.Length, ' '));
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(p.Type) && p.Type == "N" && !string.IsNullOrEmpty(row[p.Name].ToString()))
                                    {
                                        int    lengthallotted = p.Length - p.Start;
                                        string withzeroes     = string.Empty;
                                        //check if the data is decimal, remove the decimal
                                        //padd zeroes to the right
                                        if (row[p.Name].ToString().Contains("."))
                                        {
                                            string decimalremoved = row[p.Name].ToString().Replace(".", string.Empty);
                                            withzeroes = string.Empty.PadLeft(lengthallotted - decimalremoved.Length, '0') + decimalremoved.ToString();
                                            line.Insert(p.Start, withzeroes);
                                        }
                                        else
                                        {
                                            withzeroes = lengthallotted > row[p.Name].ToString().Length ? string.Empty.PadLeft(lengthallotted - row[p.Name].ToString().Length, '0') + row[p.Name].ToString() : row[p.Name].ToString();
                                            //withzeroes = string.Empty.PadLeft(lengthallotted - row[p.Name].ToString().Length, '0') + row[p.Name].ToString();
                                            line.Insert(p.Start, withzeroes);
                                        }
                                    }
                                    else
                                    {
                                        line.Insert(p.Start, (row[p.Name] ?? "").ToString().PadRight(p.Length, ' '));
                                    }
                                }
                            }
                            else
                            {
                                //log an error and exit
                                _logger.LogError("Error while generating POAPL file. Column name mismatch for--{column}", p.Name);
                                break;
                            }
                        }
                        stream.WriteLine(line.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Method Name -- WriteFixedWidth: {Reason}", ex.Message);
            }
        }
Example #37
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int resultId = Int32.Parse(Request["ResultId"]);
                if (resultId == CommunicationService.StartRssFeedConstant)
                {
                    InnerText = "<h1>Benvenuto</h1>";
                }
                else
                {
                    StorageManager manager = new StorageManager();
                    Result         result  = manager.getEntityByID <Result>(resultId);


                    if (result != null)
                    {
                        Publication pub = result.Publication;
                        if (pub == null)
                        {
                            pub = result.CompilationRequest.Publication;
                        }

                        Uri    uri   = new Uri(pub.URIUpload);
                        string token = uri.Query.Substring(7);
                        if (pub.publicationID != Int32.Parse(Request["PubId"]) ||
                            !(Request["token"] != null && token.Equals(Request["token"])))
                        {
                            Response.StatusCode = 400;
                            Response.Write("HTTP 400 BAD REQUEST");
                            Response.End();
                            return;
                        }
                        StringBuilder            builder = new StringBuilder();
                        System.Xml.Linq.XElement xmlRes  = result.xmlResult;
                        builder.Append("<h1>" + XmlConvert.DecodeName(xmlRes.Name.LocalName) + "</h1>");
                        System.Collections.Generic.IEnumerable <XElement> elements = xmlRes.Elements();
                        foreach (System.Xml.Linq.XElement el in elements)
                        {
                            builder.Append("<div>");
                            builder.Append("<h3 class=\"step\">" + XmlConvert.DecodeName(el.Name.LocalName) + "</h3>");
                            System.Collections.Generic.IEnumerable <XElement> childsEnum = el.Elements();
                            foreach (System.Xml.Linq.XElement quest in childsEnum)
                            {
                                builder.Append("<p> <span class=\"question\">" + XmlConvert.DecodeName(quest.Name.LocalName) +
                                               " = </span>  <span class=\"answer\">" + XmlConvert.DecodeName(quest.Value) + "</span> </p>");
                            }
                            builder.Append("</div>");
                        }
                        InnerText = builder.ToString();
                    }
                    else
                    {
                        Response.StatusCode = 400;
                        Response.Write("HTTP 400 BAD REQUEST");
                        Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                if (Response.StatusCode != 400)
                {
                    Response.StatusCode = 400;
                    Response.Write("HTTP 400 BAD REQUEST");
                    Response.End();
                }
            }
        }
Example #38
0
 public static VisioAutomation.Models.Color.ColorRgb AttributeAsColor(this SXL.XElement el, string name,
                                                                      VisioAutomation.Models.Color.ColorRgb def)
 {
     return(el.GetAttributeValue(name, def, VisioAutomation.Models.Color.ColorRgb.ParseWebColor));
 }
Example #39
0
    public bool AddTypeElement(System.Xml.Linq.XElement elemtype)
    {
        if (store == null) //nowhere to put the image.
        {
            Debug.LogError("Texture Storage is Null: " + elemtype);
            return(false);
        }

        XAttribute patternAtt = elemtype.Attribute("pattern");

        if (patternAtt == null)
        {
            Debug.LogError("No pattern attribute in " + elemtype);
            //Add error message here
            return(false);
        }
        string patternPath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), patternAtt.Value);

        patternPath = Path.GetFullPath(patternPath);

        if (!File.Exists(patternPath))
        {
            Debug.LogError("File not found: " + patternPath);
            return(false);
        }

        byte[] patternData = File.ReadAllBytes(patternPath);

        Texture2D patternTex = new Texture2D(2, 2);

        patternTex.LoadImage(patternData);

        if (patternTex.width > GameSettings.Instance.rendering.maxTextureSize || patternTex.height > GameSettings.Instance.rendering.maxTextureSize)
        {
            if (patternTex.width > patternTex.height)
            {
                TextureScale.Bilinear(
                    patternTex,
                    GameSettings.Instance.rendering.maxTextureSize,
                    GameSettings.Instance.rendering.maxTextureSize * patternTex.height / patternTex.width);
            }
            else
            {
                TextureScale.Bilinear(
                    patternTex,
                    GameSettings.Instance.rendering.maxTextureSize * patternTex.width / patternTex.height,
                    GameSettings.Instance.rendering.maxTextureSize);
            }
        }

        XAttribute specularAtt = elemtype.Attribute("specular");

        if (specularAtt == null)
        {
            Debug.LogError("No specular attribute in " + elemtype);
            //Add error message here
            return(false);
        }
        string specularPath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), specularAtt.Value);

        specularPath = Path.GetFullPath(specularPath);

        if (!File.Exists(specularPath))
        {
            Debug.LogError("File not found: " + specularPath);
            return(false);
        }

        byte[] specularData = File.ReadAllBytes(specularPath);

        Texture2D specularTex = new Texture2D(2, 2);

        specularTex.LoadImage(specularData);

        if (specularTex.width != patternTex.width || specularTex.height != patternTex.height)
        {
            TextureScale.Bilinear(specularTex, patternTex.width, patternTex.height);
        }

        Texture2D combinedMap = new Texture2D(patternTex.width, patternTex.height, TextureFormat.ARGB32, false, false);

        combinedMap.name = patternPath + specularAtt.Value;

        Color[] patternColors  = patternTex.GetPixels();
        Color[] specularColors = specularTex.GetPixels();

        for (int i = 0; i < patternColors.Length; i++)
        {
            patternColors[i] = new Color(patternColors[i].r, patternColors[i].g, patternColors[i].b, specularColors[i].linear.r);
        }

        combinedMap.SetPixels(patternColors);
        combinedMap.Apply();


        storageIndex = store.AddTexture(combinedMap);
        return(true);
    }
 public static double AttributeAsInches(this SXL.XElement el, string name, double def)
 {
     return(XmlUtil.GetAttributeValue(el, name, def, s => XmlExtensions.PointsToInches(double.Parse(s))));
 }
 public void UpgradeParams(System.Xml.Linq.XElement param)
 {
 }
Example #42
0
 public override void LoadXml(System.Xml.Linq.XElement xmlNode)
 {
     // nothing needed
 }
Example #43
0
 public bool CanCreateFormatter(System.Xml.Linq.XElement element)
 {
     return(this.GetFormatterElement(element) != null);
 }
Example #44
0
 protected override void AddToTypeEl(SXL.XElement parent)
 {
     parent.Value = this.Double.ToString(System.Globalization.CultureInfo.InvariantCulture);
 }
Example #45
0
        public static DoubleValue XmlToValue(SXL.XElement parent)
        {
            var bv = new DoubleValue(double.Parse(parent.Value));

            return(bv);
        }
Example #46
0
 public SvgReader(System.Xml.Linq.XElement xElement)
 {
     this.source = xElement;
 }
Example #47
0
 public virtual void AddToElement(SXL.XElement parent)
 {
     throw new System.Exception();
 }
Example #48
0
 public static double AttributeAsInches(this SXL.XElement el, string name, double def)
 {
     return(VA.Scripting.XmlUtil.GetAttributeValue(el, name, def, s => PointsToInches(double.Parse(s))));
 }
Example #49
0
 public object ParseArgumentValue(System.Xml.Linq.XElement ele)
 {
     return(null);
 }
Example #50
0
        public override void ToEntity(System.Xml.Linq.XElement xElement, PolygonElementEntity entity)
        {
            WorldElementTransformer.Instance.ToEntity(xElement, entity);

            entity.Vertices = VerticesTransformer.Instance.ToEntity(xElement.Attribute(STR_Vertices));
        }
 internal override void AddAttributes(System.Xml.Linq.XElement controlElement)
 {
     base.AddAttributes(controlElement);
     controlElement.Add(new XAttribute("Width", Width.ToString() + "px"));
     controlElement.Attribute("LabelText").Remove();
 }
Example #52
0
        public void Initialize(System.Xml.Linq.XElement xmlSettings)
        {
            try
            {
                gatewaySettings = new GatewaySettings();

                //get transaction url attribute
                if (xmlSettings.Attribute("transactionUrl") != null)
                {
                    gatewaySettings.TransactionURL = xmlSettings.Attribute("transactionUrl").Value;
                }

                if (xmlSettings.Attribute("transactionKey") != null)
                {
                    gatewaySettings.TransactionKey = xmlSettings.Attribute("transactionKey").Value;
                }

                if (xmlSettings.Attribute("delimitedData") != null)
                {
                    gatewaySettings.DelimData = xmlSettings.Attribute("delimitedData").Value;
                }

                if (xmlSettings.Attribute("DelimChar") != null)
                {
                    gatewaySettings.DelimChar = xmlSettings.Attribute("DelimChar").Value;
                }

                if (xmlSettings.Attribute("version") != null)
                {
                    gatewaySettings.Version = xmlSettings.Attribute("version").Value;
                }

                if (xmlSettings.Attribute("transactionTest") != null)
                {
                    gatewaySettings.TestMode = xmlSettings.Attribute("transactionTest").Value;
                }

                if (xmlSettings.Attribute("deviceType") != null)
                {
                    gatewaySettings.DeviceType = xmlSettings.Attribute("deviceType").Value;
                }

                if (xmlSettings.Attribute("marketType") != null)
                {
                    gatewaySettings.MarketType = xmlSettings.Attribute("marketType").Value;
                }

                if (xmlSettings.Attribute("requestType") != null)
                {
                    gatewaySettings.RequestType = xmlSettings.Attribute("requestType").Value;
                }

                if (xmlSettings.Attribute("merchantId") != null)
                {
                    gatewaySettings.MerchantId = xmlSettings.Attribute("merchantId").Value;
                }

                if (xmlSettings.Attribute("user") != null)
                {
                    gatewaySettings.User = xmlSettings.Attribute("user").Value;
                }

                if (xmlSettings.Attribute("password") != null)
                {
                    gatewaySettings.Password = xmlSettings.Attribute("password").Value;
                }

                if (string.IsNullOrEmpty(gatewaySettings.TransactionURL))
                {
                    throw new PaymentProviderException("TransactionURL cannot be null");
                }

                if (string.IsNullOrEmpty(gatewaySettings.MerchantId))
                {
                    throw new PaymentProviderException("MerchantId cannot be null");
                }

                if (string.IsNullOrEmpty(gatewaySettings.DelimData))
                {
                    gatewaySettings.DelimData = "TRUE";
                }

                if (string.IsNullOrEmpty(gatewaySettings.DelimChar))
                {
                    gatewaySettings.DelimChar = "|";
                }

                if (string.IsNullOrEmpty(gatewaySettings.TestMode))
                {
                    gatewaySettings.TestMode = "FALSE";
                }
            }
            catch (Exception ex)
            {
                throw new PaymentProviderException("An error occured while reading the gateway settings", ex);
            }
        }
 public Constraint Parse(System.Xml.Linq.XElement e)
 {
     return((Constraint)parser.Parse(e));
 }
Example #54
0
    public bool AddTypeElement(System.Xml.Linq.XElement elemtype)
    {
        if (store == null) //nowhere to put the image.
        {
            Debug.LogError("Texture Storage is Null: " + elemtype);
            return(false);
        }

        XAttribute normalAtt = elemtype.Attribute("normal");

        if (normalAtt == null)
        {
            Debug.LogError("No normal map in " + elemtype);
            //Add error message here
            return(false);
        }
        string normalPath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), normalAtt.Value);

        normalPath = Path.GetFullPath(normalPath);

        if (!File.Exists(normalPath))
        {
            Debug.LogError("File not found: " + normalPath);
            return(false);
        }

        byte[]    normalData = File.ReadAllBytes(normalPath);
        Texture2D normalMap  = new Texture2D(2, 2, TextureFormat.ARGB32, false, true);

        normalMap.LoadImage(normalData);

        XAttribute specularAtt = elemtype.Attribute("specular");

        if (specularAtt == null)
        {
            Debug.LogError("No specular map in " + elemtype);
            //Add error message here
            return(false);
        }
        string specularPath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), specularAtt.Value);

        specularPath = Path.GetFullPath(specularPath);

        if (!File.Exists(specularPath))
        {
            Debug.LogError("File not found: " + specularPath);
            return(false);
        }

        byte[]    specularData = File.ReadAllBytes(specularPath);
        Texture2D specularMap  = new Texture2D(2, 2, TextureFormat.ARGB32, false, false);

        specularMap.LoadImage(specularData);

        if ((specularMap.width != normalMap.width) || (specularMap.height != normalMap.height))
        {
            TextureScale.Bilinear(specularMap, normalMap.width, normalMap.height);
        }

        XAttribute occlusionAtt = elemtype.Attribute("occlusion");

        if (occlusionAtt == null)
        {
            Debug.LogError("No occlusion map in " + elemtype);
            //Add error message here
            return(false);
        }
        string occlusionPath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), occlusionAtt.Value);

        occlusionPath = Path.GetFullPath(occlusionPath);

        if (!File.Exists(occlusionPath))
        {
            Debug.LogError("File not found: " + occlusionPath);
            return(false);
        }

        byte[] occlusionData = File.ReadAllBytes(occlusionPath);

        Texture2D occlusionMap = new Texture2D(2, 2, TextureFormat.ARGB32, false, true);

        occlusionMap.LoadImage(occlusionData);

        if (occlusionMap.width != normalMap.width || occlusionMap.height != normalMap.height)
        {
            TextureScale.Bilinear(occlusionMap, normalMap.width, normalMap.height);
        }

        Texture2D combinedMap = new Texture2D(normalMap.width, normalMap.height, TextureFormat.ARGB32, false, true);

        combinedMap.name = normalPath + occlusionAtt.Value + specularAtt.Value;

        Color[] normalColors    = normalMap.GetPixels();
        Color[] occlusionColors = occlusionMap.GetPixels();
        Color[] specularColors  = specularMap.GetPixels();

        if (normalColors.Length != specularColors.Length)
        {
            Debug.LogError("Maps aren't same size!");
        }

        for (int i = 0; i < normalColors.Length; i++)
        {
            normalColors[i] = new Color(occlusionColors[i].r, normalColors[i].g, specularColors[i].r, normalColors[i].r);
        }

        combinedMap.SetPixels(normalColors);
        combinedMap.Apply();

        storageIndex = store.AddTexture(combinedMap);
        return(true);
    }
Example #55
0
 public override System.Xml.Linq.XElement ToXml(System.Xml.Linq.XElement baseElement, bool AddCommonAttributes)
 {
     baseElement.SetAttributeValue("name", this.Name);
     AddToXMLChildElementsByName(baseElement, "classes", this.Classes);
     return(baseElement);
 }
 protected override void InnerInitializeProperties(System.Xml.Linq.XElement element)
 {
     this.FillProperty(m => m.OpenOrderId);
     this.FillProperty(m => m.DeliveryQuantity);
     this.FillProperty(m => m.DeliveryLot);
 }
Example #57
0
 public Message BuildMessage(System.Xml.Linq.XElement elem, string strXML)
 {
     return(null);
 }
Example #58
0
        public override bool BuildCfg(System.Xml.Linq.XElement xe, ref string reStr)
        {
            if (!base.BuildCfg(xe, ref reStr))
            {
                return(false);
            }
            XElement selfDataXE = xe.Element("SelfDatainfo");

            this.portCata = int.Parse(selfDataXE.Element("PortType").Value.ToString());


            if (selfDataXE.Attribute("portSeq") != null)
            {
                this.portSeq = int.Parse(selfDataXE.Attribute("portSeq").Value.ToString());
            }
            if (selfDataXE.Attribute("capacity") != null)
            {
                this.PortinBufCapacity = int.Parse(selfDataXE.Attribute("capacity").Value.ToString());
            }
            if (selfDataXE.Attribute("emptyPalletCheckIn") != null)
            {
                if (selfDataXE.Attribute("emptyPalletCheckIn").Value.ToString().ToUpper() == "TRUE")
                {
                    this.EmptyPalletInputEnabled = true;
                }
            }

            if (selfDataXE.Attribute("bindedTask") != null)
            {
                string[] strArray = selfDataXE.Attribute("bindedTask").Value.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (strArray != null)
                {
                    if (strArray.Count() > 0)
                    {
                        foreach (string strTask in strArray)
                        {
                            bindedTaskList.Add((SysCfg.EnumAsrsTaskType)Enum.Parse(typeof(SysCfg.EnumAsrsTaskType), strTask));
                        }

                        if (this.portCata == 1)
                        {
                            this.bindedTaskInput = (SysCfg.EnumAsrsTaskType)Enum.Parse(typeof(SysCfg.EnumAsrsTaskType), strArray[0]);
                        }
                        else if (this.portCata == 2)
                        {
                            this.bindedTaskOutput = (SysCfg.EnumAsrsTaskType)Enum.Parse(typeof(SysCfg.EnumAsrsTaskType), strArray[0]);
                        }
                        else if (this.portCata == 3)
                        {
                            this.bindedTaskInput = (SysCfg.EnumAsrsTaskType)Enum.Parse(typeof(SysCfg.EnumAsrsTaskType), strArray[0]);
                            if (strArray.Count() > 1)
                            {
                                this.bindedTaskOutput = (SysCfg.EnumAsrsTaskType)Enum.Parse(typeof(SysCfg.EnumAsrsTaskType), strArray[1]);
                            }
                        }
                    }
                }
            }
            if (selfDataXE.Attribute("barcodeScanRequire") != null)
            {
                if (selfDataXE.Attribute("barcodeScanRequire").Value.ToString().ToUpper() == "TRUE")
                {
                    BarcodeScanRequire = true;
                }
            }
            return(true);
        }
Example #59
0
    public bool AddTypeElement(System.Xml.Linq.XElement elemtype)
    {
        XAttribute fileAtt = elemtype.Attribute("file");

        if (fileAtt == null)
        {
            //Add error message here
            return(false);
        }


        if (storeContainer.shapeStore != null &&
            (elemtype.Attribute("normal") != null ||
             elemtype.Attribute("occlusion") != null ||
             elemtype.Attribute("alpha") != null
            ))
        {
            _normalTexture = new NormalContent();
            _normalTexture.ExternalStorage = storeContainer.shapeStore;
            if (!_normalTexture.AddTypeElement(elemtype))
            {
                _normalTexture = null;
            }
        }

        if (storeContainer.specialStore != null &&
            (elemtype.Attribute("metallic") != null ||
             elemtype.Attribute("illumination") != null
            ))
        {
            _specialTexture = new SpecialMapContent();
            _specialTexture.ExternalStorage = storeContainer.specialStore;
            if (!_specialTexture.AddTypeElement(elemtype))
            {
                _specialTexture = null;
            }
        }

        if (storeContainer.materialStore != null &&
            (elemtype.Attribute("pattern") != null ||
             elemtype.Attribute("specular") != null
            ))
        {
            _matTexture = new TextureContent();
            _matTexture.ExternalStorage = storeContainer.materialStore;
            if (!_matTexture.AddTypeElement(elemtype))
            {
                _matTexture = null;
            }
        }


        if (fileAtt.Value == "NONE")
        {
            //This means we don't want to actually store a mesh,
            //but still want to use the category.
            MeshData = new Dictionary <MeshLayer, CPUMesh>();
        }
        else
        {
            string filePath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), fileAtt.Value);
            filePath = Path.GetFullPath(filePath);

            //	Load the OBJ in
            var lStream  = new FileStream(filePath, FileMode.Open);
            var lOBJData = OBJLoader.LoadOBJ(lStream);
            lStream.Close();
            MeshData = new Dictionary <MeshLayer, CPUMesh>();
            Mesh tempMesh = new Mesh();
            foreach (MeshLayer layer in Enum.GetValues(typeof(MeshLayer)))
            {
                MeshLayer translatedLayer;
                if (layer == MeshLayer.GrowthCutout1 ||
                    layer == MeshLayer.GrowthCutout2 ||
                    layer == MeshLayer.GrowthCutout3)
                {
                    translatedLayer = MeshLayer.GrowthCutout;
                }
                else if (layer == MeshLayer.GrowthMaterial1 ||
                         layer == MeshLayer.GrowthMaterial2 ||
                         layer == MeshLayer.GrowthMaterial3)
                {
                    translatedLayer = MeshLayer.GrowthMaterial;
                }
                else if (layer == MeshLayer.GrowthTransparent1 ||
                         layer == MeshLayer.GrowthTransparent2 ||
                         layer == MeshLayer.GrowthTransparent3)
                {
                    translatedLayer = MeshLayer.GrowthTransparent;
                }
                else
                {
                    translatedLayer = layer;
                }
                tempMesh.LoadOBJ(lOBJData, (layer.ToString()));
                if (tempMesh == null || tempMesh.vertexCount == 0)
                {
                    continue;
                }
                tempMesh.name = filePath + "." + layer.ToString();
                if (translatedLayer == MeshLayer.GrowthCutout ||
                    translatedLayer == MeshLayer.GrowthMaterial ||
                    translatedLayer == MeshLayer.GrowthTransparent)
                {
                    for (int i = (int)translatedLayer; i < (int)translatedLayer + 4; i++)
                    {
                        //This is because the tree growths can be in any order
                        //So we just copy the un-numbered one onto the rest.
                        MeshData[(MeshLayer)i] = new CPUMesh(tempMesh);
                    }
                }
                else
                {
                    MeshData[layer] = new CPUMesh(tempMesh);
                }
                tempMesh.Clear();
            }
            lStream  = null;
            lOBJData = null;
        }

        XAttribute rotAtt = elemtype.Attribute("rotation");

        if (rotAtt == null)
        {
            rotationType = RotationType.None;
        }
        else
        {
            try
            {
                rotationType = (RotationType)Enum.Parse(typeof(RotationType), rotAtt.Value);
            }
            catch
            {
                rotationType = RotationType.None;
                Debug.Log("Unknown rotation value: " + rotAtt.Value);
            }
        }
        return(true);
    }
Example #60
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                    = parser.ParseString(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)
                    {
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription = null;

                        // 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 and we just need to update it
                        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, delete it before adding it again!
                            WriteWarning(string.Format("Workflow Subscription '{0}' already exists. It will be updated.", subscription.Name), ProvisioningMessageType.Warning);
                            workflowSubscription = existingWorkflowSubscriptions.FirstOrDefault((s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId));

                            if (workflowSubscription != null)
                            {
                                subscriptionService.DeleteSubscription(workflowSubscription.Id);
                                web.Context.ExecuteQueryRetry();
                            }
                        }

#if ONPREMISES
                        // Create the WorkflowDefinition instance
                        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
                        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

                        if (workflowSubscription != null)
                        {
                            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);
        }