Exemplo n.º 1
0
        public void Write(string path)
        {
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            XmlWriter writer = XmlWriter.Create(path, settings);

            // Begins the document.
            writer.WriteStartDocument();

            /// Writes the root element and its GUID.
            writer.WriteStartElement("FieldData");

            // Goals
            writer.WriteStartElement("Goals");
            writer.WriteStartElement("RedGoals");
            writer.WriteEndElement();
            writer.WriteStartElement("BlueGoals");
            writer.WriteEndElement();
            writer.WriteEndElement();

            // Gamepieces
            // At some point this should actually be part of the BXDF, not user configurable.
            writer.WriteStartElement("General");
            writer.WriteStartElement("Gamepieces");
            foreach (Gamepiece gamepiece in gamepieces)
            {
                writer.WriteStartElement("gamepiece");
                writer.WriteAttributeString("id", gamepiece.id);
                writer.WriteAttributeString("holdinglimit", gamepiece.holdingLimit.ToString());

                BXDVector3 spawn = new BXDVector3(gamepiece.spawnpoint.x * -0.01, gamepiece.spawnpoint.y * 0.01, gamepiece.spawnpoint.z * 0.01);
                writer.WriteAttributeString("x", spawn.x.ToString());
                writer.WriteAttributeString("y", spawn.y.ToString());
                writer.WriteAttributeString("z", spawn.z.ToString());

                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            // Spawn Points
            // Create a spawnpoint if none were specified
            if (spawnpoints.Length == 0)
            {
                spawnpoints = new BXDVector3[] { new BXDVector3(0, 3, 0) }
            }
            ;

            foreach (BXDVector3 point in spawnpoints)
            {
                writer.WriteStartElement("RobotSpawnPoint");

                BXDVector3 spawn = new BXDVector3(point.x * -0.01, point.y * 0.01, point.z * 0.01);
                writer.WriteAttributeString("x", spawn.x.ToString());
                writer.WriteAttributeString("y", spawn.y.ToString());
                writer.WriteAttributeString("z", spawn.z.ToString());

                writer.WriteEndElement();
            }

            // Ends the document.
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();

            // Close the writer.
            writer.Close();
        }
    }
Exemplo n.º 2
0
        protected void wizPackage_ActiveStepChanged(object sender, EventArgs e)
        {
            switch (wizPackage.ActiveStepIndex)
            {
            case 1:     //Display the files
                if (chkUseManifest.Checked)
                {
                    wizPackage.ActiveStepIndex = 3;
                }
                GetFiles(string.IsNullOrEmpty(txtFiles.Text));
                includeSourceRow.Visible = _Writer.HasProjectFile || _Writer.AppCodeFiles.Count > 0;
                break;

            case 2:     //Display the assemblies
                if (_Writer.IncludeAssemblies)
                {
                    GetAssemblies(string.IsNullOrEmpty(txtAssemblies.Text));
                }
                else
                {
                    wizPackage.ActiveStepIndex = 3;
                }
                break;

            case 3:     //Display the manfest
                if (chkUseManifest.Checked)
                {
                    if (string.IsNullOrEmpty(cboManifests.SelectedValue))
                    {
                        //Use Database
                        var sb       = new StringBuilder();
                        var settings = new XmlWriterSettings();
                        settings.ConformanceLevel   = ConformanceLevel.Fragment;
                        settings.OmitXmlDeclaration = true;
                        settings.Indent             = true;

                        _Writer.WriteManifest(XmlWriter.Create(sb, settings), Package.Manifest);

                        txtManifest.Text = sb.ToString();
                    }
                    else
                    {
                        string       filename        = Path.Combine(Server.MapPath(_Writer.BasePath), cboManifests.SelectedValue);
                        StreamReader objStreamReader = File.OpenText(filename);
                        txtManifest.Text = objStreamReader.ReadToEnd();
                    }
                }
                else
                {
                    CreateManifest();
                }
                if (!chkReviewManifest.Checked)
                {
                    wizPackage.ActiveStepIndex = 4;
                }
                break;

            case 4:
                txtManifestName.Text = Package.Owner + "_" + Package.Name;
                if (chkUseManifest.Checked)
                {
                    txtArchiveName.Text = Package.Owner + "_" + Package.Name + "_" + Globals.FormatVersion(Package.Version) + "_Install.zip";
                    chkManifest.Checked = true;
                    trManifest1.Visible = false;
                    trManifest2.Visible = false;
                }
                else
                {
                    if (chkIncludeSource.Checked)
                    {
                        txtArchiveName.Text = Package.Owner + "_" + Package.Name + "_" + Globals.FormatVersion(Package.Version) + "_Source.zip";
                    }
                    else
                    {
                        txtArchiveName.Text = Package.Owner + "_" + Package.Name + "_" + Globals.FormatVersion(Package.Version) + "_Install.zip";
                    }
                }
                if (!txtManifestName.Text.ToLower().EndsWith(".dnn"))
                {
                    txtManifestName.Text = txtManifestName.Text + ".dnn";
                }
                wizPackage.DisplayCancelButton = false;
                break;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(CreateFieldLevelEncryptionConfigRequest publicRequest)
        {
            var request = new DefaultRequest(publicRequest, "Amazon.CloudFront");

            request.HttpMethod        = "POST";
            request.ResourcePath      = "/2020-05-31/field-level-encryption";
            request.MarshallerVersion = 2;

            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
            {
                Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true
            }))
            {
                if (publicRequest.IsSetFieldLevelEncryptionConfig())
                {
                    xmlWriter.WriteStartElement("FieldLevelEncryptionConfig", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                    if (publicRequest.FieldLevelEncryptionConfig.IsSetCallerReference())
                    {
                        xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequest.FieldLevelEncryptionConfig.CallerReference));
                    }

                    if (publicRequest.FieldLevelEncryptionConfig.IsSetComment())
                    {
                        xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequest.FieldLevelEncryptionConfig.Comment));
                    }


                    if (publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig != null)
                    {
                        xmlWriter.WriteStartElement("ContentTypeProfileConfig", "http://cloudfront.amazonaws.com/doc/2020-05-31/");

                        if (publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig.ContentTypeProfiles != null)
                        {
                            xmlWriter.WriteStartElement("ContentTypeProfiles", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                            var publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItems = publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig.ContentTypeProfiles.Items;
                            if (publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItems != null && publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItems.Count > 0)
                            {
                                xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                foreach (var publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue in publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItems)
                                {
                                    if (publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue != null)
                                    {
                                        xmlWriter.WriteStartElement("ContentTypeProfile", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                        if (publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue.IsSetContentType())
                                        {
                                            xmlWriter.WriteElementString("ContentType", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue.ContentType));
                                        }

                                        if (publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue.IsSetFormat())
                                        {
                                            xmlWriter.WriteElementString("Format", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue.Format));
                                        }

                                        if (publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue.IsSetProfileId())
                                        {
                                            xmlWriter.WriteElementString("ProfileId", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionConfigContentTypeProfileConfigContentTypeProfilesItemsValue.ProfileId));
                                        }

                                        xmlWriter.WriteEndElement();
                                    }
                                }
                                xmlWriter.WriteEndElement();
                            }
                            if (publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig.ContentTypeProfiles.IsSetQuantity())
                            {
                                xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromInt(publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig.ContentTypeProfiles.Quantity));
                            }

                            xmlWriter.WriteEndElement();
                        }
                        if (publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig.IsSetForwardWhenContentTypeIsUnknown())
                        {
                            xmlWriter.WriteElementString("ForwardWhenContentTypeIsUnknown", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromBool(publicRequest.FieldLevelEncryptionConfig.ContentTypeProfileConfig.ForwardWhenContentTypeIsUnknown));
                        }

                        xmlWriter.WriteEndElement();
                    }

                    if (publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig != null)
                    {
                        xmlWriter.WriteStartElement("QueryArgProfileConfig", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                        if (publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig.IsSetForwardWhenQueryArgProfileIsUnknown())
                        {
                            xmlWriter.WriteElementString("ForwardWhenQueryArgProfileIsUnknown", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromBool(publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig.ForwardWhenQueryArgProfileIsUnknown));
                        }


                        if (publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig.QueryArgProfiles != null)
                        {
                            xmlWriter.WriteStartElement("QueryArgProfiles", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                            var publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItems = publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig.QueryArgProfiles.Items;
                            if (publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItems != null && publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItems.Count > 0)
                            {
                                xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                foreach (var publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItemsValue in publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItems)
                                {
                                    if (publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItemsValue != null)
                                    {
                                        xmlWriter.WriteStartElement("QueryArgProfile", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                        if (publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItemsValue.IsSetProfileId())
                                        {
                                            xmlWriter.WriteElementString("ProfileId", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItemsValue.ProfileId));
                                        }

                                        if (publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItemsValue.IsSetQueryArg())
                                        {
                                            xmlWriter.WriteElementString("QueryArg", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionConfigQueryArgProfileConfigQueryArgProfilesItemsValue.QueryArg));
                                        }

                                        xmlWriter.WriteEndElement();
                                    }
                                }
                                xmlWriter.WriteEndElement();
                            }
                            if (publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig.QueryArgProfiles.IsSetQuantity())
                            {
                                xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromInt(publicRequest.FieldLevelEncryptionConfig.QueryArgProfileConfig.QueryArgProfiles.Quantity));
                            }

                            xmlWriter.WriteEndElement();
                        }
                        xmlWriter.WriteEndElement();
                    }

                    xmlWriter.WriteEndElement();
                }
            }
            try
            {
                string content = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(content);
                request.Headers["Content-Type"] = "application/xml";
                request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-05-31";
            }
            catch (EncoderFallbackException e)
            {
                throw new AmazonServiceException("Unable to marshall request to XML", e);
            }

            return(request);
        }
Exemplo n.º 4
0
        private object ProcessDownloadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));
                memoryStream.Flush();

                webRequest.ContentLength = memoryStream.Position;
                Stream requestStream = webRequest.GetRequestStream();
                CopyStreamContent(memoryStream, requestStream);

                requestStream.Flush();
                requestStream.Close();

                // Fire the Before request handler
                this.FirePreRequestHandler(webRequest);
            }

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSet changeSet = new ChangeSet();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                        case ReaderItemType.Entry:
                            changeSet.AddItem(this._syncReader.GetItem());
                            break;

                        case ReaderItemType.SyncBlob:
                            changeSet.ServerBlob = this._syncReader.GetServerBlob();
                            break;

                        case ReaderItemType.HasMoreChanges:
                            changeSet.IsLastBatch = !this._syncReader.GetHasMoreChangesValue();
                            break;
                        }
                    }

                    this.FirePostResponseHandler(webResponse);
                }

                webResponse.Close();

                return(changeSet);
            }
            else
            {
                throw new CacheControllerException(
                          string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                        webResponse.StatusCode,
                                        webResponse.StatusDescription));
            }
        }
Exemplo n.º 5
0
        public static void ComplexProperty()
        {
            var credentials = new XbimEditorCredentials
            {
                ApplicationDevelopersName = "xBIM Team",
                ApplicationFullName       = "xBIM Toolkit",
                ApplicationIdentifier     = "xBIM",
                ApplicationVersion        = "4.0",
                EditorsFamilyName         = "Cerny",
                EditorsGivenName          = "Martin",
                EditorsOrganisationName   = "CAS"
            };

            using (var model = IfcStore.Create(credentials, XbimSchemaVersion.Ifc4, XbimStoreType.InMemoryModel))
            //using (var model = new MemoryModel(new Xbim.Ifc4.EntityFactoryIfc4()))
            {
                ComplexPropertiesExample.model = model;

                using (var txn = model.BeginTransaction("Example"))
                {
                    var lib = New <IfcProjectLibrary>(l => l.Name = "Declaration of Performance");
                    var mm  = New <IfcSIUnit>(u => {
                        u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.METRE;
                        u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.MILLI;
                        u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.LENGTHUNIT;
                    });
                    lib.UnitsInContext = New <IfcUnitAssignment>(ua => {
                        ua.Units.Add(mm);
                    });

                    var declarations = New <IfcRelDeclares>(rel =>
                    {
                        rel.RelatingContext = lib;
                    }).RelatedDefinitions;

                    var psetTemplate = New <IfcPropertySetTemplate>(ps => {
                        ps.Name             = "dimensions";
                        ps.ApplicableEntity = nameof(IfcElement);
                    });

                    declarations.Add(psetTemplate);

                    var lengthTemplate = New <IfcComplexPropertyTemplate>(c => {
                        c.Name = "length";
                        c.HasPropertyTemplates.AddRange(new[] {
                            New <IfcSimplePropertyTemplate>(v => {
                                v.Name               = "Value";
                                v.TemplateType       = Xbim.Ifc4.Interfaces.IfcSimplePropertyTemplateTypeEnum.P_SINGLEVALUE;
                                v.PrimaryUnit        = mm;
                                v.PrimaryMeasureType = nameof(IfcLengthMeasure);
                            }),
                            New <IfcSimplePropertyTemplate>(v => {
                                v.Name               = "ReferenceDocument";
                                v.TemplateType       = Xbim.Ifc4.Interfaces.IfcSimplePropertyTemplateTypeEnum.P_REFERENCEVALUE;
                                v.PrimaryMeasureType = nameof(IfcDocumentReference);
                            })
                        });
                    });
                    psetTemplate.HasPropertyTemplates.Add(lengthTemplate);


                    var brick = New <IfcBuildingElementPart>(b => {
                        b.Name           = "Porotherm 50 EKO+ Profi R";
                        b.PredefinedType = Xbim.Ifc4.Interfaces.IfcBuildingElementPartTypeEnum.USERDEFINED;
                        b.ObjectType     = "BRICK";
                    });
                    declarations.Add(brick);

                    var pset = New <IfcPropertySet>(ps => {
                        ps.Name = psetTemplate.Name;
                        ps.HasProperties.Add(New <IfcComplexProperty>(c => {
                            c.Name = lengthTemplate.Name?.ToString();
                            c.HasProperties.AddRange(new IfcProperty[] {
                                New <IfcPropertySingleValue>(v => {
                                    v.Name         = "Value";
                                    v.Unit         = mm;
                                    v.NominalValue = new IfcLengthMeasure(300);
                                }),
                                New <IfcPropertyReferenceValue>(v => {
                                    v.Name = "ReferenceDocument";
                                    v.PropertyReference = New <IfcDocumentReference>(d => {
                                        d.Identification = "EN 772-1";
                                    });
                                })
                            });
                        }));
                    });
                    New <IfcRelDefinesByTemplate>(r => {
                        r.RelatedPropertySets.Add(pset);
                        r.RelatingTemplate = psetTemplate;
                    });
                    New <IfcRelDefinesByProperties>(r => {
                        r.RelatingPropertyDefinition = pset;
                        r.RelatedObjects.Add(brick);
                    });

                    txn.Commit();
                }

                //model.SaveAs("complex_length.ifcxml");
                model.SaveAs("complex_length.ifc");
                var w   = new XbimXmlWriter4(XbimXmlSettings.IFC4Add2);
                var xml = XmlWriter.Create("complex_length.ifcxml", new XmlWriterSettings {
                    Indent = true, IndentChars = "  "
                });
                var entities = new IPersistEntity[0]
                               .Concat(model.Instances.OfType <IfcProjectLibrary>())
                               .Concat(model.Instances);
                w.Write(model, xml, entities);
                xml.Close();
            }
        }
Exemplo n.º 6
0
        public void SaveNewPlayerConfig()
        {
            XDocument doc = new XDocument();

            UnsavedSettings = false;

            if (doc.Root == null)
            {
                doc.Add(new XElement("config"));
            }

            doc.Root.Add(
                new XAttribute("language", TextManager.Language),
                new XAttribute("masterserverurl", MasterServerUrl),
                new XAttribute("autocheckupdates", AutoCheckUpdates),
                new XAttribute("musicvolume", musicVolume),
                new XAttribute("soundvolume", soundVolume),
                new XAttribute("verboselogging", VerboseLogging),
                new XAttribute("savedebugconsolelogs", SaveDebugConsoleLogs),
                new XAttribute("enablesplashscreen", EnableSplashScreen),
                new XAttribute("usesteammatchmaking", useSteamMatchmaking),
                new XAttribute("quickstartsub", QuickStartSubmarineName),
                new XAttribute("requiresteamauthentication", requireSteamAuthentication),
                new XAttribute("autoupdateworkshopitems", AutoUpdateWorkshopItems),
                new XAttribute("pauseonfocuslost", PauseOnFocusLost),
                new XAttribute("aimassistamount", aimAssistAmount),
                new XAttribute("enablemouselook", EnableMouseLook),
                new XAttribute("chatopen", ChatOpen),
                new XAttribute("crewmenuopen", CrewMenuOpen),
                new XAttribute("campaigndisclaimershown", CampaignDisclaimerShown),
                new XAttribute("editordisclaimershown", EditorDisclaimerShown));

            if (!string.IsNullOrEmpty(overrideSaveFolder))
            {
                doc.Root.Add(new XAttribute("overridesavefolder", overrideSaveFolder));
            }
            if (!string.IsNullOrEmpty(overrideMultiplayerSaveFolder))
            {
                doc.Root.Add(new XAttribute("overridemultiplayersavefolder", overrideMultiplayerSaveFolder));
            }

            if (!ShowUserStatisticsPrompt)
            {
                doc.Root.Add(new XAttribute("senduserstatistics", sendUserStatistics));
            }

            XElement gMode = doc.Root.Element("graphicsmode");

            if (gMode == null)
            {
                gMode = new XElement("graphicsmode");
                doc.Root.Add(gMode);
            }

            if (GraphicsWidth == 0 || GraphicsHeight == 0)
            {
                gMode.ReplaceAttributes(new XAttribute("displaymode", windowMode));
            }
            else
            {
                gMode.ReplaceAttributes(
                    new XAttribute("width", GraphicsWidth),
                    new XAttribute("height", GraphicsHeight),
                    new XAttribute("vsync", VSyncEnabled),
                    new XAttribute("displaymode", windowMode));
            }

            XElement audio = doc.Root.Element("audio");

            if (audio == null)
            {
                audio = new XElement("audio");
                doc.Root.Add(audio);
            }
            audio.ReplaceAttributes(
                new XAttribute("musicvolume", musicVolume),
                new XAttribute("soundvolume", soundVolume),
                new XAttribute("voicechatvolume", voiceChatVolume),
                new XAttribute("microphonevolume", microphoneVolume),
                new XAttribute("muteonfocuslost", MuteOnFocusLost),
                new XAttribute("usedirectionalvoicechat", UseDirectionalVoiceChat),
                new XAttribute("voicesetting", VoiceSetting),
                new XAttribute("voicecapturedevice", VoiceCaptureDevice ?? ""),
                new XAttribute("noisegatethreshold", NoiseGateThreshold));

            XElement gSettings = doc.Root.Element("graphicssettings");

            if (gSettings == null)
            {
                gSettings = new XElement("graphicssettings");
                doc.Root.Add(gSettings);
            }

            gSettings.ReplaceAttributes(
                new XAttribute("particlelimit", ParticleLimit),
                new XAttribute("lightmapscale", LightMapScale),
                new XAttribute("specularity", SpecularityEnabled),
                new XAttribute("chromaticaberration", ChromaticAberrationEnabled),
                new XAttribute("losmode", LosMode),
                new XAttribute("hudscale", HUDScale),
                new XAttribute("inventoryscale", InventoryScale));

            foreach (ContentPackage contentPackage in SelectedContentPackages)
            {
                doc.Root.Add(new XElement("contentpackage",
                                          new XAttribute("path", contentPackage.Path)));
            }

            var keyMappingElement = new XElement("keymapping");

            doc.Root.Add(keyMappingElement);
            for (int i = 0; i < keyMapping.Length; i++)
            {
                if (keyMapping[i].MouseButton == null)
                {
                    keyMappingElement.Add(new XAttribute(((InputType)i).ToString(), keyMapping[i].Key));
                }
                else
                {
                    keyMappingElement.Add(new XAttribute(((InputType)i).ToString(), keyMapping[i].MouseButton));
                }
            }

            var gameplay       = new XElement("gameplay");
            var jobPreferences = new XElement("jobpreferences");

            foreach (string jobName in JobPreferences)
            {
                jobPreferences.Add(new XElement("job", new XAttribute("identifier", jobName)));
            }
            gameplay.Add(jobPreferences);
            doc.Root.Add(gameplay);

            var playerElement = new XElement("player",
                                             new XAttribute("name", defaultPlayerName ?? ""),
                                             new XAttribute("headindex", CharacterHeadIndex),
                                             new XAttribute("gender", CharacterGender),
                                             new XAttribute("race", CharacterRace),
                                             new XAttribute("hairindex", CharacterHairIndex),
                                             new XAttribute("beardindex", CharacterBeardIndex),
                                             new XAttribute("moustacheindex", CharacterMoustacheIndex),
                                             new XAttribute("faceattachmentindex", CharacterFaceAttachmentIndex));

            doc.Root.Add(playerElement);

#if CLIENT
            if (Tutorial.Tutorials != null)
            {
                foreach (Tutorial tutorial in Tutorial.Tutorials)
                {
                    if (tutorial.Completed && !CompletedTutorialNames.Contains(tutorial.Identifier))
                    {
                        CompletedTutorialNames.Add(tutorial.Identifier);
                    }
                }
            }
#endif
            var tutorialElement = new XElement("tutorials");
            foreach (string tutorialName in CompletedTutorialNames)
            {
                tutorialElement.Add(new XElement("Tutorial", new XAttribute("name", tutorialName)));
            }
            doc.Root.Add(tutorialElement);

            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent              = true,
                OmitXmlDeclaration  = true,
                NewLineOnAttributes = true
            };

            try
            {
                using (var writer = XmlWriter.Create(playerSavePath, settings))
                {
                    doc.WriteTo(writer);
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Saving game settings failed.", e);
                GameAnalyticsManager.AddErrorEventOnce("GameSettings.Save:SaveFailed", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       "Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace);
            }
        }
Exemplo n.º 7
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

                if (TrackCancel == null)
                {
                    TrackCancel = new CancelTrackerClass();
                }

                IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter;
                IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter);
                IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber));

                // get the name of the feature dataset
                int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");

                string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1);


                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;

                System.Xml.XmlWriter xmlWriter = null;

                try
                {
                    xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings);
                }
                catch (Exception ex)
                {
                    message.AddError(120021, ex.Message);
                    return;
                }

                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("osm"); // start the osm root node
                xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute
                xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute

                // write all the nodes
                // use a feature search cursor to loop through all the known points and write them out as osm node

                IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer;

                if (osmFeatureClasses == null)
                {
                    message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name));
                    return;
                }

                IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt");

                if (osmPointFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt"));
                    return;
                }

                // check the extension of the point feature class to determine its version
                int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion();

                IFeatureCursor searchCursor = null;

                System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces();
                xmlnsEmpty.Add("", "");

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg"));
                int pointCounter = 0;

                string nodesExportedMessage = String.Empty;

                // collect the indices for the point feature class once
                int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID");
                int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset");
                int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion");
                int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid");
                int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser");
                int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp");
                int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible");
                int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags");

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPointFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node));

                    IFeature currentFeature = searchCursor.NextFeature();

                    IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == true)
                        {
                            // convert the found point feature into a osm node representation to store into the OSM XML file
                            node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion);

                            pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);

                            // increase the point counter to later status report
                            pointCounter++;

                            currentFeature = searchCursor.NextFeature();
                        }
                        else
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loader so far
                            nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                            message.AddMessage(nodesExportedMessage);

                            return;
                        }
                    }
                }

                nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                message.AddMessage(nodesExportedMessage);

                // next loop through the line and polygon feature classes to export those features as ways
                // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table
                IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln");

                if (osmLineFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln"));
                    return;
                }

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg"));

                // as we are looping through the line and polygon feature classes let's collect the multi-part features separately 
                // as they are considered relations in the OSM world
                List<relation> multiPartElements = new List<relation>();

                System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way));
                int lineCounter = 0;
                int relationCounter = 0;
                string waysExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmLineFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID");
                    int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset");
                    int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion");
                    int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid");
                    int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser");
                    int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp");
                    int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible");
                    int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags");
                    int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }


                IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply");
                IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace;

                if (osmPolygonFeatureClass == null)
                {
                    message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply"));
                    return;
                }

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPolygonFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID");
                    int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset");
                    int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion");
                    int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid");
                    int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser");
                    int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp");
                    int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible");
                    int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags");
                    int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }

                waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                message.AddMessage(waysExportedMessage);


                // now let's go through the relation table 
                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg"));
                ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation");

                if (relationTable == null)
                {
                    message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation"));
                    return;
                }


                System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation));
                string relationsExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    ICursor rowCursor = relationTable.Search(null, false);
                    comReleaser.ManageLifetime(rowCursor);

                    IRow currentRow = rowCursor.NextRow();

                    // collect the indices for the relation table once
                    int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID");
                    int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset");
                    int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion");
                    int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid");
                    int relationUserFieldIndex = relationTable.Fields.FindField("osmuser");
                    int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp");
                    int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible");
                    int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags");
                    int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;


                    while (currentRow != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loaded so far
                            relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                            message.AddMessage(relationsExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion);
                        relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty);

                        // increase the line counter for later status report
                        relationCounter++;

                        currentRow = rowCursor.NextRow();
                    }
                }

                // lastly let's serialize the collected multipart-geometries back into relation elements
                foreach (relation currentRelation in multiPartElements)
                {
                    if (TrackCancel.Continue() == false)
                    {
                        // properly close the document
                        xmlWriter.WriteEndElement(); // closing the osm root element
                        xmlWriter.WriteEndDocument(); // finishing the document

                        xmlWriter.Close(); // closing the document

                        // report the number of elements loaded so far
                        relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                        message.AddMessage(relationsExportedMessage);

                        return;
                    }

                    relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty);
                    relationCounter++;
                }

                relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                message.AddMessage(relationsExportedMessage);


                xmlWriter.WriteEndElement(); // closing the osm root element
                xmlWriter.WriteEndDocument(); // finishing the document

                xmlWriter.Close(); // closing the document
            }
            catch (Exception ex)
            {
                message.AddError(11111, ex.StackTrace);
                message.AddError(120026, ex.Message);
            }
        }
Exemplo n.º 8
0
            private void IndentXml(TextReader xmlContent, TextWriter writer)
            {
                char[] writeNodeBuffer = null;

                var settings = new XmlWriterSettings();

                settings.OmitXmlDeclaration = true;
                settings.Indent             = true;
                settings.IndentChars        = "  ";
                settings.CheckCharacters    = true;

                using (var reader = XmlReader.Create(xmlContent))
                    using (var xmlWriter = XmlWriter.Create(writer, settings))
                    {
                        bool canReadValueChunk = reader.CanReadValueChunk;
                        while (reader.Read())
                        {
                            switch (reader.NodeType)
                            {
                            case XmlNodeType.Element:
                                xmlWriter.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
                                xmlWriter.WriteAttributes(reader, false);
                                if (reader.IsEmptyElement)
                                {
                                    xmlWriter.WriteEndElement();
                                }
                                break;

                            case XmlNodeType.Text:
                                if (canReadValueChunk)
                                {
                                    if (writeNodeBuffer == null)
                                    {
                                        writeNodeBuffer = new char[1024];
                                    }
                                    int count;
                                    while ((count = reader.ReadValueChunk(writeNodeBuffer, 0, 1024)) > 0)
                                    {
                                        xmlWriter.WriteChars(writeNodeBuffer, 0, count);
                                    }
                                }
                                break;

                            case XmlNodeType.CDATA:
                                xmlWriter.WriteCData(reader.Value);
                                break;

                            case XmlNodeType.EntityReference:
                                xmlWriter.WriteEntityRef(reader.Name);
                                break;

                            case XmlNodeType.ProcessingInstruction:
                            case XmlNodeType.XmlDeclaration:
                                xmlWriter.WriteProcessingInstruction(reader.Name, reader.Value);
                                break;

                            case XmlNodeType.Comment:
                                xmlWriter.WriteComment(reader.Value);
                                break;

                            case XmlNodeType.DocumentType:
                                xmlWriter.WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
                                break;

                            case XmlNodeType.Whitespace:
                            case XmlNodeType.SignificantWhitespace:
                                xmlWriter.WriteWhitespace(reader.Value);
                                break;

                            case XmlNodeType.EndElement:
                                xmlWriter.WriteFullEndElement();
                                break;
                            }
                        }

                        xmlWriter.Flush();
                        writer.Flush();
                    }
            }
Exemplo n.º 9
0
    private static void PatchVCXProjFile(HoloLensProjectInfo projectInfo)
    {
        string vcxProjFilePath = Path.Combine(projectInfo.BuildOutputPath, projectInfo.ProjectName, $"{projectInfo.ProjectName}.vcxproj");

        Debug.Log($"Patching {vcxProjFilePath} with {AzureSpatialAnchorsPackage} {projectInfo.SpatialAnchorsSdkVersion}");

        if (!File.Exists(vcxProjFilePath))
        {
            Debug.LogError($"The project is not a native MSBuild project: {projectInfo.BuildOutputPath}");
            return;
        }

        XDocument vcxProjDoc           = XDocument.Load(vcxProjFilePath);
        string    ns                   = vcxProjDoc.Root.Name.NamespaceName;
        XElement  fileIncludeItemGroup = vcxProjDoc.Root.Elements()
                                         .Where(el => el.Name.LocalName == "ItemGroup")
                                         .FirstOrDefault(el => el.Elements().Any(el2 => el2.Name.LocalName == "None"));

        if (fileIncludeItemGroup == null)
        {
            Debug.LogError($"Invalid vcxproj file: {vcxProjFilePath}");
            return;
        }

        // Add the packages.config file reference.
        XElement packagesConfigRefElement = new XElement(XName.Get("None", ns));

        packagesConfigRefElement.Add(new XAttribute("Include", "packages.config"));
        fileIncludeItemGroup.Add(packagesConfigRefElement);

        XElement importGroupExtensionTargetsElement = vcxProjDoc.Root.Elements()
                                                      .Where(el => el.Name.LocalName == "ImportGroup")
                                                      .FirstOrDefault(el => el.Attributes().Any(a => a.Name.LocalName == "Label" && a.Value == "ExtensionTargets"));

        if (importGroupExtensionTargetsElement == null)
        {
            Debug.LogError($"Invalid vcxproj file: {vcxProjFilePath}");
            return;
        }

        // Add the targets imports for the packages.
        string[] packages = new[] { AzureSpatialAnchorsRedistPackage, AzureSpatialAnchorsPackage };
        foreach (string packageName in packages)
        {
            XElement importElement = new XElement(XName.Get("Import", ns));
            string   targetPath    = $@"..\packages\{packageName}.{projectInfo.SpatialAnchorsSdkVersion}\build\native\{packageName}.targets";
            importElement.Add(new XAttribute("Project", targetPath));
            importElement.Add(new XAttribute("Condition", $"Exists('{targetPath}')"));

            importGroupExtensionTargetsElement.Add(importElement);
        }

        // Add a target to check that a restore has been performed.
        XElement nugetCheckTargetElement = new XElement(XName.Get("Target", ns),
                                                        new XElement(XName.Get("PropertyGroup", ns),
                                                                     new XElement(XName.Get("ErrorText", ns), "This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.")));

        nugetCheckTargetElement.Add(new XAttribute("Name", "EnsureNuGetPackageBuildImports"));
        nugetCheckTargetElement.Add(new XAttribute("BeforeTargets", "PrepareForBuild"));

        foreach (string packageName in packages)
        {
            XElement errorElement = new XElement(XName.Get("Error", ns));
            string   targetPath   = $@"..\packages\{packageName}.{projectInfo.SpatialAnchorsSdkVersion}\build\native\{packageName}.targets";
            errorElement.Add(new XAttribute("Condition", $"!Exists('{targetPath}')"));
            errorElement.Add(new XAttribute("Text", $"$([System.String]::Format('$(ErrorText)', '{targetPath}'))"));

            nugetCheckTargetElement.Add(errorElement);
        }

        vcxProjDoc.Root.Add(nugetCheckTargetElement);

        // Update the contents of the vcxproj
        using (XmlWriter xmlWriter = XmlWriter.Create(vcxProjFilePath, new XmlWriterSettings {
            Indent = true
        }))
        {
            vcxProjDoc.Save(xmlWriter);
        }
    }
Exemplo n.º 10
0
        public void SendXmlOut()
        {
            string xml;

            if (dateTimePicker2.Value.Day < 10 && dateTimePicker2.Value.Month < 10)
            {
                xml = $@"C:\Users\Radnik\Desktop" +
                      $@"\niks\{textBox2.Text}_{dateTimePicker2.Value.Year}" +
                      $@"0{dateTimePicker2.Value.Month}0{dateTimePicker2.Value.Day}.xml";
            }
            else if (dateTimePicker2.Value.Day < 10)
            {
                xml = $@"C:\Users\Radnik\Desktop" +
                      $@"\niks\{textBox2.Text}_{dateTimePicker2.Value.Year}" +
                      $@"{dateTimePicker2.Value.Month}0{dateTimePicker2.Value.Day}.xml";
            }
            else if (dateTimePicker2.Value.Month < 10)
            {
                xml = $@"C:\Users\Radnik\Desktop" +
                      $@"\niks\{textBox2.Text}_{dateTimePicker2.Value.Year}" +
                      $@"0{dateTimePicker2.Value.Month}{dateTimePicker2.Value.Day}.xml";
            }
            else
            {
                xml = $@"C:\Users\Radnik\Desktop" +
                      $@"\niks\{textBox2.Text}_{dateTimePicker2.Value.Year}" +
                      $@"{dateTimePicker2.Value.Month}{dateTimePicker2.Value.Day}.xml";
            }

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent      = true;
            settings.IndentChars = ("   ");

            XmlWriter xmlOut = XmlWriter.Create(xml, settings);

            xmlOut.WriteStartDocument();
            xmlOut.WriteStartElement("Pumpe");
            xmlOut.WriteStartElement("Pumpa");
            xmlOut.WriteElementString("IDPumpe", textBox2.Text);
            xmlOut.WriteElementString("BrojTankova", textBox3.Text);
            xmlOut.WriteElementString("MatičniBroj", textBox4.Text);
            xmlOut.WriteElementString("TelBrojKontrolera", textBox5.Text);
            xmlOut.WriteElementString("NazivPumpe", textBox6.Text);
            xmlOut.WriteElementString("Adresa", richTextBox1.Text);
            xmlOut.WriteStartElement("Tankovi");
            if (textBox3.Text != "")
            {
                int s = int.Parse(textBox3.Text);
                for (int i = 0; i < s; i++)
                {
                    xmlOut.WriteStartElement("Tank");
                    xmlOut.WriteElementString("ID", dataGridView1.Rows[i].Cells[0].Value.ToString());
                    xmlOut.WriteElementString("TankSpremnik", dataGridView1.Rows[i].Cells[1].Value.ToString());
                    xmlOut.WriteElementString("IDFMT", dataGridView1.Rows[i].Cells[2].Value.ToString());
                    xmlOut.WriteElementString("PočetnoStanje", dataGridView1.Rows[i].Cells[3].Value.ToString());
                    xmlOut.WriteElementString("UlaznaKoličina", dataGridView1.Rows[i].Cells[4].Value.ToString());
                    xmlOut.WriteElementString("IzlaznaKoličina", dataGridView1.Rows[i].Cells[5].Value.ToString());
                    xmlOut.WriteElementString("ProdajnaCijena", dataGridView1.Rows[i].Cells[6].Value.ToString());
                    xmlOut.WriteEndElement();
                }
            }
            xmlOut.WriteEndElement();
            xmlOut.WriteEndElement();
            xmlOut.WriteEndElement();
            xmlOut.Close();

            testDialog.Clear_listbox();
            testDialog.Populate_listbox(shrt, type);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Performs XML XSL transformation
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="xslPath">Path to xml style sheet.</param>
        /// <param name="xmlPath">Path xml data.</param>
        /// <param name="resultPath">Transformation result path.</param>
        /// <param name="settings">Settings for result file xml transformation.</param>
        public static void Transform(IFileSystem fileSystem, FilePath xslPath, FilePath xmlPath, FilePath resultPath, XmlTransformationSettings settings)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem", "Null filesystem supplied.");
            }

            if (xslPath == null)
            {
                throw new ArgumentNullException("xslPath", "Null XML style sheet path supplied.");
            }

            if (xmlPath == null)
            {
                throw new ArgumentNullException("xmlPath", "Null XML data path supplied.");
            }

            if (resultPath == null)
            {
                throw new ArgumentNullException("resultPath", "Null result path supplied.");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings", "Null settings supplied.");
            }

            IFile
                xslFile    = fileSystem.GetFile(xslPath),
                xmlFile    = fileSystem.GetFile(xmlPath),
                resultFile = fileSystem.GetFile(resultPath);

            if (!xslFile.Exists)
            {
                throw new FileNotFoundException("Xsl File not found.", xslFile.Path.FullPath);
            }

            if (!xmlFile.Exists)
            {
                throw new FileNotFoundException("XML File not found.", xmlFile.Path.FullPath);
            }

            if (!settings.Overwrite && resultFile.Exists)
            {
                throw new CakeException("Result file found and overwrite set to false.");
            }

            using (Stream
                   xslStream = xslFile.OpenRead(),
                   xmlStream = xmlFile.OpenRead(),
                   resultStream = resultFile.OpenWrite())
            {
                XmlReader
                    xslReader = XmlReader.Create(xslStream),
                    xmlReader = XmlReader.Create(xmlStream);

                var resultWriter = XmlWriter.Create(resultStream, settings.XmlWriterSettings);

                Transform(xslReader, xmlReader, resultWriter);
            }
        }
Exemplo n.º 12
0
        public bool Save(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (!this.Loaded)
            {
                return(false);
            }

            if (!this.Changed && this.FilePath != null && path.Equals(this.FilePath))
            {
                return(true);
            }

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent          = true;
            settings.IndentChars     = @"    ";
            settings.NewLineChars    = Environment.NewLine;
            settings.NewLineHandling = NewLineHandling.Replace;

            try
            {
                using (XmlWriter writer = XmlWriter.Create(path, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("versions");

                    foreach (Version version in this.Versions)
                    {
                        writer.WriteStartElement("version");
                        writer.WriteAttributeString("value", version.Value.ToString());
                        writer.WriteAttributeString("description", version.Description);
                        writer.WriteAttributeString("dat", string.Format("{0:X}", version.DatSignature));
                        writer.WriteAttributeString("spr", string.Format("{0:X}", version.SprSignature));
                        writer.WriteAttributeString("otb", version.OtbValue.ToString());
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Flush();
                    writer.Close();
                }
            }
            catch
            {
                return(false);
            }

            this.FilePath = path;
            this.Changed  = false;

            if (this.StorageCompiled != null)
            {
                this.StorageCompiled(this, new EventArgs());
            }

            return(true);
        }
Exemplo n.º 13
0
        internal static void DoDrag(FrameworkElement host, QDocument active, InfoOwner item, InfoOwnerData itemData, Action beforeDrag = null, Action afterDrag = null)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            if (active == null)
            {
                throw new ArgumentNullException(nameof(active));
            }

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (itemData == null)
            {
                throw new ArgumentNullException(nameof(itemData));
            }

            itemData.GetFullData(active.Document, item);
            var dataObject = new DataObject(itemData);

            if (host.DataContext is RoundViewModel roundViewModel)
            {
                var packageViewModel = roundViewModel.OwnerPackage;
                if (packageViewModel == null)
                {
                    throw new ArgumentException(nameof(packageViewModel));
                }

                int index = packageViewModel.Rounds.IndexOf(roundViewModel);

                active.BeginChange();

                try
                {
                    var sb = new StringBuilder();
                    using (var writer = XmlWriter.Create(sb))
                    {
                        roundViewModel.Model.WriteXml(writer);
                    }

                    dataObject.SetData("siqround", "1");
                    dataObject.SetData(DataFormats.Serializable, sb);

                    var result = DragDrop.DoDragDrop(host, dataObject, DragDropEffects.Move);
                    if (result == DragDropEffects.Move)
                    {
                        if (packageViewModel.Rounds[index] != roundViewModel)
                        {
                            index++;
                        }

                        packageViewModel.Rounds.RemoveAt(index);
                        active.CommitChange();
                    }
                    else
                    {
                        active.RollbackChange();
                    }
                }
                catch (Exception exc)
                {
                    active.RollbackChange();
                    throw exc;
                }
            }
            else
            {
                if (host.DataContext is ThemeViewModel themeViewModel)
                {
                    roundViewModel = themeViewModel.OwnerRound;
                    if (roundViewModel == null)
                    {
                        throw new ArgumentException(nameof(roundViewModel));
                    }

                    int index = roundViewModel.Themes.IndexOf(themeViewModel);

                    active.BeginChange();

                    try
                    {
                        var sb = new StringBuilder();
                        using (var writer = XmlWriter.Create(sb))
                        {
                            themeViewModel.Model.WriteXml(writer);
                        }

                        dataObject.SetData("siqtheme", "1");
                        dataObject.SetData(DataFormats.Serializable, sb);

                        var result = DragDrop.DoDragDrop(host, dataObject, DragDropEffects.Move);
                        if (result == DragDropEffects.Move)
                        {
                            if (roundViewModel.Themes[index] != themeViewModel)
                            {
                                index++;
                            }

                            roundViewModel.Themes.RemoveAt(index);
                        }

                        active.CommitChange();
                    }
                    catch (Exception exc)
                    {
                        active.RollbackChange();
                        throw exc;
                    }
                }
                else
                {
                    var questionViewModel = host.DataContext as QuestionViewModel;
                    themeViewModel = questionViewModel.OwnerTheme;
                    if (themeViewModel == null)
                    {
                        throw new ArgumentException(nameof(themeViewModel));
                    }

                    var index = themeViewModel.Questions.IndexOf(questionViewModel);
                    active.BeginChange();

                    try
                    {
                        var sb = new StringBuilder();
                        using (var writer = XmlWriter.Create(sb))
                        {
                            questionViewModel.Model.WriteXml(writer);
                        }

                        dataObject.SetData("siqquestion", "1");
                        dataObject.SetData(DataFormats.Serializable, sb);

                        beforeDrag?.Invoke();

                        DragDropEffects result;
                        try
                        {
                            result = DragDrop.DoDragDrop(host, dataObject, DragDropEffects.Move);
                        }
                        catch (InvalidOperationException)
                        {
                            result = DragDropEffects.None;
                        }
                        finally
                        {
                            host.Opacity = 1.0;

                            afterDrag?.Invoke();
                        }

                        if (result == DragDropEffects.Move)
                        {
                            if (themeViewModel.Questions[index] != questionViewModel)
                            {
                                index++;
                            }

                            themeViewModel.Questions.RemoveAt(index);

                            if (AppSettings.Default.ChangePriceOnMove)
                            {
                                RecountPrices(themeViewModel);
                            }
                        }

                        active.CommitChange();
                    }
                    catch (Exception exc)
                    {
                        active.RollbackChange();
                        throw exc;
                    }
                }
            }
        }
Exemplo n.º 14
0
        public NSAttributedString ToAttributedString(NSFont font, int?lineSpacing)
        {
            xmlWriter.Flush();

            var finaltext      = new StringBuilder();
            var finalxmlWriter = XmlWriter.Create(finaltext, new XmlWriterSettings {
                OmitXmlDeclaration = true,
                Encoding           = Encoding.UTF8,
                Indent             = true,
                IndentChars        = "\t"
            });


            float  fontSize;
            string fontFamily;

            if (font != null)
            {
                fontSize   = (float)font.PointSize;
                fontFamily = font.FontName;
            }
            else
            {
                fontSize   = 16;
                fontFamily = "sans-serif";
            }

            finalxmlWriter.WriteDocType("html", "-//W3C//DTD XHTML 1.0", "Strict//EN", null);
            finalxmlWriter.WriteStartElement("html");
            finalxmlWriter.WriteStartElement("meta");
            finalxmlWriter.WriteAttributeString("http-equiv", "Content-Type");
            finalxmlWriter.WriteAttributeString("content", "text/html; charset=utf-8");
            finalxmlWriter.WriteEndElement();
            finalxmlWriter.WriteStartElement("body");

            string style = String.Format("font-family: {0}; font-size: {1}", fontFamily, fontSize);

            if (lineSpacing.HasValue)
            {
                style += "; line-height: " + (lineSpacing.Value + fontSize) + "px";
            }

            finalxmlWriter.WriteAttributeString("style", style);
            finalxmlWriter.WriteRaw(text.ToString());
            finalxmlWriter.WriteEndElement();              // body
            finalxmlWriter.WriteEndElement();              // html
            finalxmlWriter.Flush();

            if (finaltext == null || finaltext.Length == 0)
            {
                return(new NSAttributedString(String.Empty));
            }

            NSDictionary docAttributes;

            try {
                return(CreateStringFromHTML(finaltext.ToString(), out docAttributes));
            } finally {
                finaltext = null;
                ((IDisposable)finalxmlWriter).Dispose();
                finalxmlWriter = null;
                docAttributes  = null;
            }
        }
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(UpdatePublicKeyRequest publicRequest)
        {
            var request = new DefaultRequest(publicRequest, "Amazon.CloudFront");

            request.HttpMethod = "PUT";
            string uriResourcePath = "/2018-06-18/public-key/{Id}/config";

            if (publicRequest.IsSetIfMatch())
            {
                request.Headers["If-Match"] = publicRequest.IfMatch;
            }
            if (!publicRequest.IsSetId())
            {
                throw new AmazonCloudFrontException("Request object does not have required field Id set");
            }
            uriResourcePath      = uriResourcePath.Replace("{Id}", StringUtils.FromString(publicRequest.Id));
            request.ResourcePath = uriResourcePath;

            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
            {
                Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true
            }))
            {
                xmlWriter.WriteStartElement("PublicKeyConfig", "http://cloudfront.amazonaws.com/doc/2018-06-18/");
                if (publicRequest.PublicKeyConfig.IsSetCallerReference())
                {
                    xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2018-06-18/", StringUtils.FromString(publicRequest.PublicKeyConfig.CallerReference));
                }

                if (publicRequest.PublicKeyConfig.IsSetComment())
                {
                    xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2018-06-18/", StringUtils.FromString(publicRequest.PublicKeyConfig.Comment));
                }

                if (publicRequest.PublicKeyConfig.IsSetEncodedKey())
                {
                    xmlWriter.WriteElementString("EncodedKey", "http://cloudfront.amazonaws.com/doc/2018-06-18/", StringUtils.FromString(publicRequest.PublicKeyConfig.EncodedKey));
                }

                if (publicRequest.PublicKeyConfig.IsSetName())
                {
                    xmlWriter.WriteElementString("Name", "http://cloudfront.amazonaws.com/doc/2018-06-18/", StringUtils.FromString(publicRequest.PublicKeyConfig.Name));
                }


                xmlWriter.WriteEndElement();
            }
            try
            {
                string content = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(content);
                request.Headers["Content-Type"] = "application/xml";
            }
            catch (EncoderFallbackException e)
            {
                throw new AmazonServiceException("Unable to marshall request to XML", e);
            }

            return(request);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Returns the rss xml string for the blog or a blog category.
        /// The rss feed always returns first page with 10 results.
        /// </summary>
        /// <param name="cat"></param>
        /// <returns></returns>
        private async Task <string> GetFeed(Category cat = null)
        {
            var key  = cat == null ? BlogCache.KEY_MAIN_RSSFEED : string.Format(BlogCache.KEY_CAT_RSSFEED, cat.Slug);
            var time = cat == null ? BlogCache.Time_MainRSSFeed : BlogCache.Time_CatRSSFeed;

            return(await _cache.GetAsync(key, time, async() =>
            {
                var sw = new StringWriter();
                using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings()
                {
                    Async = true, Indent = true
                }))
                {
                    var postList = cat == null ?
                                   await _blogSvc.GetListAsync(1, 10, cacheable: false) :
                                   await _blogSvc.GetListForCategoryAsync(cat.Slug, 1);
                    var coreSettings = await _settingSvc.GetSettingsAsync <CoreSettings>();
                    var blogSettings = await _settingSvc.GetSettingsAsync <BlogSettings>();
                    var vm = new BlogPostListViewModel(postList, blogSettings, Request);

                    var settings = await _settingSvc.GetSettingsAsync <CoreSettings>();
                    var channelTitle = cat == null ? settings.Title : $"{cat.Title} - {settings.Title}";
                    var channelDescription = coreSettings.Tagline;
                    var channelLink = $"{Request.Scheme}://{Request.Host}";
                    var channelLastPubDate = postList.Posts.Count <= 0 ? DateTimeOffset.UtcNow : postList.Posts[0].CreatedOn;

                    var writer = new RssFeedWriter(xmlWriter);
                    await writer.WriteTitle(channelTitle);
                    await writer.WriteDescription(channelDescription);
                    await writer.Write(new SyndicationLink(new Uri(channelLink)));
                    await writer.WritePubDate(channelLastPubDate);
                    await writer.WriteGenerator("https://www.fanray.com");

                    foreach (var postVM in vm.BlogPostViewModels)
                    {
                        var post = postVM;
                        var item = new SyndicationItem()
                        {
                            Id = postVM.Permalink, // guid https://www.w3schools.com/xml/rss_tag_guid.asp
                            Title = post.Title,
                            Description = blogSettings.FeedShowExcerpt ? post.Excerpt : post.Body,
                            Published = post.CreatedOn,
                        };

                        // link to the post
                        item.AddLink(new SyndicationLink(new Uri(postVM.CanonicalUrl)));

                        // category takes in both cats and tags
                        item.AddCategory(new SyndicationCategory(post.Category.Title));
                        foreach (var tag in post.Tags)
                        {
                            item.AddCategory(new SyndicationCategory(tag.Title));
                        }

                        // https://www.w3schools.com/xml/rss_tag_author.asp
                        // the author tag exposes email
                        //item.AddContributor(new SyndicationPerson(post.User.DisplayName, post.User.Email));

                        await writer.Write(item);
                    }

                    xmlWriter.Flush();
                }

                return sw.ToString();
            }));
        }
Exemplo n.º 17
0
        private void SaveNewDefaultConfig()
        {
            XDocument doc = new XDocument();

            if (doc.Root == null)
            {
                doc.Add(new XElement("config"));
            }

            doc.Root.Add(
                new XAttribute("language", TextManager.Language),
                new XAttribute("masterserverurl", MasterServerUrl),
                new XAttribute("autocheckupdates", AutoCheckUpdates),
                new XAttribute("musicvolume", musicVolume),
                new XAttribute("soundvolume", soundVolume),
                new XAttribute("microphonevolume", microphoneVolume),
                new XAttribute("voicechatvolume", voiceChatVolume),
                new XAttribute("verboselogging", VerboseLogging),
                new XAttribute("savedebugconsolelogs", SaveDebugConsoleLogs),
                new XAttribute("enablesplashscreen", EnableSplashScreen),
                new XAttribute("usesteammatchmaking", useSteamMatchmaking),
                new XAttribute("quickstartsub", QuickStartSubmarineName),
                new XAttribute("requiresteamauthentication", requireSteamAuthentication),
                new XAttribute("aimassistamount", aimAssistAmount));

            if (!ShowUserStatisticsPrompt)
            {
                doc.Root.Add(new XAttribute("senduserstatistics", sendUserStatistics));
            }

            if (WasGameUpdated)
            {
                doc.Root.Add(new XAttribute("wasgameupdated", true));
            }

            XElement gMode = doc.Root.Element("graphicsmode");

            if (gMode == null)
            {
                gMode = new XElement("graphicsmode");
                doc.Root.Add(gMode);
            }
            if (GraphicsWidth == 0 || GraphicsHeight == 0)
            {
                gMode.ReplaceAttributes(new XAttribute("displaymode", windowMode));
            }
            else
            {
                gMode.ReplaceAttributes(
                    new XAttribute("width", GraphicsWidth),
                    new XAttribute("height", GraphicsHeight),
                    new XAttribute("vsync", VSyncEnabled),
                    new XAttribute("displaymode", windowMode));
            }

            XElement gSettings = doc.Root.Element("graphicssettings");

            if (gSettings == null)
            {
                gSettings = new XElement("graphicssettings");
                doc.Root.Add(gSettings);
            }

            gSettings.ReplaceAttributes(
                new XAttribute("particlelimit", ParticleLimit),
                new XAttribute("lightmapscale", LightMapScale),
                new XAttribute("specularity", SpecularityEnabled),
                new XAttribute("chromaticaberration", ChromaticAberrationEnabled),
                new XAttribute("losmode", LosMode),
                new XAttribute("hudscale", HUDScale),
                new XAttribute("inventoryscale", InventoryScale));

            foreach (ContentPackage contentPackage in SelectedContentPackages)
            {
                if (contentPackage.Path.Contains(vanillaContentPackagePath))
                {
                    doc.Root.Add(new XElement("contentpackage", new XAttribute("path", contentPackage.Path)));
                    break;
                }
            }

            var keyMappingElement = new XElement("keymapping");

            doc.Root.Add(keyMappingElement);
            for (int i = 0; i < keyMapping.Length; i++)
            {
                if (keyMapping[i].MouseButton == null)
                {
                    keyMappingElement.Add(new XAttribute(((InputType)i).ToString(), keyMapping[i].Key));
                }
                else
                {
                    keyMappingElement.Add(new XAttribute(((InputType)i).ToString(), keyMapping[i].MouseButton));
                }
            }

            var gameplay       = new XElement("gameplay");
            var jobPreferences = new XElement("jobpreferences");

            foreach (string jobName in JobPreferences)
            {
                jobPreferences.Add(new XElement("job", new XAttribute("identifier", jobName)));
            }
            gameplay.Add(jobPreferences);
            doc.Root.Add(gameplay);

            var playerElement = new XElement("player",
                                             new XAttribute("name", defaultPlayerName ?? ""),
                                             new XAttribute("headindex", CharacterHeadIndex),
                                             new XAttribute("gender", CharacterGender),
                                             new XAttribute("race", CharacterRace),
                                             new XAttribute("hairindex", CharacterHairIndex),
                                             new XAttribute("beardindex", CharacterBeardIndex),
                                             new XAttribute("moustacheindex", CharacterMoustacheIndex),
                                             new XAttribute("faceattachmentindex", CharacterFaceAttachmentIndex));

            doc.Root.Add(playerElement);

            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent              = true,
                OmitXmlDeclaration  = true,
                NewLineOnAttributes = true
            };

            try
            {
                using (var writer = XmlWriter.Create(savePath, settings))
                {
                    doc.WriteTo(writer);
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Saving game settings failed.", e);
                GameAnalyticsManager.AddErrorEventOnce("GameSettings.Save:SaveFailed", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       "Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Feature转换成GGGX数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static XmlDocument FeatureToGGGX(List <GeoFeature> list)
        {
            List <GeoFeature> ftList = list;
            //初始化一个xml实例
            XmlDocument    myXmlDoc    = new XmlDocument();
            XmlDeclaration declaration = myXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            myXmlDoc.AppendChild(declaration);

            XmlNamespaceManager xnm = new XmlNamespaceManager(myXmlDoc.NameTable);

            xnm.AddNamespace("gml", "http://www.opengis.net/gml");
            xnm.AddNamespace(string.Empty, "http://www.jurassic.com.cn/3gx");

            //创建xml的根节点
            XmlElement rootElement = myXmlDoc.CreateElement("", "FeatureCollection", "http://www.jurassic.com.cn/3gx");

            rootElement.SetAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
            rootElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

            rootElement.SetAttribute("name", "GGGX数据 ");//设置该节点genre属性
            rootElement.SetAttribute("xsi:schemaLocation", "http://www.jurassic.com.cn/3gx 3GX.Data.Feature.GeoMap.xsd");
            myXmlDoc.AppendChild(rootElement);

            XmlElement crsElement = myXmlDoc.CreateElement("CRS", "http://www.jurassic.com.cn/3gx");

            crsElement.SetAttribute("codeSpace", "china");
            crsElement.InnerText = "地理坐标(经纬度)";
            rootElement.AppendChild(crsElement);

            foreach (GeoFeature ft in ftList)
            {
                XmlElement gfElement = myXmlDoc.CreateElement("GF", "http://www.jurassic.com.cn/3gx");
                gfElement.SetAttribute("class", ft.CLASS);
                gfElement.SetAttribute("id", ft.BOID);
                gfElement.SetAttribute("bot", ft.BOT);
                gfElement.SetAttribute("type", ft.FT);

                XmlElement titleElement = myXmlDoc.CreateElement("Title", "http://www.jurassic.com.cn/3gx");
                titleElement.InnerText = ft.NAME;
                gfElement.AppendChild(titleElement);
                if (ft.AliasNameList != null)
                {
                    foreach (AliasName aliasName in ft.AliasNameList)
                    {
                        XmlElement nameElement = myXmlDoc.CreateElement("Name");
                        nameElement.SetAttribute("codeSpace", aliasName.APPDOMAIN);
                        nameElement.InnerText = aliasName.NAME;
                        gfElement.AppendChild(nameElement);
                    }
                }
                XmlElement PropertySetsElement = myXmlDoc.CreateElement("PropertySets", "http://www.jurassic.com.cn/3gx");
                if (ft.PropertyList != null)
                {
                    foreach (Property property in ft.PropertyList)
                    {
                        XmlDocumentFragment propertyElement = myXmlDoc.CreateDocumentFragment();
                        propertyElement.InnerXml = property.MD;
                        PropertySetsElement.AppendChild(propertyElement);
                    }
                }
                gfElement.AppendChild(PropertySetsElement);

                XmlElement shapesElement = myXmlDoc.CreateElement("Shapes", "http://www.jurassic.com.cn/3gx");
                if (ft.GeometryList != null)
                {
                    foreach (Geometry geometry in ft.GeometryList)
                    {
                        XmlElement shapeElement = myXmlDoc.CreateElement("Shape", "http://www.jurassic.com.cn/3gx");
                        shapeElement.SetAttribute("name", geometry.NAME);

                        XmlReader            reader = XmlReader.Create(new StringReader(DbGeography.FromText(geometry.GEOMETRY).AsGml()));
                        AbstractGeometryType gml    = GmlHelper.Deserialize(reader);
                        StringWriter         sw     = new StringWriter();
                        XmlWriter            xw     = XmlWriter.Create(sw);
                        GmlHelper.Serialize(xw, gml);

                        XmlDocument shapeDoc = new XmlDocument();
                        shapeDoc.LoadXml(sw.ToString());

                        XmlDocumentFragment shape = myXmlDoc.CreateDocumentFragment();
                        shape.InnerXml = shapeDoc.DocumentElement.OuterXml;

                        shapeElement.AppendChild(shape);
                        shapesElement.AppendChild(shapeElement);
                    }
                }
                gfElement.AppendChild(shapesElement);

                rootElement.AppendChild(gfElement);
            }
            return(myXmlDoc);
        }
        /// <summary>
        /// Converts DataSet-object to XML.
        /// </summary>
        /// <param name="result">DataSet-object</param>
        /// <param name="options">Input configurations</param>
        /// <param name="file_name">Excel file name to be read</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>String containing contents in XML format.</returns>
        public static string ConvertToXml(DataSet result, Options options, string file_name, CancellationToken cancellationToken)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true
            };

            var builder = new StringBuilder();
            using (var sw = new StringWriter(builder))
            {
                using (var xw = XmlWriter.Create(sw, settings))
                {
                    // Write workbook element. Workbook is also known as sheet.
                    xw.WriteStartDocument();
                    xw.WriteStartElement("workbook");
                    xw.WriteAttributeString("workbook_name", file_name);

                    foreach (DataTable table in result.Tables)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        // Read only wanted worksheets. If none is specified read all.
                        if (options.ReadOnlyWorkSheetWithName.Contains(table.TableName) || options.ReadOnlyWorkSheetWithName.Length == 0)
                        {
                            // Write worksheet element.
                            xw.WriteStartElement("worksheet");
                            xw.WriteAttributeString("worksheet_name", table.TableName);

                            for (var i = 0; i < table.Rows.Count; i++)
                            {
                                cancellationToken.ThrowIfCancellationRequested();
                                var row_element_is_writed = false;
                                for (var j = 0; j < table.Columns.Count; j++)
                                {
                                    // Write column only if it has some content.
                                    var content = table.Rows[i].ItemArray[j];
                                    if (string.IsNullOrWhiteSpace(content.ToString()) == false)
                                    {

                                        if (row_element_is_writed == false)
                                        {
                                            xw.WriteStartElement("row");
                                            xw.WriteAttributeString("row_header", (i + 1).ToString());
                                            row_element_is_writed = true;
                                        }

                                        xw.WriteStartElement("column");
                                        if (options.UseNumbersAsColumnHeaders)
                                        {
                                            xw.WriteAttributeString("column_header", (j + 1).ToString());
                                        }
                                        else
                                        {
                                            xw.WriteAttributeString("column_header", ColumnIndexToColumnLetter(j + 1));
                                        }
                                        if (content.GetType().Name == "DateTime")
                                        {
                                            content = ConvertDateTimes((DateTime)content, options);
                                        }
                                        xw.WriteString(content.ToString());
                                        xw.WriteEndElement();
                                    }
                                }
                                if (row_element_is_writed == true)
                                {
                                    xw.WriteEndElement();
                                }
                            }
                            xw.WriteEndElement();
                        }
                    }
                    xw.WriteEndDocument();
                    xw.Close();
                    return builder.ToString();
                }
            }
        }
Exemplo n.º 20
0
        public string GetRequest(SamlRequestFormat format, string assertionConsumerServiceUrl, string certPath, string certPassword)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;

                using (XmlWriter xw = XmlWriter.Create(sw, xws))
                {
                    xw.WriteStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol");
                    xw.WriteAttributeString("ID", _id);
                    xw.WriteAttributeString("Version", "2.0");
                    xw.WriteAttributeString("IssueInstant", _issueInstant);
                    xw.WriteAttributeString("Destination", _ssoSettings.SsoEndPoint);
                    xw.WriteAttributeString("AssertionConsumerServiceURL", assertionConsumerServiceUrl);

                    // for ADFS
                    xw.WriteAttributeString("Consent", "urn:oasis:names:tc:SAML:2.0:consent:unspecified");
                    xw.WriteStartElement("Issuer", "urn:oasis:names:tc:SAML:2.0:assertion");
                    xw.WriteString("www.sp.com");
                    xw.WriteEndElement();

                    // for ADFS
                    xw.WriteStartElement("Conditions", "urn:oasis:names:tc:SAML:2.0:assertion");
                    xw.WriteStartElement("AudienceRestriction");
                    xw.WriteStartElement("Audience");
                    xw.WriteString(assertionConsumerServiceUrl);
                    xw.WriteEndElement();
                    xw.WriteEndElement();
                    xw.WriteEndElement();

                    xw.WriteEndElement();
                }

                _log.DebugFormat("Format: {0}, SAML Request: {1}", format, sw.ToString());
                if (format == SamlRequestFormat.Base64)
                {
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(sw.ToString());
                    AsymmetricAlgorithm privateKey;
                    try
                    {
                        _log.DebugFormat("Using certificate for signing saml requests. certPath={0}", certPath);
                        X509Certificate2 cert = new X509Certificate2(certPath, certPassword);
                        privateKey = cert.PrivateKey;
                    }
                    catch (CryptographicException ex)
                    {
                        _log.DebugFormat("Using SAML requests without certificate. {0}", ex);
                        privateKey = null;
                    }
                    catch (Exception ex)
                    {
                        _log.ErrorFormat("Certification error. {0}", ex);
                        throw new Exception("Certification error");
                    }
                    return(CreateQueryString(xdoc.DocumentElement, privateKey));
                }
                _log.ErrorFormat("Unknown format: {0}", format);
                return(null);
            }
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            Utility.WriteExeDetails();

            Console.WriteLine("Loading skill strings...");
            Utility.LoadSkillStrings(root);

            Console.WriteLine("Loading skills...");
            Utility.LoadSkills(root);

            Console.WriteLine("Loading skill learns...");
            Utility.LoadSkillLearns(root);

            var skill_learns = Utility.SkillLearnIndex.SkillList.Where(n => n.id != 0);

            SkillTreeTemplates outputFile = new SkillTreeTemplates();

            outputFile.skills = new List <SkillTreeTemplate>();

            foreach (var skill in skill_learns)
            {
                var template = new SkillTreeTemplate();

                template.minLevel   = skill.pc_level;
                template.race       = skill.skillRace.ToString();
                template.stigma     = skill.stigma_display > 0 ? true : false;
                template.autolearn  = (bool)skill.autolearn;
                template.name       = Utility.SkillStringIndex.GetString(Utility.SkillIndex[skill.skill].desc);
                template.skillLevel = skill.skill_level;
                template.skillId    = Utility.SkillIndex[skill.skill].id;
                template.classId    = skill.classId;

                outputFile.skills.Add(template);
            }

            string outputPath = Path.Combine(root, @".\output");

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            var settings = new XmlWriterSettings()
            {
                CheckCharacters = false,
                CloseOutput     = false,
                Indent          = true,
                IndentChars     = "\t",
                NewLineChars    = "\n",
                Encoding        = new UTF8Encoding(false)
            };

            try {
                using (var fs = new FileStream(Path.Combine(outputPath, "skill_tree.xml"), FileMode.Create, FileAccess.Write))
                    using (var writer = XmlWriter.Create(fs, settings)) {
                        XmlSerializer ser = new XmlSerializer(typeof(SkillTreeTemplates));
                        ser.Serialize(writer, outputFile);
                    }
            }
            catch (Exception ex) {
                Debug.Print(ex.ToString());
            }
        }
Exemplo n.º 22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async(context) =>
            {
                HttpRequest request   = context.Request;
                HttpResponse response = context.Response;
                response.ContentType  = "text/html";
                XmlDocument document  = new XmlDocument();
                document.AppendChild(document.CreateElement("html"));
                XmlElement headElement = document.DocumentElement.AppendElement("head");
                headElement.AppendElement("meta").ApplyAttributeValue("charset", "utf-8");
                headElement.AppendElement("meta")
                .ApplyAttributeValue("name", "viewport")
                .ApplyAttributeValue("content", "width=device-width, initial-scale=1, shrink-to-fit=no");
                headElement.AppendTextElement("title", "Example Web Application");
                XmlElement bodyElement  = document.DocumentElement.AppendElement("body");
                XmlElement tableElement = bodyElement.AppendElement("table");
                XmlElement rowElement   = tableElement.AppendElement("tr");
                rowElement.AppendTextElement("th", "IHostingEnvironment.ContentRootPath").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", env.ContentRootPath ?? "");
                rowElement.AppendTextElement("th", "IHostingEnvironment.ContentRootFileProvider").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", (env.ContentRootFileProvider == null) ? "null" : env.ContentRootFileProvider.GetType().FullName);
                rowElement = tableElement.AppendElement("tr");
                rowElement.AppendTextElement("th", "IHostingEnvironment.WebRootPath").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", env.WebRootPath ?? "");
                rowElement.AppendTextElement("th", "IHostingEnvironment.WebRootFileProvider").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", (env.WebRootFileProvider == null) ? "null" : env.WebRootFileProvider.GetType().FullName);
                rowElement = tableElement.AppendElement("tr");
                rowElement.AppendTextElement("th", "HttpRequest.Path.Hasvalue").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", request.Path.HasValue.ToString());
                rowElement.AppendTextElement("th", "HttpRequest.Path.Value").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", (request.Path.HasValue) ? request.Path.Value : "");
                rowElement = tableElement.AppendElement("tr");
                rowElement.AppendTextElement("th", "HttpRequest.PathBase.Hasvalue").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", request.PathBase.HasValue.ToString());
                rowElement.AppendTextElement("th", "HttpRequest.PathBase.Value").ApplyAttributeValue("style", "text-align: right");
                rowElement.AppendTextElement("th", (request.PathBase.HasValue) ? request.PathBase.Value : "");
                XmlWriterSettings settings = new XmlWriterSettings
                {
                    Encoding = new System.Text.UTF8Encoding(false),
                    Indent   = true
                };

                string html;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (XmlWriter writer = XmlWriter.Create(ms, settings))
                    {
                        document.WriteTo(writer);
                        writer.Flush();
                        html = settings.Encoding.GetString(ms.ToArray());
                    }
                }
                await context.Response.WriteAsync("<!DOCTYPE html>\n" + html);
            });
        }
Exemplo n.º 23
0
        private object ProcessUploadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in request.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (TempIdToEntityMapping == null)
                        {
                            TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }
                        tempId = Guid.NewGuid().ToString();
                        TempIdToEntityMapping.Add(tempId, entity);
                    }

                    this._syncWriter.AddItem(entity, tempId);
                }

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));

                memoryStream.Flush();
                // Set the content length
                webRequest.ContentLength = memoryStream.Position;

                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    CopyStreamContent(memoryStream, requestStream);

                    // Close the request stream
                    requestStream.Flush();
                    requestStream.Close();
                }
            }

            // Fire the Before request handler
            this.FirePreRequestHandler(webRequest);

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSetResponse changeSetResponse = new ChangeSetResponse();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                        case ReaderItemType.Entry:
                            IOfflineEntity entity      = this._syncReader.GetItem();
                            IOfflineEntity ackedEntity = entity;
                            string         tempId      = null;

                            // If conflict only one temp ID should be set
                            if (this._syncReader.HasTempId() && this._syncReader.HasConflictTempId())
                            {
                                throw new CacheControllerException(string.Format("Service returned a TempId '{0}' in both live and conflicting entities.",
                                                                                 this._syncReader.GetTempId()));
                            }

                            // Validate the live temp ID if any, before adding anything to the offline context
                            if (this._syncReader.HasTempId())
                            {
                                tempId = this._syncReader.GetTempId();
                                CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, entity, tempId, changeSetResponse);
                            }

                            //  If conflict
                            if (this._syncReader.HasConflict())
                            {
                                Conflict       conflict       = this._syncReader.GetConflict();
                                IOfflineEntity conflictEntity = (conflict is SyncConflict) ?
                                                                ((SyncConflict)conflict).LosingEntity : ((SyncError)conflict).ErrorEntity;

                                // Validate conflict temp ID if any
                                if (this._syncReader.HasConflictTempId())
                                {
                                    tempId = this._syncReader.GetConflictTempId();
                                    CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, conflictEntity, tempId, changeSetResponse);
                                }

                                // Add conflict
                                changeSetResponse.AddConflict(conflict);

                                //
                                // If there is a conflict and the tempId is set in the conflict entity then the client version lost the
                                // conflict and the live entity is the server version (ServerWins)
                                //
                                if (this._syncReader.HasConflictTempId() && entity.ServiceMetadata.IsTombstone)
                                {
                                    //
                                    // This is a ServerWins conflict, or conflict error. The winning version is a tombstone without temp Id
                                    // so there is no way to map the winning entity with a temp Id. The temp Id is in the conflict so we are
                                    // using the conflict entity, which has the PK, to build a tombstone entity used to update the offline context
                                    //
                                    // In theory, we should copy the service metadata but it is the same end result as the service fills in
                                    // all the properties in the conflict entity
                                    //

                                    // Add the conflict entity
                                    conflictEntity.ServiceMetadata.IsTombstone = true;
                                    ackedEntity = conflictEntity;
                                }
                            }

                            // Add ackedEntity to storage. If ackedEntity is still equal to entity then add non-conflict entity.
                            if (!String.IsNullOrEmpty(tempId))
                            {
                                changeSetResponse.AddUpdatedItem(ackedEntity);
                            }

                            break;

                        case ReaderItemType.SyncBlob:
                            changeSetResponse.ServerBlob = this._syncReader.GetServerBlob();
                            break;
                        }
                    }
                }

                if (TempIdToEntityMapping != null && TempIdToEntityMapping.Count != 0)
                {
                    // The client sent some inserts which werent ack'd by the service. Throw.
                    StringBuilder builder = new StringBuilder("Server did not acknowledge with a permanant Id for the following tempId's: ");
                    builder.Append(string.Join(",", TempIdToEntityMapping.Keys.ToArray()));
                    throw new CacheControllerException(builder.ToString());
                }

                this.FirePostResponseHandler(webResponse);

                webResponse.Close();

                return(changeSetResponse);
            }
            else
            {
                throw new CacheControllerException(
                          string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                        webResponse.StatusCode,
                                        webResponse.StatusDescription));
            }
        }
        public IRequest Marshall(PutBucketReplicationRequest putBucketreplicationRequest)
        {
            IRequest request = new DefaultRequest(putBucketreplicationRequest, "AmazonS3");

            request.HttpMethod = "PUT";

            if (string.IsNullOrEmpty(putBucketreplicationRequest.BucketName))
            {
                throw new System.ArgumentException("BucketName is a required property and must be set before making this call.", "PutBucketReplicationRequest.BucketName");
            }

            request.ResourcePath = string.Concat("/", S3Transforms.ToStringValue(putBucketreplicationRequest.BucketName));

            request.AddSubResource("replication");

            if (putBucketreplicationRequest.IsSetToken())
            {
                request.Headers.Add("x-amz-bucket-object-lock-token", putBucketreplicationRequest.Token);
            }

            if (putBucketreplicationRequest.IsSetExpectedBucketOwner())
            {
                request.Headers.Add(S3Constants.AmzHeaderExpectedBucketOwner, S3Transforms.ToStringValue(putBucketreplicationRequest.ExpectedBucketOwner));
            }

            var stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);

            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8, OmitXmlDeclaration = true
            }))
            {
                var replicationConfiguration = putBucketreplicationRequest.Configuration;

                if (replicationConfiguration != null)
                {
                    xmlWriter.WriteStartElement("ReplicationConfiguration", "");
                    if (replicationConfiguration.Role != null)
                    {
                        xmlWriter.WriteElementString("Role", "", S3Transforms.ToXmlStringValue(replicationConfiguration.Role));
                    }
                    if (replicationConfiguration.Rules != null)
                    {
                        foreach (var rule in replicationConfiguration.Rules)
                        {
                            xmlWriter.WriteStartElement("Rule");
                            if (rule.IsSetId())
                            {
                                xmlWriter.WriteElementString("ID", "", S3Transforms.ToXmlStringValue(rule.Id));
                            }
                            if (rule.IsSetPriority())
                            {
                                xmlWriter.WriteElementString("Priority", "", S3Transforms.ToXmlStringValue(rule.Priority));
                            }
                            if (rule.IsSetPrefix())
                            {
                                xmlWriter.WriteElementString("Prefix", "", S3Transforms.ToXmlStringValue(rule.Prefix));
                            }

                            if (rule.IsSetFilter())
                            {
                                xmlWriter.WriteStartElement("Filter", "");
                                if (rule.Filter.IsSetPrefix())
                                {
                                    xmlWriter.WriteElementString("Prefix", "", S3Transforms.ToXmlStringValue(rule.Filter.Prefix));
                                }
                                if (rule.Filter.IsSetTag())
                                {
                                    rule.Filter.Tag.Marshall("Tag", xmlWriter);
                                }
                                if (rule.Filter.IsSetAnd())
                                {
                                    xmlWriter.WriteStartElement("And");
                                    if (rule.Filter.And.IsSetPrefix())
                                    {
                                        xmlWriter.WriteElementString("Prefix", "", S3Transforms.ToXmlStringValue(rule.Filter.And.Prefix));
                                    }
                                    if (rule.Filter.And.IsSetTags())
                                    {
                                        foreach (var tag in rule.Filter.And.Tags)
                                        {
                                            tag.Marshall("Tag", xmlWriter);
                                        }
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                xmlWriter.WriteEndElement();
                            }

                            if (rule.IsSetStatus())
                            {
                                xmlWriter.WriteElementString("Status", "", S3Transforms.ToXmlStringValue(rule.Status.ToString()));
                            }
                            if (rule.IsSetSourceSelectionCriteria())
                            {
                                xmlWriter.WriteStartElement("SourceSelectionCriteria");
                                if (rule.SourceSelectionCriteria.IsSetSseKmsEncryptedObjects())
                                {
                                    xmlWriter.WriteStartElement("SseKmsEncryptedObjects");
                                    if (rule.SourceSelectionCriteria.SseKmsEncryptedObjects.IsSetSseKmsEncryptedObjectsStatus())
                                    {
                                        xmlWriter.WriteElementString("Status", "", rule.SourceSelectionCriteria.SseKmsEncryptedObjects.SseKmsEncryptedObjectsStatus);
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                if (rule.SourceSelectionCriteria.IsSetReplicaModifications())
                                {
                                    xmlWriter.WriteStartElement("ReplicaModifications");
                                    if (rule.SourceSelectionCriteria.ReplicaModifications.IsSetStatus())
                                    {
                                        xmlWriter.WriteElementString("Status", "", rule.SourceSelectionCriteria.ReplicaModifications.Status);
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                xmlWriter.WriteEndElement();
                            }
                            if (rule.IsSetExistingObjectReplication())
                            {
                                xmlWriter.WriteStartElement("ExistingObjectReplication");
                                if (rule.ExistingObjectReplication.IsSetExistingObjectReplicationStatus())
                                {
                                    xmlWriter.WriteElementString("Status", "", rule.ExistingObjectReplication.Status);
                                }
                                xmlWriter.WriteEndElement();
                            }
                            if (rule.IsSetDeleteMarkerReplication())
                            {
                                xmlWriter.WriteStartElement("DeleteMarkerReplication");
                                if (rule.DeleteMarkerReplication.IsSetStatus())
                                {
                                    xmlWriter.WriteElementString("Status", "", rule.DeleteMarkerReplication.Status);
                                }
                                xmlWriter.WriteEndElement();
                            }
                            if (rule.IsSetDestination())
                            {
                                xmlWriter.WriteStartElement("Destination", "");
                                if (rule.Destination.IsSetBucketArn())
                                {
                                    xmlWriter.WriteElementString("Bucket", "", rule.Destination.BucketArn);
                                }
                                if (rule.Destination.IsSetStorageClass())
                                {
                                    xmlWriter.WriteElementString("StorageClass", "", rule.Destination.StorageClass);
                                }
                                if (rule.Destination.IsSetAccountId())
                                {
                                    xmlWriter.WriteElementString("Account", "", S3Transforms.ToXmlStringValue(rule.Destination.AccountId));
                                }
                                if (rule.Destination.IsSetEncryptionConfiguration())
                                {
                                    xmlWriter.WriteStartElement("EncryptionConfiguration");
                                    if (rule.Destination.EncryptionConfiguration.isSetReplicaKmsKeyID())
                                    {
                                        xmlWriter.WriteElementString("ReplicaKmsKeyID", "", S3Transforms.ToXmlStringValue(rule.Destination.EncryptionConfiguration.ReplicaKmsKeyID));
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                if (rule.Destination.IsSetMetrics())
                                {
                                    xmlWriter.WriteStartElement("Metrics");
                                    if (rule.Destination.Metrics.IsSetStatus())
                                    {
                                        xmlWriter.WriteElementString("Status", "", S3Transforms.ToXmlStringValue(rule.Destination.Metrics.Status));
                                    }
                                    if (rule.Destination.Metrics.IsSetEventThreshold())
                                    {
                                        xmlWriter.WriteStartElement("EventThreshold");
                                        if (rule.Destination.Metrics.EventThreshold.IsSetMinutes())
                                        {
                                            xmlWriter.WriteElementString("Minutes", "", S3Transforms.ToXmlStringValue(rule.Destination.Metrics.EventThreshold.Minutes));
                                        }
                                        xmlWriter.WriteEndElement();
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                if (rule.Destination.IsSetReplicationTime())
                                {
                                    xmlWriter.WriteStartElement("ReplicationTime");
                                    if (rule.Destination.ReplicationTime.IsSetStatus())
                                    {
                                        xmlWriter.WriteElementString("Status", "", S3Transforms.ToXmlStringValue(rule.Destination.ReplicationTime.Status));
                                    }
                                    if (rule.Destination.ReplicationTime.IsSetTime())
                                    {
                                        xmlWriter.WriteStartElement("Time");
                                        if (rule.Destination.ReplicationTime.Time.IsSetMinutes())
                                        {
                                            xmlWriter.WriteElementString("Minutes", "", S3Transforms.ToXmlStringValue(rule.Destination.ReplicationTime.Time.Minutes));
                                        }
                                        xmlWriter.WriteEndElement();
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                if (rule.Destination.IsSetAccessControlTranslation())
                                {
                                    xmlWriter.WriteStartElement("AccessControlTranslation");
                                    if (rule.Destination.AccessControlTranslation.IsSetOwner())
                                    {
                                        xmlWriter.WriteElementString("Owner", "", S3Transforms.ToXmlStringValue(rule.Destination.AccessControlTranslation.Owner));
                                    }
                                    xmlWriter.WriteEndElement();
                                }
                                xmlWriter.WriteEndElement();
                            }
                            xmlWriter.WriteEndElement();
                        }
                    }

                    xmlWriter.WriteEndElement();
                }
            }

            try
            {
                var content = stringWriter.ToString();
                request.Content = Encoding.UTF8.GetBytes(content);
                request.Headers[HeaderKeys.ContentTypeHeader] = "application/xml";

                var checksum = AWSSDKUtils.GenerateChecksumForContent(content, true);
                request.Headers[HeaderKeys.ContentMD5Header] = checksum;
            }
            catch (EncoderFallbackException e)
            {
                throw new AmazonServiceException("Unable to marshall request to XML", e);
            }

            return(request);
        }
Exemplo n.º 25
0
        public static string Deserialize(Stream input, Endian endian)
        {
            if (input.ReadValueU8() != 4)
            {
                throw new FormatException();
            }

            var count = input.ReadValueU32(endian);

            if (count > 0x3FFFFFFF)
            {
                throw new FormatException();
            }

            var dataSize = input.ReadValueU32(endian);

            if (dataSize > 0x500000)
            {
                throw new FormatException();
            }
            var data = input.ReadToMemoryStream((int)dataSize);

            var nodes = new List <NodeEntry>();

            for (uint i = 0; i < count; i++)
            {
                var node = new NodeEntry()
                {
                    Name  = DeserializeData(data, input.ReadValueU32(endian), endian),
                    Value = DeserializeData(data, input.ReadValueU32(endian), endian),
                    Id    = input.ReadValueU32(),
                };

                var childCount = input.ReadValueU32(endian);
                node.Children.Clear();
                for (uint j = 0; j < childCount; j++)
                {
                    node.Children.Add(input.ReadValueU32(endian));
                }

                var attributeCount = input.ReadValueU32(endian);
                node.Attributes.Clear();
                for (uint j = 0; j < attributeCount; j++)
                {
                    var attribute = new AttributeEntry()
                    {
                        Name  = DeserializeData(data, input.ReadValueU32(endian), endian),
                        Value = DeserializeData(data, input.ReadValueU32(endian), endian),
                    };
                    if (attribute.Name.Value.ToString() == "__type")
                    {
                        throw new FormatException("someone used __type?");
                    }
                    node.Attributes.Add(attribute);
                }

                nodes.Add(node);
            }

            var settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.OmitXmlDeclaration = true;

            var output = new StringBuilder();
            var writer = XmlWriter.Create(output, settings);

            writer.WriteStartDocument();

            if (nodes.Count > 0)
            {
                var root = nodes.SingleOrDefault(n => n.Id == 0);

                if (root == null)
                {
                    throw new InvalidOperationException();
                }

                if (root.Children.Count != 1 || root.Attributes.Count > 0 || root.Value != null)
                {
                    throw new FormatException();
                }

                foreach (var childId in root.Children)
                {
                    var child = nodes.SingleOrDefault(n => n.Id == childId);
                    if (child == null)
                    {
                        throw new KeyNotFoundException();
                    }

                    WriteXmlNode(writer, nodes, child);
                }
            }
            writer.WriteEndDocument();
            writer.Flush();
            return(output.ToString());
        }
Exemplo n.º 26
0
        public static string Convert(string kva, bool isFile, out bool relativeTrajectories)
        {
            // the kva parameter can either be a filepath or the xml string.
            // We return the same kind of string as passed in.
            string result = kva;

            relativeTrajectories = false;

            XmlDocument kvaDoc = new XmlDocument();

            try
            {
                if (isFile)
                {
                    kvaDoc.Load(kva);
                }
                else
                {
                    kvaDoc.LoadXml(kva);
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("The file couldn't be loaded. No conversion or reading will be attempted.");
                log.Error(e.Message);
                return(result);
            }

            string            tempFile = Path.Combine(Software.SettingsDirectory, "temp.kva");
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            XmlNode formatNode = kvaDoc.DocumentElement.SelectSingleNode("descendant::FormatVersion");

            if (formatNode == null)
            {
                log.ErrorFormat("The format node couldn't be found. No conversion will be attempted.");
                return(result);
            }

            double format;
            bool   read = double.TryParse(formatNode.InnerText, NumberStyles.Any, CultureInfo.InvariantCulture, out format);

            if (!read)
            {
                log.ErrorFormat("The format couldn't be parsed. No conversion will be attempted. Read:{0}", formatNode.InnerText);
                return(result);
            }

            if (format < 2.0 && format >= 1.3)
            {
                log.DebugFormat("Older format detected ({0}). Starting conversion", format);
                relativeTrajectories = true;

                try
                {
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    string stylesheet         = Application.StartupPath + "\\xslt\\kva-1.5to2.0.xsl";
                    xslt.Load(stylesheet);

                    if (isFile)
                    {
                        using (XmlWriter xw = XmlWriter.Create(tempFile, settings))
                        {
                            xslt.Transform(kvaDoc, xw);
                        }

                        result = tempFile;
                    }
                    else
                    {
                        StringBuilder builder = new StringBuilder();
                        using (XmlWriter xw = XmlWriter.Create(builder, settings))
                        {
                            xslt.Transform(kvaDoc, xw);
                        }

                        result = builder.ToString();
                    }

                    log.DebugFormat("Older format converted.");
                }
                catch (Exception)
                {
                    log.ErrorFormat("An error occurred during KVA conversion. Conversion aborted.", format.ToString());
                }
            }
            else if (format <= 1.2)
            {
                log.ErrorFormat("Format too old ({0}). No conversion will be attempted.", format.ToString());
            }

            return(result);
        }
Exemplo n.º 27
0
        public void SaveClientPermissions()
        {
            //delete old client permission file
            if (File.Exists("Data/clientpermissions.txt"))
            {
                File.Delete("Data/clientpermissions.txt");
            }

            GameServer.Log("Saving client permissions", ServerLog.MessageType.ServerMessage);

            XDocument doc = new XDocument(new XElement("ClientPermissions"));

            foreach (SavedClientPermission clientPermission in ClientPermissions)
            {
                var matchingPreset = PermissionPreset.List.Find(p => p.MatchesPermissions(clientPermission.Permissions, clientPermission.PermittedCommands));
                if (matchingPreset != null && matchingPreset.Name == "None")
                {
                    continue;
                }

                XElement clientElement = new XElement("Client",
                                                      new XAttribute("name", clientPermission.Name));

                if (clientPermission.SteamID > 0)
                {
                    clientElement.Add(new XAttribute("steamid", clientPermission.SteamID));
                }
                else
                {
                    clientElement.Add(new XAttribute("endpoint", clientPermission.EndPoint));
                }

                if (matchingPreset == null)
                {
                    clientElement.Add(new XAttribute("permissions", clientPermission.Permissions.ToString()));
                    if (clientPermission.Permissions.HasFlag(Networking.ClientPermissions.ConsoleCommands))
                    {
                        foreach (DebugConsole.Command command in clientPermission.PermittedCommands)
                        {
                            clientElement.Add(new XElement("command", new XAttribute("name", command.names[0])));
                        }
                    }
                }
                else
                {
                    clientElement.Add(new XAttribute("preset", matchingPreset.Name));
                }
                doc.Root.Add(clientElement);
            }

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineOnAttributes = true;

                using (var writer = XmlWriter.Create(ClientPermissionsFile, settings))
                {
                    doc.Save(writer);
                }
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Saving client permissions to " + ClientPermissionsFile + " failed", e);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(UpdateFieldLevelEncryptionProfileRequest publicRequest)
        {
            var request = new DefaultRequest(publicRequest, "Amazon.CloudFront");

            request.HttpMethod = "PUT";

            if (publicRequest.IsSetIfMatch())
            {
                request.Headers["If-Match"] = publicRequest.IfMatch;
            }
            if (!publicRequest.IsSetId())
            {
                throw new AmazonCloudFrontException("Request object does not have required field Id set");
            }
            request.AddPathResource("{Id}", StringUtils.FromString(publicRequest.Id));
            request.ResourcePath = "/2020-05-31/field-level-encryption-profile/{Id}/config";

            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
            {
                Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true
            }))
            {
                if (publicRequest.IsSetFieldLevelEncryptionProfileConfig())
                {
                    xmlWriter.WriteStartElement("FieldLevelEncryptionProfileConfig", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                    if (publicRequest.FieldLevelEncryptionProfileConfig.IsSetCallerReference())
                    {
                        xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequest.FieldLevelEncryptionProfileConfig.CallerReference));
                    }

                    if (publicRequest.FieldLevelEncryptionProfileConfig.IsSetComment())
                    {
                        xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequest.FieldLevelEncryptionProfileConfig.Comment));
                    }


                    if (publicRequest.FieldLevelEncryptionProfileConfig.EncryptionEntities != null)
                    {
                        xmlWriter.WriteStartElement("EncryptionEntities", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                        var publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItems = publicRequest.FieldLevelEncryptionProfileConfig.EncryptionEntities.Items;
                        if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItems != null && publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItems.Count > 0)
                        {
                            xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                            foreach (var publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue in publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItems)
                            {
                                if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue != null)
                                {
                                    xmlWriter.WriteStartElement("EncryptionEntity", "http://cloudfront.amazonaws.com/doc/2020-05-31/");

                                    if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.FieldPatterns != null)
                                    {
                                        xmlWriter.WriteStartElement("FieldPatterns", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                        var publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValueFieldPatternsItems = publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.FieldPatterns.Items;
                                        if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValueFieldPatternsItems != null && publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValueFieldPatternsItems.Count > 0)
                                        {
                                            xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                            foreach (var publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValueFieldPatternsItemsValue in publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValueFieldPatternsItems)
                                            {
                                                xmlWriter.WriteStartElement("FieldPattern", "http://cloudfront.amazonaws.com/doc/2020-05-31/");
                                                xmlWriter.WriteValue(publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValueFieldPatternsItemsValue);
                                                xmlWriter.WriteEndElement();
                                            }
                                            xmlWriter.WriteEndElement();
                                        }
                                        if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.FieldPatterns.IsSetQuantity())
                                        {
                                            xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromInt(publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.FieldPatterns.Quantity));
                                        }

                                        xmlWriter.WriteEndElement();
                                    }
                                    if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.IsSetProviderId())
                                    {
                                        xmlWriter.WriteElementString("ProviderId", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.ProviderId));
                                    }

                                    if (publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.IsSetPublicKeyId())
                                    {
                                        xmlWriter.WriteElementString("PublicKeyId", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequestFieldLevelEncryptionProfileConfigEncryptionEntitiesItemsValue.PublicKeyId));
                                    }

                                    xmlWriter.WriteEndElement();
                                }
                            }
                            xmlWriter.WriteEndElement();
                        }
                        if (publicRequest.FieldLevelEncryptionProfileConfig.EncryptionEntities.IsSetQuantity())
                        {
                            xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromInt(publicRequest.FieldLevelEncryptionProfileConfig.EncryptionEntities.Quantity));
                        }

                        xmlWriter.WriteEndElement();
                    }
                    if (publicRequest.FieldLevelEncryptionProfileConfig.IsSetName())
                    {
                        xmlWriter.WriteElementString("Name", "http://cloudfront.amazonaws.com/doc/2020-05-31/", StringUtils.FromString(publicRequest.FieldLevelEncryptionProfileConfig.Name));
                    }


                    xmlWriter.WriteEndElement();
                }
            }
            try
            {
                string content = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(content);
                request.Headers["Content-Type"] = "application/xml";
                request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-05-31";
            }
            catch (EncoderFallbackException e)
            {
                throw new AmazonServiceException("Unable to marshall request to XML", e);
            }

            return(request);
        }
Exemplo n.º 29
0
        static void GetFolderPermissions(string utente, string folderId)
        {
            NetworkCredential userCredentials = new NetworkCredential(username, password);

            var getFolderSOAPRequest =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "              xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\"\n" +
                "             xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\"\n" +
                "              xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                " <soap:Header>\n" +
                "   <t:RequestServerVersion Version=\"Exchange2013_SP1\" />\n" +
                " </soap:Header>\n" +
                " <soap:Body>\n" +
                "   <m:GetFolder>\n" +
                "     <m:FolderShape>\n" +
                "       <t:BaseShape>IdOnly</t:BaseShape>\n" +
                "       <t:AdditionalProperties>\n" +
                "         <t:FieldURI FieldURI=\"folder:PermissionSet\" />\n" +
                "       </t:AdditionalProperties>\n" +
                "     </m:FolderShape>\n" +
                "     <m:FolderIds>\n" +
                "       <t:DistinguishedFolderId Id=\"" + folderId + "\">\n" +
                "<t:Mailbox> <t:EmailAddress>" + utente + "</t:EmailAddress> </t:Mailbox>" +
                "</t:DistinguishedFolderId>" +
                "     </m:FolderIds>\n" +
                "   </m:GetFolder>\n" +
                " </soap:Body>\n" +
                "</soap:Envelope>\n";

            // Write the get folder operation request to the console and log file.


            //var getFolderRequest = WebRequest.CreateHttp(Office365WebServicesURL);
            var getFolderRequest = WebRequest.CreateHttp(WebServicesURL);

            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            getFolderRequest.AllowAutoRedirect = false;
            getFolderRequest.Credentials       = userCredentials;
            getFolderRequest.Method            = "POST";
            getFolderRequest.ContentType       = "text/xml";


            var requestWriter = new StreamWriter(getFolderRequest.GetRequestStream());

            requestWriter.Write(getFolderSOAPRequest);
            requestWriter.Close();

            try
            {
                var getFolderResponse = (HttpWebResponse)(getFolderRequest.GetResponse());
                if (getFolderResponse.StatusCode == HttpStatusCode.OK)
                {
                    var      responseStream   = getFolderResponse.GetResponseStream();
                    XElement responseEnvelope = XElement.Load(responseStream);
                    if (responseEnvelope != null)
                    {
                        // Write the response to the console and log file.

                        StringBuilder     stringBuilder = new StringBuilder();
                        XmlWriterSettings settings      = new XmlWriterSettings();
                        settings.Indent = true;
                        XmlWriter writer = XmlWriter.Create(stringBuilder, settings);
                        responseEnvelope.Save(writer);
                        writer.Close();
                        //         Console.WriteLine(responseEnvelope);

                        var Folders = responseEnvelope.Descendants("Folders");
                        //         var Folders = responseEnvelope.Descendants("Folder");
                        //       var Folders = responseEnvelope.Descendants("Folder");



                        foreach (var book in StreamBooks(responseEnvelope.ToString()))
                        {
                            Console.WriteLine("Identity, User: {0}, {1}", book.Identity, book.User);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (ApplicationException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 30
0
        public override bool Execute(ProgramOptions programOptions)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            StepTiming stepTimingFunction = new StepTiming();
            stepTimingFunction.JobFileName = programOptions.ReportJobFilePath;
            stepTimingFunction.StepName = programOptions.ReportJob.Status.ToString();
            stepTimingFunction.StepID = (int)programOptions.ReportJob.Status;
            stepTimingFunction.StartTime = DateTime.Now;
            stepTimingFunction.NumEntities = 0;

            this.DisplayJobStepStartingStatus(programOptions);

            this.FilePathMap = new FilePathMap(programOptions);

            try
            {
                FileIOHelper.CreateFolder(this.FilePathMap.Report_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Report_GraphViz_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Report_Diagram_SVG_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Report_Diagram_PNG_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Report_Diagram_PDF_FolderPath());

                #region Construct object hierarchy with grants

                Account account = buildObjectHierarchyWithGrants();

                #endregion

                List<Role> rolesList = FileIOHelper.ReadListFromCSVFile<Role>(FilePathMap.Report_RoleDetail_FilePath(), new RoleMap());
                if (rolesList != null)
                {
                    #region Make GraphViz charts

                    loggerConsole.Info("Creating visualizations for {0} roles", rolesList.Count);

                    Role syntheticRoleAll = new Role();
                    syntheticRoleAll.Name = "ALL_ROLES_TOGETHER_SYNTHETIC";
                    rolesList.Insert(0, syntheticRoleAll);

                    ParallelOptions parallelOptions = new ParallelOptions();
                    if (programOptions.ProcessSequentially == true)
                    {
                        parallelOptions.MaxDegreeOfParallelism = 1;
                    }

                    int j = 0;

                    Parallel.ForEach<Role, int>(
                        rolesList,
                        parallelOptions,
                        () => 0,
                        (role, loop, subtotal) =>
                        {
                            logger.Info("Processing visualization for {0}", role);  

                            List<RoleHierarchy> thisRoleAndItsRelationsHierarchiesList = FileIOHelper.ReadListFromCSVFile<RoleHierarchy>(FilePathMap.Report_RoleHierarchy_RoleAndItsRelations_FilePath(role.Name), new RoleHierarchyMap());;
                            List<Role> thisRoleAndItsRelationsList = FileIOHelper.ReadListFromCSVFile<Role>(FilePathMap.Report_RoleDetail_RoleAndItsRelations_FilePath(role.Name), new RoleMap());

                            if (role == syntheticRoleAll)
                            {
                                thisRoleAndItsRelationsHierarchiesList = FileIOHelper.ReadListFromCSVFile<RoleHierarchy>(FilePathMap.Report_RoleHierarchy_FilePath(), new RoleHierarchyMap());;
                                thisRoleAndItsRelationsList = FileIOHelper.ReadListFromCSVFile<Role>(FilePathMap.Report_RoleDetail_FilePath(), new RoleMap());
                            }

                            if (thisRoleAndItsRelationsList != null && thisRoleAndItsRelationsHierarchiesList != null)
                            {
                                Dictionary<string, Role> rolesDict = thisRoleAndItsRelationsList.ToDictionary(k => k.Name, r => r);
                                Dictionary<string, Role> roleNamesOutput = new Dictionary<string, Role>(thisRoleAndItsRelationsList.Count);
                                Role roleBeingOutput = null;

                                StringBuilder sbGraphViz = new StringBuilder(64 * thisRoleAndItsRelationsHierarchiesList.Count + 128);

                                // Start the graph and set its default settings
                                sbGraphViz.AppendLine("digraph {");
                                sbGraphViz.AppendLine(" layout=\"dot\";");
                                sbGraphViz.AppendLine(" rankdir=\"TB\";");
                                sbGraphViz.AppendLine(" center=true;");
                                sbGraphViz.AppendLine(" splines=\"ortho\";");
                                sbGraphViz.AppendLine(" overlap=false;");
                                //sbGraphViz.AppendLine(" colorscheme=\"SVG\";");
                                sbGraphViz.AppendLine(" node [shape=\"rect\" style=\"filled,rounded\" fontname=\"Courier New\"];");
                                sbGraphViz.AppendLine(" edge [fontname=\"Courier New\"];");

                                sbGraphViz.AppendFormat(" // Graph for the Role {0}", role); sbGraphViz.AppendLine();

                                #region Role boxes

                                // Role boxes
                                sbGraphViz.AppendLine();
                                sbGraphViz.AppendLine(" // Roles");
                                sbGraphViz.AppendLine  ("  subgraph cluster_roles {");
                                sbGraphViz.AppendFormat("   label = \"roles related to: {0}\";", role); sbGraphViz.AppendLine();

                                // Add the role itself
                                sbGraphViz.AppendFormat("  \"{0}\"{1};", role.Name.Replace("\"", "\\\""), getRoleStyleAttribute(role)); sbGraphViz.AppendLine();
                                roleNamesOutput.Add(role.Name, role);

                                foreach (RoleHierarchy roleHierarchy in thisRoleAndItsRelationsHierarchiesList)
                                {
                                    if (roleHierarchy.GrantedTo != "<NOTHING>" && roleNamesOutput.ContainsKey(roleHierarchy.GrantedTo) == false)
                                    {
                                        // Name of the role with color
                                        rolesDict.TryGetValue(roleHierarchy.GrantedTo, out roleBeingOutput);
                                        sbGraphViz.AppendFormat("  \"{0}\"{1};", roleHierarchy.GrantedTo.Replace("\"", "\\\""), getRoleStyleAttribute(roleBeingOutput)); sbGraphViz.AppendLine();
                                        roleNamesOutput.Add(roleHierarchy.GrantedTo, roleBeingOutput);
                                    }
                                    
                                    if (roleNamesOutput.ContainsKey(roleHierarchy.Name) == false)
                                    {
                                        // Name of the role with color
                                        rolesDict.TryGetValue(roleHierarchy.Name, out roleBeingOutput);
                                        sbGraphViz.AppendFormat("  \"{0}\"{1};", roleHierarchy.Name.Replace("\"", "\\\""), getRoleStyleAttribute(roleBeingOutput)); sbGraphViz.AppendLine();
                                        roleNamesOutput.Add(roleHierarchy.Name, roleBeingOutput);
                                    }
                                }
                                sbGraphViz.AppendLine("  }// /Roles");

                                #endregion

                                #region Role hierachy

                                // Role connections
                                sbGraphViz.AppendLine();
                                sbGraphViz.AppendLine(" // Role hierarchy");
                                foreach (RoleHierarchy roleHierarchy in thisRoleAndItsRelationsHierarchiesList)
                                {
                                    if (roleHierarchy.GrantedTo == "<NOTHING>") continue;

                                    // Role to role connector
                                    sbGraphViz.AppendFormat(" \"{0}\"->\"{1}\";", roleHierarchy.GrantedTo.Replace("\"", "\\\""), roleHierarchy.Name.Replace("\"", "\\\"")); sbGraphViz.AppendLine();
                                }
                                sbGraphViz.AppendLine(" // /Role hierarchy");

                                #endregion

                                if (role != syntheticRoleAll)
                                {
                                    #region Databases, Schemas, Tables and Views

                                    sbGraphViz.AppendLine();
                                    sbGraphViz.AppendLine(" // Databases");
                                    sbGraphViz.AppendLine(" subgraph cluster_db_wrapper {");
                                    sbGraphViz.AppendLine("  label = \"Databases\";");
                                    sbGraphViz.AppendLine();

                                    int databaseIndex = 0;
                                    foreach (Database database in account.Databases)
                                    {
                                        // Should output database
                                        bool isDatabaseRelatedToSelectedRole = false;
                                        foreach (Grant grant in database.Grants)
                                        {
                                            if (grant.Privilege == "USAGE" || grant.Privilege == "OWNERSHIP")
                                            {
                                                if (roleNamesOutput.ContainsKey(grant.GrantedTo) == true)
                                                {
                                                    isDatabaseRelatedToSelectedRole = true;
                                                    break;
                                                }
                                            }
                                        }
                                        if (isDatabaseRelatedToSelectedRole == false) continue;

                                        // Output database
                                        sbGraphViz.AppendFormat("  // Database {0}", database.FullName); sbGraphViz.AppendLine();
                                        sbGraphViz.AppendFormat("  subgraph cluster_db_{0} {{", databaseIndex); sbGraphViz.AppendLine();
                                        sbGraphViz.AppendLine  ("   style=\"filled\";");
                                        sbGraphViz.AppendLine  ("   fillcolor=\"snow\";");
                                        sbGraphViz.AppendFormat("   label = \"db: {0}\";", database.ShortName); sbGraphViz.AppendLine();
                                        sbGraphViz.AppendLine  ("   node [shape=\"cylinder\" fillcolor=\"darkkhaki\"];");
                                        sbGraphViz.AppendLine();

                                        sbGraphViz.AppendFormat("   \"{0}\";", database.FullName); sbGraphViz.AppendLine();
                                        sbGraphViz.AppendLine();

                                        // List of schemas with number of tables and views
                                        sbGraphViz.AppendFormat("   \"{0}.schema\"  [shape=\"folder\" label=<", database.FullName);  sbGraphViz.AppendLine();
                                        sbGraphViz.AppendLine  ("    <table border=\"0\" cellborder=\"1\" bgcolor=\"white\">");
                                        sbGraphViz.AppendLine  ("     <tr><td>S</td><td>T</td><td>V</td></tr>");
                                        
                                        int schemaLimit = 0;
                                        foreach (Schema schema in database.Schemas)
                                        {
                                            // Only output 
                                            if (schemaLimit >= 10) 
                                            {
                                                sbGraphViz.AppendFormat("     <tr><td align=\"left\">Up to {0}</td><td align=\"right\">...</td><td align=\"right\">...</td></tr>", database.Schemas.Count); sbGraphViz.AppendLine();

                                                break;
                                            }

                                            // Do not output future grants which are in form of <SCHEMANAME>
                                            if (schema.ShortName.StartsWith("<") && schema.ShortName.EndsWith(">")) continue;

                                            sbGraphViz.AppendFormat("     <tr><td align=\"left\">{0}</td><td align=\"right\">{1}</td><td align=\"right\">{2}</td></tr>", System.Web.HttpUtility.HtmlEncode(schema.ShortName), schema.Tables.Count, schema.Views.Count); sbGraphViz.AppendLine();

                                            schemaLimit++;
                                        }
                                        sbGraphViz.AppendLine  ("    </table>>];");

                                        // Connect database to schemas
                                        sbGraphViz.AppendFormat("   \"{0}\"->\"{0}.schema\" [style=\"invis\"];", database.FullName); sbGraphViz.AppendLine();

                                        sbGraphViz.AppendFormat("  }} // /Database {0}", database.FullName); sbGraphViz.AppendLine();

                                        databaseIndex++;
                                    }

                                    sbGraphViz.AppendLine(" } // /Databases");

                                    #endregion

                                    #region Roles using databases 
                                    
                                    sbGraphViz.AppendLine();
                                    sbGraphViz.AppendLine(" // Roles using databases");

                                    // Output connectors from roles USAGE'ing databases
                                    foreach (Database database in account.Databases)
                                    {
                                        foreach (Grant grant in database.Grants)
                                        {
                                            if (grant.Privilege == "USAGE" || grant.Privilege == "OWNERSHIP")
                                            {
                                                if (roleNamesOutput.ContainsKey(grant.GrantedTo) == true)
                                                {
                                                    sbGraphViz.AppendFormat(" \"{0}\"->\"{1}\" [color=\"darkkhaki\"];", grant.GrantedTo, grant.ObjectNameUnquoted); sbGraphViz.AppendLine();
                                                }
                                            }
                                        }
                                    }

                                    sbGraphViz.AppendLine(" // /Roles using databases");

                                    #endregion
                                }

                                #region Legend

                                // Output Legend
                                sbGraphViz.AppendLine();
                                string legend = @" // Legend
    ""legend"" [label=<
    <table border=""0"" cellborder=""0"" bgcolor=""white"">
    <tr><td align=""center"">Legend</td></tr>
    <tr><td align=""left"" bgcolor=""lightgray"">BUILT IN</td></tr>
    <tr><td align=""left"" bgcolor=""beige"">SCIM</td></tr>
    <tr><td align=""left"" bgcolor=""palegreen"">ROLE MANAGEMENT</td></tr>
    <tr><td align=""left"" bgcolor=""orchid"">FUNCTIONAL</td></tr>
    <tr><td align=""left"" bgcolor=""plum"">FUNCTIONAL, NOT UNDER SYSADMIN</td></tr>
    <tr><td align=""left"" bgcolor=""lightblue"">ACCESS</td></tr>
    <tr><td align=""left"" bgcolor=""azure"">ACCESS, NOT UNDER SYSADMIN</td></tr>
    <tr><td align=""left"" bgcolor=""navajowhite"">UNKNOWN</td></tr>
    <tr><td align=""left"" bgcolor=""orange"">UNKNOWN, NOT UNDER ACCOUNTADMIN</td></tr>
    </table>>];";
                                sbGraphViz.AppendLine(legend);
                                
                                #endregion

                                // Close the graph
                                sbGraphViz.AppendLine("}");
        
                                FileIOHelper.SaveFileToPath(sbGraphViz.ToString(), FilePathMap.Report_GraphViz_RoleAndItsRelationsGrants_FilePath(role.Name), false);
                            }

                            return 1;
                        },
                        (finalResult) =>
                        {
                            Interlocked.Add(ref j, finalResult);
                            if (j % 50 == 0)
                            {
                                Console.Write("[{0}].", j);
                            }
                        }
                    );
                    loggerConsole.Info("Completed {0} Roles", rolesList.Count);

                    #endregion

                    #region HTML file with Links to Files

                    loggerConsole.Info("Creating HTML links for {0} roles", rolesList.Count);

                    // Create the HTML page with links for all the images
                    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                    xmlWriterSettings.OmitXmlDeclaration = true;
                    xmlWriterSettings.Indent = true;

                    using (XmlWriter xmlWriter = XmlWriter.Create(FilePathMap.UsersRolesAndGrantsWebReportFilePath(), xmlWriterSettings))
                    {
                        xmlWriter.WriteDocType("html", null, null, null);
                        
                        xmlWriter.WriteStartElement("html");

                        xmlWriter.WriteStartElement("head");
                        xmlWriter.WriteStartElement("title");
                        xmlWriter.WriteString(String.Format("Snowflake Grants Report {0} {1} roles", programOptions.ReportJob.Connection, rolesList.Count));
                        xmlWriter.WriteEndElement(); // </title>
                        xmlWriter.WriteEndElement(); // </head>

                        xmlWriter.WriteStartElement("body");

                        xmlWriter.WriteStartElement("table");
                        xmlWriter.WriteAttributeString("border", "1");

                        // Header row
                        xmlWriter.WriteStartElement("tr");
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("Role"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("Type"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("# Parents"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("# Children"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("# Ancestry Paths"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("Online"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("SVG"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("PNG"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("th"); xmlWriter.WriteString("PDF"); xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement(); // </tr>
                        
                        foreach (Role role in rolesList)
                        {
                            xmlWriter.WriteStartElement("tr");
                            xmlWriter.WriteStartElement("td"); xmlWriter.WriteString(role.Name); xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("td"); xmlWriter.WriteString(role.Type.ToString()); xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("td"); xmlWriter.WriteString(role.NumParentRoles.ToString()); xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("td"); xmlWriter.WriteString(role.NumChildRoles.ToString()); xmlWriter.WriteEndElement();
                            xmlWriter.WriteStartElement("td"); xmlWriter.WriteString(role.NumAncestryPaths.ToString()); xmlWriter.WriteEndElement();

                            string graphText = FileIOHelper.ReadFileFromPath(FilePathMap.Report_GraphViz_RoleAndItsRelationsGrants_FilePath(role.Name));

                            xmlWriter.WriteStartElement("td"); 
                            
                            // https://edotor.net
                            xmlWriter.WriteStartElement("a"); 
                            xmlWriter.WriteAttributeString("href", String.Format("https://edotor.net/?#{0}", Uri.EscapeDataString(graphText)));
                            xmlWriter.WriteString("Online");
                            xmlWriter.WriteEndElement(); // </a>

                            // // http://magjac.com/graphviz-visual-editor
                            // xmlWriter.WriteStartElement("a"); 
                            // xmlWriter.WriteAttributeString("href", String.Format("http://magjac.com/graphviz-visual-editor/?dot={0}", Uri.EscapeDataString(graphText)));
                            // xmlWriter.WriteString("Opt2");
                            // xmlWriter.WriteEndElement(); // </a>

                            // // https://stamm-wilbrandt.de/GraphvizFiddle/2.1.2/index.html
                            // xmlWriter.WriteStartElement("a"); 
                            // xmlWriter.WriteAttributeString("href", String.Format("https://stamm-wilbrandt.de/GraphvizFiddle/2.1.2/index.html?#{0}", Uri.EscapeDataString(graphText)));
                            // xmlWriter.WriteString("Opt3");
                            // xmlWriter.WriteEndElement(); // </a>

                            // // https://dreampuf.github.io/GraphvizOnline
                            // xmlWriter.WriteStartElement("a"); 
                            // xmlWriter.WriteAttributeString("href", String.Format("https://dreampuf.github.io/GraphvizOnline/#{0}", Uri.EscapeDataString(graphText)));
                            // xmlWriter.WriteString("Opt4");
                            // xmlWriter.WriteEndElement(); // </a>

                            xmlWriter.WriteEndElement(); // </td>

                            xmlWriter.WriteStartElement("td"); 
                            xmlWriter.WriteStartElement("a"); 
                            xmlWriter.WriteAttributeString("href", FilePathMap.Report_Diagram_SVG_RoleAndItsRelationsGrants_FilePath(role.Name, false));
                            xmlWriter.WriteString("SVG");
                            xmlWriter.WriteEndElement(); // </a>
                            xmlWriter.WriteEndElement(); // </td>

                            xmlWriter.WriteStartElement("td"); 
                            xmlWriter.WriteStartElement("a"); 
                            xmlWriter.WriteAttributeString("href", FilePathMap.Report_Diagram_PNG_RoleAndItsRelationsGrants_FilePath(role.Name, false));
                            xmlWriter.WriteString("PNG");
                            xmlWriter.WriteEndElement(); // </a>
                            xmlWriter.WriteEndElement(); // </td>

                            xmlWriter.WriteStartElement("td"); 
                            xmlWriter.WriteStartElement("a"); 
                            xmlWriter.WriteAttributeString("href", FilePathMap.Report_Diagram_PDF_RoleAndItsRelationsGrants_FilePath(role.Name, false));
                            xmlWriter.WriteString("PDF");
                            xmlWriter.WriteEndElement(); // </a>
                            xmlWriter.WriteEndElement(); // </td>

                            xmlWriter.WriteEndElement(); // </tr>
                        }
                        xmlWriter.WriteEndElement(); // </table>

                        xmlWriter.WriteEndElement(); // </body>
                        xmlWriter.WriteEndElement(); // </html>
                    }

                    #endregion

                    #region Make SVG, PNG and PDF Files with GraphViz binaries

                    loggerConsole.Info("Making picture files for {0} roles", rolesList.Count);

                    GraphVizDriver graphVizDriver = new GraphVizDriver();
                    graphVizDriver.ValidateToolInstalled(programOptions);

                    if (graphVizDriver.ExecutableFilePath.Length > 0)
                    {
                        j = 0;

                        Parallel.ForEach<Role, int>(
                            rolesList,
                            parallelOptions,
                            () => 0,
                            (role, loop, subtotal) =>
                            {
                                loggerConsole.Info("Rendering graphs for {0}", role);  

                                graphVizDriver.ConvertGraphVizToFile(
                                    FilePathMap.Report_GraphViz_RoleAndItsRelationsGrants_FilePath(role.Name),
                                    FilePathMap.Report_Diagram_SVG_RoleAndItsRelationsGrants_FilePath(role.Name, true), 
                                    "svg");
                                graphVizDriver.ConvertGraphVizToFile(
                                    FilePathMap.Report_GraphViz_RoleAndItsRelationsGrants_FilePath(role.Name),
                                    FilePathMap.Report_Diagram_PNG_RoleAndItsRelationsGrants_FilePath(role.Name, true), 
                                    "png");
                                graphVizDriver.ConvertGraphVizToFile(
                                    FilePathMap.Report_GraphViz_RoleAndItsRelationsGrants_FilePath(role.Name),
                                    FilePathMap.Report_Diagram_PDF_RoleAndItsRelationsGrants_FilePath(role.Name, true), 
                                    "pdf");                                

                                return 1;
                            },
                            (finalResult) =>
                            {
                                Interlocked.Add(ref j, finalResult);
                                if (j % 10 == 0)
                                {
                                    Console.Write("[{0}].", j);
                                }
                            }
                        );
                        loggerConsole.Info("Completed {0} Roles", rolesList.Count);
                    }

                    #endregion
                }
                
                return true;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                loggerConsole.Error(ex);

                return false;
            }
            finally
            {
                stopWatch.Stop();

                this.DisplayJobStepEndedStatus(programOptions, stopWatch);

                stepTimingFunction.EndTime = DateTime.Now;
                stepTimingFunction.Duration = stopWatch.Elapsed;
                stepTimingFunction.DurationMS = stopWatch.ElapsedMilliseconds;

                List<StepTiming> stepTimings = new List<StepTiming>(1);
                stepTimings.Add(stepTimingFunction);
                FileIOHelper.WriteListToCSVFile(stepTimings, new StepTimingReportMap(), FilePathMap.StepTimingReportFilePath(), true);
            }
        }