public void CreateDumpFile()
        {            
            try
            {
                System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument();
                System.Xml.Linq.XElement xel = new System.Xml.Linq.XElement("DumpList");

                foreach (var item in EquipmentManagerInstance.EquipmentList)
                {
                    var list = new List<object>();
                    var xml = Utility.UtilityClass.ObjectToXml(item.Value);
                    if (xml != null)
                    {
                        var equipXml = new System.Xml.Linq.XElement("Equipment");
                        var name = new System.Xml.Linq.XElement("Name");
                        name.Value = item.Key;

                        var value = new System.Xml.Linq.XElement("Value");
                        value.Add(xml);

                        equipXml.Add(name);
                        equipXml.Add(value);

                        xel.Add(equipXml);
                    }
                }

                doc.Add(xel);

                string filename = DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + ".xml";
                string path = System.IO.Path.Combine(ConfigClasses.GlobalConst.ROOT_PATH, "DumpFile");
                if (System.IO.Directory.Exists(path) == false)
                    System.IO.Directory.CreateDirectory(path);

                string pathAndFilename = System.IO.Path.Combine(path, filename);

                doc.Save(pathAndFilename);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.ToString());
            }
        }
        public void UpdateConductorTest()
        {
            Conductor testConductor = Conductor.GetConductorByID(-1);
            if (testConductor.IsNew)
            {
                testConductor.ConductorID = -1;
            }
            testConductor.ConductorFirstName = "Adage";
            testConductor.ConductorLastName = "Tech";
            BsoArchiveEntities.Current.Save();

            var conductorID = Helper.CreateXElement(Constants.Conductor.conductorIDElement, "-1");
            var conductorFirstName = Helper.CreateXElement(Constants.Conductor.conductorFirstNameElement, "Test");
            var conductorItem = new System.Xml.Linq.XElement(Constants.Conductor.conductorElement, conductorID, conductorFirstName);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, conductorItem);
            var doc = new System.Xml.Linq.XDocument(eventItem);

            Conductor conductor = Conductor.NewConductor();
            conductor.UpdateData(doc, "ConductorFirstName", "eventConductorFirstname");
            Assert.IsTrue(testConductor.ConductorFirstName == "Test");

            BsoArchiveEntities.Current.DeleteObject(testConductor);
            BsoArchiveEntities.Current.DeleteObject(conductor);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateWorkArtistTest()
        {
            WorkArtist testArtist = WorkArtist.GetWorkArtistByID(-1, -1);
            if (testArtist.IsNew)
            {
                testArtist.ArtistID = -1;
                testArtist.WorkID = -1;
            }

            testArtist.Artist.ArtistFirstName = "Adage";
            BsoArchiveEntities.Current.Save();

            WorkArtist testWorkArtist = new WorkArtist();
            var workArtistId = Helper.CreateXElement(Constants.WorkArtist.workArtistIDElement, "-1");
            var workArtistFirstName = Helper.CreateXElement(Constants.WorkArtist.workArtistFirstNameElement, "Test");
            var workArtistItem = new System.Xml.Linq.XElement(Constants.WorkArtist.workArtistElement, workArtistId, workArtistFirstName);
            var workID = new System.Xml.Linq.XElement(Constants.Work.workIDElement, "-1");
            var workGroupID = new System.Xml.Linq.XElement(Constants.Work.workGroupIDElement, "-1");
            var workItem = new System.Xml.Linq.XElement(Constants.Work.workElement, workID, workGroupID, workArtistItem);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, workItem);

            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(eventItem);

            testWorkArtist.UpdateData(doc, "WorkArtistFirstName", "workArtistFirstname");

            Assert.IsTrue(testArtist.Artist.ArtistFirstName == "Test");
            BsoArchiveEntities.Current.DeleteObject(testWorkArtist);
            BsoArchiveEntities.Current.DeleteObject(testArtist);
            BsoArchiveEntities.Current.DeleteObject(Work.GetWorkByID(-1));
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateVenueTest()
        {
            Venue testVenue = Venue.GetVenueByID(-1);

            if (testVenue.IsNew)
            {
                testVenue.VenueID = -1;
            }
            testVenue.VenueName = "Adage";
            BsoArchiveEntities.Current.Save();

            var venueID = Helper.CreateXElement(Constants.Venue.venueIDElement, "-1");
            var venueName = Helper.CreateXElement(Constants.Venue.venueNameElement, "Test");
            var venueItem = new System.Xml.Linq.XElement(Constants.Venue.venueElement, venueID, venueName);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, venueItem);
            var doc = new System.Xml.Linq.XDocument(eventItem);

            Venue typeVenue = Venue.NewVenue();

            typeVenue.UpdateData(doc, "VenueName", Constants.Venue.venueNameElement);

            Assert.IsTrue(testVenue.VenueName == "Test");
            BsoArchiveEntities.Current.DeleteObject(testVenue);
            BsoArchiveEntities.Current.DeleteObject(typeVenue);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateArtistTest()
        {
            Artist testArtist = Artist.GetArtistByID(-1);
            if (testArtist.IsNew)
            {
                testArtist.ArtistID = -1;
            }
            testArtist.ArtistFirstName = "Adage";
            testArtist.ArtistLastName = "Tech";
            BsoArchiveEntities.Current.Save();

            var artistId = Helper.CreateXElement(Constants.Artist.artistIDElement, "-1");
            var artistFirstName = Helper.CreateXElement(Constants.Artist.artistFirstNameElement, "Test");
            var artistItem = new System.Xml.Linq.XElement("eventArtistItem", artistId, artistFirstName);
            var eventItem = new System.Xml.Linq.XElement("eventItem", artistItem);

            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(new System.Xml.Linq.XElement(eventItem));

            Artist artist = Artist.NewArtist();
            artist.UpdateData(doc, "ArtistFirstName", "eventArtistFirstname");

            Assert.IsTrue(testArtist.ArtistFirstName == "Test");
            BsoArchiveEntities.Current.DeleteObject(artist);
            BsoArchiveEntities.Current.DeleteObject(testArtist);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateTypeTest()
        {
            Bso.Archive.BusObj.EventType testType = Bso.Archive.BusObj.EventType.GetEventTypeByID(-1);
            if (testType.IsNew)
            {
                testType.TypeID = -1;
            }
            testType.TypeName = "Adage";
            BsoArchiveEntities.Current.Save();

            var typeID = Helper.CreateXElement(Constants.EventType.typeIDElement, "-1");
            var typeName2 = Helper.CreateXElement(Constants.EventType.typeName2Element, "Test");

            var typeItem = new System.Xml.Linq.XElement(Constants.EventType.typeElement, typeID, typeName2);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, typeItem);
            var doc = new System.Xml.Linq.XDocument(eventItem);

            Bso.Archive.BusObj.EventType typeGroup = Bso.Archive.BusObj.EventType.NewEventType();

            typeGroup.UpdateData(doc, "TypeName2", "eventTypeName2");
            Assert.IsTrue(testType.TypeName2 == "Test");

            BsoArchiveEntities.Current.DeleteObject(testType);
            BsoArchiveEntities.Current.DeleteObject(typeGroup);
            BsoArchiveEntities.Current.Save();
        }
示例#7
0
 public static void SaveBlogConnectionInfo(MP.BlogConnectionInfo coninfo, string filename)
 {
     var doc = new System.Xml.Linq.XDocument();
     var p = new System.Xml.Linq.XElement("blogconnectioninfo");
     doc.Add(p);
     p.Add(new System.Xml.Linq.XElement("blogurl", coninfo.BlogUrl));
     p.Add(new System.Xml.Linq.XElement("blogid", coninfo.BlogId));
     p.Add(new System.Xml.Linq.XElement("metaweblog_url", coninfo.MetaWeblogUrl));
     p.Add(new System.Xml.Linq.XElement("username", coninfo.Username));
     p.Add(new System.Xml.Linq.XElement("password", coninfo.Password));
     doc.Save(filename);
 }
示例#8
0
 private void refreshreport()
 {
     var rep = this.reportViewer1.ServerReport;
     var exec_header = new SSRSCommon.ReportExecutionService.ExecutionHeader();
     rep_exec_svc.ExecutionHeaderValue = exec_header;
     string historyid = null;
     var reportserver_url =  new System.Uri(this.textBoxReportServer.Text);
     var report = this.reportViewer1.ServerReport;
     report.ReportServerUrl = reportserver_url;
     report.ReportPath = this.GetFullReportPath();
     this.ReportXML = SSRSCommon.RSUtil.GetRDLXML(rep_svc, rep);
     this.reportViewer1.RefreshReport();
 }
示例#9
0
        public void WriteInFile(String filename)
        {
            try
            {
                System.Xml.Linq.XDocument xDoc = new System.Xml.Linq.XDocument(new System.Xml.Linq.XDeclaration("1.0", "UTF-16", null), xelement);

                System.IO.StringWriter sw = new System.IO.StringWriter();
                System.Xml.XmlWriter xWrite = System.Xml.XmlWriter.Create(sw);
                xDoc.Save(xWrite);
                xWrite.Close();
                xDoc.Save(filename);
            }
            catch { }
        }
示例#10
0
        public PlayerAnimation(ContentManager Content, SpriteBatch Sprite, string CharacterName)
        {
            sprite = Sprite;
            content = Content;

            spriteSheetData = System.Xml.Linq.XDocument.Load("Content/Animations/Player/" + CharacterName + ".xml");
            playerTex = content.Load<Texture2D>(@"Animations/Player/" + CharacterName + "Sheet");

            var idle = spriteSheetData.Root.Element("idle");

            frameSizeIdle = new Point();
            frameSizeIdle.X = int.Parse(idle.Attribute("FrameWidth").Value, NumberStyles.Integer);
            frameSizeIdle.Y = int.Parse(idle.Attribute("FrameHeight").Value, NumberStyles.Integer);
        }
示例#11
0
        public System.Xml.Linq.XDocument CreateDocument()
        {
            var doc = new System.Xml.Linq.XDocument();
            var root = new System.Xml.Linq.XElement("methodResponse");

            doc.Add(root);

            var f = new System.Xml.Linq.XElement("fault");

            root.Add(f);

            var struct_ = new XmlRpc.Struct();
            struct_["faultCode"] = new XmlRpc.IntegerValue(this.FaultCode);
            struct_["faultString"] = new XmlRpc.StringValue(this.FaultString);
            struct_.AddXmlElement(f);

            return doc;
        }
示例#12
0
        public FormRDLViewer(System.Xml.Linq.XDocument rdlxml)
        {
            InitializeComponent();

            this.xml = rdlxml;
            this.RDLText = xml.ToString();


            var md = SSRSCommon.RDLMetaData.Load(this.RDLXML);

            this.labelXmlNamespace.Text = md.Namespace.ToString();

            this.labelPageSettings.Text = string.Format("{0} x {1} ( {2}, {3}, {4}, {5} )", md.PageSize.Width,
                                                        md.PageSize.Height, md.MarginTop, md.MarginBottom, md.MarginLeft,
                                                        md.MarginRight);


        }
示例#13
0
        public System.Xml.Linq.XDocument ToXML()
        {
            var dom = new System.Xml.Linq.XDocument();
            var devinfo_el = new System.Xml.Linq.XElement("DeviceInfo");
            dom.Add(devinfo_el);


            this.WriteStringSafe(devinfo_el, "OutputFormat", this.OutputFormat);

            devinfo_el.SetElementValue("Toolbar", this.Capitalize(this.Toolbar.ToString()));

            this.WriteStringSafe(devinfo_el, "PageWidth", this.PageWidth);
            this.WriteStringSafe(devinfo_el, "PageHeight", this.PageHeight);
            this.WriteStringSafe(devinfo_el, "MarginTop", this.MarginTop);
            this.WriteStringSafe(devinfo_el, "MarginBottom", this.MarginBottom);
            this.WriteStringSafe(devinfo_el, "MarginLeft", this.MarginLeft);
            this.WriteStringSafe(devinfo_el, "MarginRight", this.MarginRight);

            if (this.PrintDpiX.HasValue)
            {
                devinfo_el.SetElementValue("PrintDpiX", this.PrintDpiX.ToString());
            }
            if (this.PrintDpiY.HasValue)
            {
                devinfo_el.SetElementValue("PrintDpiY", this.PrintDpiY.ToString());
            }
            if (this.DpiX.HasValue)
            {
                devinfo_el.SetElementValue("DpiX", this.DpiX.ToString());
            }
            if (this.DpiY.HasValue)
            {
                devinfo_el.SetElementValue("DpiY", this.DpiY.ToString());
            }


            return dom;
        }
        public void UpdateParticipantTest()
        {
            Participant testParticipant = Participant.GetParticipantByID(-1);
            if (testParticipant.IsNew)
            {
                testParticipant.ParticipantID = -1;
            }
            testParticipant.ParticipantFirstName = "Adage";
            BsoArchiveEntities.Current.Save();

            var participantID = Helper.CreateXElement(Constants.Participant.participantIDElement, "-1");
            var participantFirstName = Helper.CreateXElement(Constants.Participant.participantFirstNameElement, "Test");
            var participantItem = new System.Xml.Linq.XElement(Constants.Participant.participantElement, participantID, participantFirstName);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, participantItem);
            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(eventItem);

            Participant participant = Participant.NewParticipant();
            participant.UpdateData(doc, "ParticipantFirstName", Constants.Participant.participantFirstNameElement);
            Assert.IsTrue(testParticipant.ParticipantFirstName == "Test");
            BsoArchiveEntities.Current.DeleteObject(testParticipant);
            BsoArchiveEntities.Current.DeleteObject(participant);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateSeasonTest()
        {
            Season testSeason = Season.GetSeasonByID(-1);
            if (testSeason.IsNew)
            {
                testSeason.SeasonID = -1;
            }
            testSeason.SeasonCode = "Adage";
            BsoArchiveEntities.Current.Save();

            var seasonID = Helper.CreateXElement(Constants.Season.seasonIDElement, "-1");
            var seasonCode = Helper.CreateXElement(Constants.Season.seasonCodeElement, "Test");
            var seasonItem = new System.Xml.Linq.XElement(Constants.Season.seasonElement, seasonID, seasonCode);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, seasonItem);
            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(eventItem);

            Season season = Season.NewSeason();
            season.UpdateData(doc, "SeasonCode", "eventSeasonCode");
            Assert.IsTrue(testSeason.SeasonCode == "Test");
            BsoArchiveEntities.Current.DeleteObject(testSeason);
            BsoArchiveEntities.Current.DeleteObject(season);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateTypeGroupTest()
        {
            EventTypeGroup testTypeGroup = EventTypeGroup.GetTypeGroupByID(-1);
            if (testTypeGroup.IsNew)
            {
                testTypeGroup.TypeGroupID = -1;
            }
            testTypeGroup.EventTypeGroupName = "Adage";
            BsoArchiveEntities.Current.Save();

            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(
            new System.Xml.Linq.XElement(new System.Xml.Linq.XElement("eventItem", new System.Xml.Linq.XElement("eventTypeGroup",
                new System.Xml.Linq.XElement("eventTypeGroupID", -1),
                new System.Xml.Linq.XElement("eventTypeGroupName", "Test")
                ))));

            EventTypeGroup typeGroup = EventTypeGroup.NewEventTypeGroup();
            typeGroup.UpdateData(doc, "EventTypeGroupName", "eventTypeGroupName");

            Assert.IsTrue(testTypeGroup.EventTypeGroupName == "Test");
            BsoArchiveEntities.Current.DeleteObject(testTypeGroup);
            BsoArchiveEntities.Current.DeleteObject(typeGroup);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateOrchestraTest()
        {
            Orchestra testOrchestra = Orchestra.GetOrchestraByID(-1);
            if (testOrchestra.IsNew)
            {
                testOrchestra.OrchestraID = -1;
            }
            testOrchestra.OrchestraName = "Adage";
            BsoArchiveEntities.Current.Save();

            var orchestraID = Helper.CreateXElement(Constants.Orchestra.orchestraIDElement, "-1");
            var orchestraNotes = Helper.CreateXElement(Constants.Orchestra.orchestraNotesElement, "Test");
            var orchestraItem = new System.Xml.Linq.XElement(Constants.Orchestra.orchestraElement, orchestraID, orchestraNotes);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, orchestraItem);
            var doc = new System.Xml.Linq.XDocument(eventItem);

            Orchestra orchestra = Orchestra.NewOrchestra();
            orchestra.UpdateData(doc, "OrchestraNote", "eventOrchestraNotes");
            Assert.IsTrue(testOrchestra.OrchestraNote == "Test");

            BsoArchiveEntities.Current.DeleteObject(testOrchestra);
            BsoArchiveEntities.Current.DeleteObject(orchestra);
            BsoArchiveEntities.Current.Save();
        }
        public void UpdateProjectTest()
        {
            Project testProject = Project.GetProjectByID(-1);
            if (testProject.IsNew)
            {
                testProject.ProjectID = -1;
            }
            testProject.ProjectName2 = "Adage";
            BsoArchiveEntities.Current.Save();

            var projectID = Helper.CreateXElement(Constants.Project.projectIDElement, "-1");
            var projectName2 = Helper.CreateXElement(Constants.Project.projectName2Element, "Test");
            var projectItem = new System.Xml.Linq.XElement(Constants.Project.projectElement, projectName2, projectID);
            var eventItem = new System.Xml.Linq.XElement(Constants.Event.eventElement, projectItem);
            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(eventItem);

            Project project = Project.NewProject();
            project.UpdateData(doc, "ProjectName2", "eventProjectName2");
            Assert.IsTrue(testProject.ProjectName2 == "Test");

            BsoArchiveEntities.Current.DeleteObject(testProject);
            BsoArchiveEntities.Current.DeleteObject(project);
            BsoArchiveEntities.Current.Save();
        }
示例#19
0
        /// <summary>
        /// uninitialize the nps global instance
        /// </summary>
        public void UnInit()
        {
            m_IsInitialized = false;

            Util.SaveConfigSettings();
            UnwireEditEvents(m_Editor);

            m_DLLPath = null;
            m_Map = null;
            m_XMLConfig = null;
            m_XMLConfigFilePath = null;
            m_Workspace = null;
            m_DatabasePath = null;
            m_DLLPath = null;
            m_Editor = null;
            m_ProgramaticFeatureEdit = false;
            m_InitErrorMessage = null;

            m_LYR_HORIZON = m_LYR_ANIMALS = m_LYR_TRACKLOG
                = m_LYR_GPSPOINTLOG = m_LYR_RANDOMPOINTS
                = m_LYR_GENERATED_TRANSECTS = m_LYR_FLAT_AREAS
                = m_LYR_EXCLUDED_AREAS = m_LYR_SURVEY_BOUNDARY = null;
        }
示例#20
0
        public void UpdateWorkTest()
        {
            Work testWork = Work.GetWorkByID(-1);
            if (testWork.IsNew)
            {
                testWork.WorkID = -1;
            }
            testWork.WorkTitle = "Adage";
            BsoArchiveEntities.Current.Save();

            var workId = Helper.CreateXElement(Constants.Work.workIDElement, "-1");
            var workGroupID = new System.Xml.Linq.XElement(Constants.Work.workTitleElement, "Test");
            var workItem = new System.Xml.Linq.XElement(Constants.Work.workElement, workId, workGroupID);
            var eventElement = new System.Xml.Linq.XElement(Constants.Event.eventElement, workItem);

            System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument(eventElement);
            Work work = Work.NewWork();
            work.UpdateData(doc, "WorkTitle", Constants.Work.workTitleElement);

            Assert.IsTrue(testWork.WorkTitle == "Test");
            BsoArchiveEntities.Current.DeleteObject(testWork);
            BsoArchiveEntities.Current.DeleteObject(work);
            BsoArchiveEntities.Current.Save();
        }
示例#21
0
 /// <summary>
 /// find and load the xml configuration file and set the globals that
 /// need to be set from the contents of the file
 /// </summary>
 private void InitXMLConfig(string DLLPath, ref string ErrorMessage)
 {
     try
     {
         m_XMLConfigFilePath = System.IO.Path.Combine(DLLPath, "NPSConfig.xml");
         m_XMLConfig = System.Xml.Linq.XDocument.Load(m_XMLConfigFilePath);
     }
     catch (Exception ex)
     {
         ErrorMessage = "Error occured while parsing XML configuration file. " + ex.Message;
         return;
     }
 }
示例#22
0
 static partial void CustomizeMappingDocument(System.Xml.Linq.XDocument mappingDocument);
示例#23
0
 public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler?validationEventHandler, bool addSchemaInfo)
 {
 }
示例#24
0
        public void UpdateEventTest()
        {
            Event testEvent = Event.GetEventByID(-1);
            if (testEvent.IsNew)
            {
                testEvent.EventID = -1;
            }
            testEvent.EventDate = DateTime.Now;
            testEvent.EventText = "Adage";
            BsoArchiveEntities.Current.Save();

            var eventID = Helper.CreateXElement(Constants.Event.eventIDElement, "-1");
            var eventText = Helper.CreateXElement(Constants.Event.eventTextElement, "Test");
            var eventElement = new System.Xml.Linq.XElement(Constants.Event.eventElement, eventID, eventText);
            var rootElement = new System.Xml.Linq.XElement("Root", eventElement);
            var doc = new System.Xml.Linq.XDocument(rootElement);

            Event eventItem = Event.NewEvent();
            eventItem.UpdateData(doc, "EventText", "eventText");

            Assert.IsTrue(testEvent.EventText == "Test");
            BsoArchiveEntities.Current.DeleteObject(testEvent);
            BsoArchiveEntities.Current.DeleteObject(eventItem);
            BsoArchiveEntities.Current.Save();
        }
 public string GetDestinationMachineName(System.Xml.Linq.XDocument checkRun)
 {
     return(DataAccessors.GetCheckRunValue(checkRun, DataStringConstants.NameAttributeValues.DestinationMachine));
 }
示例#26
0
 public IXDocument Load(string uri)
 {
     XDoc = System.Xml.Linq.XDocument.Load(uri);
     return(this);
 }
示例#27
0
 public ResponseData(ResponseCode code, System.Xml.Linq.XDocument result, Exception error)
     : this(code, result)
 {
     this.Error = error;
 }
示例#28
0
        bool ProcessSVG(string Name, Stream InputStream)
        {
            MemoryStream ms = new MemoryStream();

            InputStream.CopyTo(ms);
            byte[] data = ms.ToArray();

            MemoryStream ms1 = new MemoryStream(data);
            MemoryStream ms2 = new MemoryStream(data);

            var xdoc = new System.Xml.Linq.XDocument();

            xdoc = System.Xml.Linq.XDocument.Load(ms1);
            var temp = xdoc.Descendants();

            foreach (var t in temp)
            {
                switch (t.Name.LocalName.ToString())
                {
                case "g":
                    //Get and apply global transform
                    var gtransform = t.Attribute("transform");
                    if (gtransform != null)
                    {
                        GlobalTransform = SVGPath.BuildTransformMatrix(gtransform.Value);
                    }
                    else
                    {
                        GlobalTransform = SKMatrix.MakeIdentity();
                    }


                    Curves.Add(new Polycurve(Name));
                    break;

                case "path":
                    //Get and apply local transformation
                    var ptransform = t.Attribute("transform");
                    if (ptransform != null)
                    {
                        LocalTransform = SVGPath.BuildTransformMatrix(ptransform.Value);
                    }
                    else
                    {
                        LocalTransform = SKMatrix.MakeIdentity();
                    }

                    var attribute = t.Attribute("d");
                    if (attribute != null)
                    {
                        ParsePath(Name, attribute.Value, _CTM);
                    }

                    break;

                default:
                    break;
                }
            }

            //Use SKSVG to get viewbox
            SKSvg Imag = new SKSvg();

            Imag.Load(ms2);

            LastCurve.CanvasSize = Imag.ViewBox.Size;
            LastCurve.Update();

            mImageFunction(Name, LastCurve);

            ms1.Dispose();
            ms2.Dispose();
            ms1  = null;
            ms2  = null;
            Imag = null;

            return(true);
        }
示例#29
0
 public ResponseData(ResponseCode code, System.Xml.Linq.XDocument result)
 {
     Code   = code;
     Result = result;
 }
示例#30
0
        /// <summary>
        /// 加载配置文件。
        /// </summary>
        /// <param name="fileName">文件名。</param>
        /// <returns>包含所指定文件内容的配置文件。</returns>
        public static ConfigurationDocument LoadFrom(string fileName)
        {
            // 创建文件对象。
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
            // 如果文件不存在,则返回空的配置文件对象。
            if (!fileInfo.Exists)
            {
                return(new ConfigurationDocument());
            }
            // 从文件中加载Xml文档对象。
            System.Xml.Linq.XDocument xDocument = System.Xml.Linq.XDocument.Load(fileInfo.FullName);
            // 如果Xml文档的根节点名称不是默认的根节点名称,则返回空的配置文件对象。
            if (xDocument.Root.Name.LocalName != XmlRootName)
            {
                return(new ConfigurationDocument());
            }
            // 创建配置文件对象。
            ConfigurationDocument document = new ConfigurationDocument();

            // 遍历Xml文档根节点下的Xml组节点。
            foreach (System.Xml.Linq.XElement xGroup in xDocument.Root.Elements())
            {
                // 如果Xml组节点的名称是默认的组节点的名称,则继续。
                if (xGroup.Name.LocalName == XmlGroupNodeName)
                {
                    // 获取Xml组节点的key属性。
                    System.Xml.Linq.XAttribute xGroupKeyAttribute = xGroup.Attribute(XmlKeyAttributeName);
                    // 如果key属性不为空且属性值不为空,则继续。
                    if (xGroupKeyAttribute != null)
                    {
                        // 根据xml组节点的key属性值创建并添加配置组对象。
                        ConfigurationGroup configurationGroup = document.GetOrAdd(xGroupKeyAttribute.Value);
                        // 遍历Xml组节点下的Xml项节点。
                        foreach (System.Xml.Linq.XElement xItem in xGroup.Elements())
                        {
                            // 如果Xml项节点的名称是默认的项节点名称,则继续。
                            if (xItem.Name.LocalName == XmlItemNodeName)
                            {
                                // 获取Xml项节点的key属性、value属性、encrypted属性。
                                System.Xml.Linq.XAttribute xItemKeyAttribute       = xItem.Attribute(XmlKeyAttributeName);
                                System.Xml.Linq.XAttribute xItemValueAttribute     = xItem.Attribute(XmlValueAttributeName);
                                System.Xml.Linq.XAttribute xItemEncryptedAttribute = xItem.Attribute(XmlEncryptedAttributeName);
                                // 如果key属性不为空,且key属性值不为空
                                if (xItemKeyAttribute != null)
                                {
                                    // 创建配置项。
                                    ConfigurationItem configurationItem = configurationGroup.GetOrAdd(xItemKeyAttribute.Value);
                                    // 如果value属性不为空,则赋值给配置项。
                                    if (xItemValueAttribute != null)
                                    {
                                        configurationItem.Value = xItemValueAttribute.Value;
                                    }
                                    // 如果encrypted属性不为空,且encrypted属性值不为空,则解密配置项的值。
                                    if (xItemEncryptedAttribute != null && !string.IsNullOrWhiteSpace(xItemEncryptedAttribute.Value))
                                    {
                                        // 如果encrypted属性可以转换成bool类型的值。
                                        if (bool.TryParse(xItemEncryptedAttribute.Value, out bool encrypted))
                                        {
                                            // 赋值配置项的加密属性。
                                            configurationItem.Encrypted = encrypted;
                                            // 根据配置项的加密属性值来解密配置项的值。
                                            if (encrypted)
                                            {
                                                if (Studio.Security.DESManager.TryDecrypt(configurationItem.Value, out string value))
                                                {
                                                    configurationItem.Value = value;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(document);
        }
示例#31
0
 private void RemoveFromXml(string pathToRemove)
 {
     System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("XmlData.xml");
     xdoc.Root.Elements("imageLink").Select(el => el).Where(el => el.Value == pathToRemove).ToList().ForEach(el => el.Remove());
     xdoc.Save("XmlData.xml");
 }
示例#32
0
        private void UpdatePrimaryTile()
        {
            System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("tiles.xml");

            var updator = TileUpdateManager.CreateTileUpdaterForApplication();

            updator.EnableNotificationQueueForSquare150x150(true);
            updator.EnableNotificationQueueForSquare310x310(true);
            updator.EnableNotificationQueueForWide310x150(true);
            updator.EnableNotificationQueue(true);
            updator.Clear();
            var n     = helpItemViewModel.HelpItemSize();
            var index = 0;

            if (n >= 5)
            {
                index = n - 5;
            }
            else
            {
                index = 0;
            }
            for (var i = n - 1; i >= index; i--)
            {
                XmlDocument tilexml = new XmlDocument();
                tilexml.LoadXml(xdoc.ToString());
                XmlNodeList titles = tilexml.GetElementsByTagName("text");
                titles[0].InnerText = helpItemViewModel.AllItems[i].type;
                titles[1].InnerText = helpItemViewModel.AllItems[i].type;
                titles[3].InnerText = helpItemViewModel.AllItems[i].type;
                titles[6].InnerText = helpItemViewModel.AllItems[i].type;
                titles[2].InnerText = helpItemViewModel.AllItems[i].details;
                titles[4].InnerText = helpItemViewModel.AllItems[i].details;
                titles[7].InnerText = helpItemViewModel.AllItems[i].details;
                titles[5].InnerText = helpItemViewModel.AllItems[i].dateTime.ToString();
                titles[8].InnerText = helpItemViewModel.AllItems[i].dateTime.ToString();

                BitmapImage b      = new BitmapImage(new Uri("ms-appx:///Assets/ItemType/" + helpItemViewModel.AllItems[i].type + ".png"));
                var         images = tilexml.GetElementsByTagName("image");
                if (images != null)
                {
                    var image = images[0] as XmlElement; if (b != null)
                    {
                        image.SetAttribute("src", b.UriSource.ToString());
                    }
                    image = images[1] as XmlElement; if (b != null)
                    {
                        image.SetAttribute("src", b.UriSource.ToString());
                    }
                    image = images[2] as XmlElement; if (b != null)
                    {
                        image.SetAttribute("src", b.UriSource.ToString());
                    }
                    image = images[3] as XmlElement; if (b != null)
                    {
                        image.SetAttribute("src", b.UriSource.ToString());
                    }
                }
                TileNotification notification = new TileNotification(tilexml);
                updator.Update(notification);
            }
        }
        public bool IsDestinationMachineLocalInstance(System.Xml.Linq.XDocument checkRun)
        {
            string destinationMachine = DataAccessors.GetCheckRunValue(checkRun, DataStringConstants.NameAttributeValues.DestinationMachine);

            return(destinationMachine.ToUpper() == System.Net.Dns.GetHostName().ToUpper());
        }
示例#34
0
        public static ActionResult InstallPdfScribePrinter(Session session)
        {
            ActionResult printerInstalled;
            String       driverSourceDirectory  = session.CustomActionData["DriverSourceDirectory"];
            String       outputCommand          = session.CustomActionData["OutputCommand"];
            String       outputCommandArguments = session.CustomActionData["OutputCommandArguments"];
            String       CurrentDir             = session.CustomActionData["CurrentDir"];
            String       transform = session.CustomActionData["TRANSFORMS"];
            SessionLogWriterTraceListener installTraceListener = new SessionLogWriterTraceListener(session);

            installTraceListener.TraceOutputOptions = TraceOptions.DateTime;

            PdfScribeInstaller installer = new PdfScribeInstaller();

            installer.AddTraceListener(installTraceListener);


            try
            {
                System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument();
                doc = System.Xml.Linq.XDocument.Load(CurrentDir + "\\" + "config.xml");

                session.Log("Parameters Loaded:" + (doc.Root != null));
                session.Log("Parameter Count:" + doc.Descendants("Parameter").Count());
                var parameters = doc.Descendants("Parameter").ToDictionary(n => n.Attribute("Name").Value, v => v.Attribute("Value").Value);

                if (parameters.Any())
                {
                    session.Log("Parameters loaded into Dictionary Count: " + parameters.Count());

                    //Set the Wix Properties in the Session object from the XML file
                    foreach (var parameter in parameters)
                    {
                        if (parameter.Key == "PrinterName" || parameter.Key == "PortName" || parameter.Key == "HardwareId")
                        {
                            session.CustomActionData[parameter.Key] = parameter.Value;
                        }
                    }
                }
                else
                {
                    session.Log("No Parameters loaded");
                }


                string folder         = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string specificFolder = Path.Combine(folder, "PdfScribe");

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                if (transform == ":instance2")
                {
                    string printer2 = System.IO.Path.Combine(specificFolder, "scribe2");
                    System.IO.Directory.CreateDirectory(printer2);
                    doc.Save(@printer2 + "\\" + "Config.xml");
                }

                else if (transform == ":instance3")
                {
                    string printer3 = System.IO.Path.Combine(specificFolder, "scribe3");
                    System.IO.Directory.CreateDirectory(printer3);
                    doc.Save(@printer3 + "\\" + "Config.xml");
                }

                else if (transform == ":instance4")
                {
                    string printer4 = System.IO.Path.Combine(specificFolder, "scribe4");
                    System.IO.Directory.CreateDirectory(printer4);
                    doc.Save(@printer4 + "\\" + "Config.xml");
                }

                else if (transform == ":instance5")
                {
                    string printer5 = System.IO.Path.Combine(specificFolder, "scribe5");
                    System.IO.Directory.CreateDirectory(printer5);
                    doc.Save(@printer5 + "\\" + "Config.xml");
                }

                else if (transform == ":instance6")
                {
                    string printer6 = System.IO.Path.Combine(specificFolder, "scribe6");
                    System.IO.Directory.CreateDirectory(printer6);
                    doc.Save(@printer6 + "\\" + "Config.xml");
                }

                else if (transform == ":instance7")
                {
                    string printer7 = System.IO.Path.Combine(specificFolder, "scribe7");
                    System.IO.Directory.CreateDirectory(printer7);
                    doc.Save(@printer7 + "\\" + "Config.xml");
                }

                else if (transform == ":instance8")
                {
                    string printer8 = System.IO.Path.Combine(specificFolder, "scribe8");
                    System.IO.Directory.CreateDirectory(printer8);
                    doc.Save(@printer8 + "\\" + "Config.xml");
                }

                else if (transform == ":instance9")
                {
                    string printer9 = System.IO.Path.Combine(specificFolder, "scribe9");
                    System.IO.Directory.CreateDirectory(printer9);
                    doc.Save(@printer9 + "\\" + "Config.xml");
                }

                else if (transform == ":instance10")
                {
                    string printer10 = System.IO.Path.Combine(specificFolder, "scribe10");
                    System.IO.Directory.CreateDirectory(printer10);
                    doc.Save(@printer10 + "\\" + "Config.xml");
                }

                else if (transform == "" || transform == ":instance")
                {
                    string printer1 = System.IO.Path.Combine(specificFolder, "scribe");
                    System.IO.Directory.CreateDirectory(printer1);

                    doc.Save(@printer1 + "\\" + "Config.xml");
                }
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            catch (Exception ex)
            {
                session.Log("ERROR in custom action SetInstallerProperties {0}", ex.ToString());
                MessageBox.Show(ex.Message);
                return(ActionResult.Failure);
            }

            //Update Printer variables for Specific Instance
            if (installer.UpdateVal(session.CustomActionData["PrinterName"], session.CustomActionData["PortName"], session.CustomActionData["HardwareId"]))
            {
                //MessageBox.Show("Success");
                //MessageBox.Show(installer.PRINTERNAME+"POrt="+installer.PORTNAME+"HD="+installer.HARDWAREID);
            }
            else
            {
                MessageBox.Show("Failed To Update Instance Setup");
            }

            try
            {
                if (installer.InstallPdfScribePrinter(driverSourceDirectory,
                                                      outputCommand,
                                                      outputCommandArguments))
                {
                    printerInstalled = ActionResult.Success;
                }
                else
                {
                    printerInstalled = ActionResult.Failure;
                }
                installTraceListener.CloseAndWriteLog();
            }
            finally
            {
                if (installTraceListener != null)
                {
                    installTraceListener.Dispose();
                }
            }
            return(printerInstalled);
        }
        public bool IsOriginMachineLocalInstance(System.Xml.Linq.XDocument crl)
        {
            string originMachine = DataAccessors.GetCheckRunValue(crl, DataStringConstants.NameAttributeValues.OriginMachine);

            return(originMachine.ToUpper() == System.Net.Dns.GetHostName().ToUpper());
        }
        public InteractiveSeries Execute(double price, double time, InteractiveSeries smile, IOptionSeries optSer, double scaleMult, double ratePct, int barNum)
        {
            int barsCount = ContextBarsCount;

            if ((barNum < barsCount - 1) || (smile == null) || (optSer == null))
            {
                return(Constants.EmptySeries);
            }

            SmileInfo oldInfo = smile.GetTag <SmileInfo>();

            if ((oldInfo == null) ||
                (oldInfo.ContinuousFunction == null) || (oldInfo.ContinuousFunctionD1 == null))
            {
                return(Constants.EmptySeries);
            }

            int      lastBarIndex   = optSer.UnderlyingAsset.Bars.Count - 1;
            DateTime now            = optSer.UnderlyingAsset.Bars[Math.Min(barNum, lastBarIndex)].Date;
            bool     wasInitialized = HandlerInitializedToday(now);

            double futPx = price;
            double dT    = time;

            if (!DoubleUtil.IsPositive(dT))
            {
                // [{0}] Time to expiry must be positive value. dT:{1}
                string msg = RM.GetStringFormat("OptHandlerMsg.TimeMustBePositive", GetType().Name, dT);
                if (wasInitialized)
                {
                    m_context.Log(msg, MessageType.Error, true);
                }
                return(Constants.EmptySeries);
            }

            if (!DoubleUtil.IsPositive(futPx))
            {
                // [{0}] Base asset price must be positive value. F:{1}
                string msg = RM.GetStringFormat("OptHandlerMsg.FutPxMustBePositive", GetType().Name, futPx);
                if (wasInitialized)
                {
                    m_context.Log(msg, MessageType.Error, true);
                }
                return(Constants.EmptySeries);
            }

            if (!DoubleUtil.IsPositive(scaleMult))
            {
                //throw new ScriptException("Argument 'scaleMult' contains NaN for some strange reason. scaleMult:" + scaleMult);
                return(Constants.EmptySeries);
            }

            if (Double.IsNaN(ratePct))
            {
                //throw new ScriptException("Argument 'ratePct' contains NaN for some strange reason. rate:" + rate);
                return(Constants.EmptySeries);
            }

            double ivAtm, slopeAtm, shape;

            if ((!oldInfo.ContinuousFunction.TryGetValue(futPx, out ivAtm)) ||
                (!oldInfo.ContinuousFunctionD1.TryGetValue(futPx, out slopeAtm)))
            {
                return(Constants.EmptySeries);
            }

            if (m_setIvByHands)
            {
                ivAtm = m_ivAtmPct.Value / Constants.PctMult;
            }

            if (m_setSlopeByHands)
            {
                slopeAtm = m_slopePct.Value / Constants.PctMult;
                //slopeAtm = slopeAtm / F / Math.Pow(dT, Pow + shape);
            }

            //if (setShapeByHands)
            {
                shape = m_shapePct.Value / Constants.PctMult;
            }

            if (!DoubleUtil.IsPositive(ivAtm))
            {
                // [{0}] ivAtm must be positive value. ivAtm:{1}
                string msg = RM.GetStringFormat("OptHandlerMsg.IvAtmMustBePositive", GetType().Name, ivAtm);
                if (wasInitialized)
                {
                    m_context.Log(msg, MessageType.Error, true);
                }
                return(Constants.EmptySeries);
            }

            if (Double.IsNaN(slopeAtm))
            {
                // [{0}] Smile skew at the money must be some number. skewAtm:{1}
                string msg = RM.GetStringFormat("OptHandlerMsg.SkewAtmMustBeNumber", GetType().Name, slopeAtm);
                if (wasInitialized)
                {
                    m_context.Log(msg, MessageType.Error, true);
                }
                return(Constants.EmptySeries);
            }

            SmileInfo templateInfo;

            #region Fill templateInfo
            if (m_useLocalTemplate)
            {
                InteractiveSeries templateSmile = m_context.LoadObject(m_frozenSmileId) as InteractiveSeries;
                if (templateSmile == null)
                {
                    // [{0}] There is no LOCAL smile with ID:{1}
                    string msg = RM.GetStringFormat("SmileImitation5.NoLocalSmile", GetType().Name, m_frozenSmileId);
                    if (wasInitialized)
                    {
                        m_context.Log(msg, MessageType.Error, true);
                    }
                    return(Constants.EmptySeries);
                }

                SmileInfo locInfo = new SmileInfo();
                locInfo.F            = futPx;
                locInfo.dT           = dT;
                locInfo.RiskFreeRate = oldInfo.RiskFreeRate;

                List <double> locXs = new List <double>();
                List <double> locYs = new List <double>();
                foreach (InteractiveObject oldObj in templateSmile.ControlPoints)
                {
                    if (!oldObj.AnchorIsActive)
                    {
                        continue;
                    }

                    double k     = oldObj.Anchor.ValueX;
                    double sigma = oldObj.Anchor.ValueY;

                    double x = Math.Log(k / futPx) / Math.Pow(dT, DefaultPow + shape) / ivAtm;
                    double sigmaNormalized = sigma / ivAtm;

                    locXs.Add(x);
                    locYs.Add(sigmaNormalized);
                }

                try
                {
                    NotAKnotCubicSpline spline = new NotAKnotCubicSpline(locXs, locYs);

                    locInfo.ContinuousFunction   = spline;
                    locInfo.ContinuousFunctionD1 = spline.DeriveD1();

                    templateInfo = locInfo;
                }
                catch (Exception ex)
                {
                    m_context.Log(ex.ToString(), MessageType.Error, true);
                    return(Constants.EmptySeries);
                }
            }
            else
            {
                //templateSmile = context.LoadGlobalObject(globalSmileID, true) as InteractiveSeries;
                templateInfo = m_context.LoadGlobalObject(m_globalSmileId, true) as SmileInfo;
                if (templateInfo == null)
                {
                    // [{0}] There is no global templateInfo with ID:{1}. I'll try to use default one.
                    string msg = RM.GetStringFormat("SmileImitation5.TemplateWasSaved", GetType().Name, m_globalSmileId);
                    m_context.Log(msg, MessageType.Error, true);

                    System.Xml.Linq.XDocument xDoc  = System.Xml.Linq.XDocument.Parse(SmileFunction5.XmlSmileRiz4Nov1);
                    System.Xml.Linq.XElement  xInfo = xDoc.Root;
                    SmileInfo templateSmile         = SmileInfo.FromXElement(xInfo);

                    // Обновляю уровень IV ATM?
                    if (Double.IsNaN(ivAtm))
                    {
                        ivAtm = oldInfo.ContinuousFunction.Value(futPx);

                        m_context.Log(String.Format("[DEBUG:{0}] ivAtm was NaN. I'll use value ivAtm:{1}", GetType().Name, ivAtm), MessageType.Warning, true);

                        if (Double.IsNaN(ivAtm))
                        {
                            throw new Exception(String.Format("[DEBUG:{0}] ivAtm is NaN.", GetType().Name));
                        }
                    }

                    templateSmile.F            = futPx;
                    templateSmile.dT           = dT;
                    templateSmile.RiskFreeRate = oldInfo.RiskFreeRate;

                    m_context.StoreGlobalObject(m_globalSmileId, templateSmile, true);

                    // [{0}] Default templateInfo was saved to Global Cache with ID:{1}.
                    msg = RM.GetStringFormat("SmileImitation5.TemplateWasSaved", GetType().Name, m_globalSmileId);
                    m_context.Log(msg, MessageType.Warning, true);

                    templateInfo = templateSmile;
                }
            }
            #endregion Fill templateInfo

            if (!m_setIvByHands)
            {
                m_ivAtmPct.Value = ivAtm * Constants.PctMult;
            }

            if (!m_setShapeByHands)
            {
                // так я ещё не умею
            }

            if (!m_setSlopeByHands)
            {
                // Пересчитываю наклон в безразмерку
                double dSigmaDx = slopeAtm * futPx * Math.Pow(dT, DefaultPow + shape);
                m_slopePct.Value = dSigmaDx * Constants.PctMult;

                // и теперь апдейчу локальную переменную slopeAtm:
                slopeAtm = m_slopePct.Value / Constants.PctMult;
            }

            // Это функция в нормированных координатах
            // поэтому достаточно обычной симметризации
            // PROD-3111: заменяю вызов на SmileFunctionExtended
            //SimmetrizeFunc simmFunc = new SimmetrizeFunc(templateInfo.ContinuousFunction);
            //SimmetrizeFunc simmFuncD1 = new SimmetrizeFunc(templateInfo.ContinuousFunctionD1);
            //SmileFunction5 smileFunc = new SmileFunction5(simmFunc, simmFuncD1, ivAtm, slopeAtm, shape, futPx, dT);
            SmileFunctionExtended smileFunc = new SmileFunctionExtended(
                (NotAKnotCubicSpline)templateInfo.ContinuousFunction, ivAtm, slopeAtm, shape, futPx, dT);
            smileFunc.UseTails = m_useSmileTails;

            List <double>       xs    = new List <double>();
            List <double>       ys    = new List <double>();
            IOptionStrikePair[] pairs = optSer.GetStrikePairs().ToArray();

            if (pairs.Length < 2)
            {
                string msg = String.Format("[{0}] optSer must contain few strike pairs. pairs.Length:{1}", GetType().Name, pairs.Length);
                if (wasInitialized)
                {
                    m_context.Log(msg, MessageType.Warning, true);
                }
                return(Constants.EmptySeries);
            }

            double minK    = pairs[0].Strike;
            double maxK    = pairs[pairs.Length - 1].Strike;
            double futStep = optSer.UnderlyingAsset.Tick;
            double dK      = pairs[1].Strike - pairs[0].Strike;
            double width   = (SigmaMult * ivAtm * Math.Sqrt(dT)) * futPx;
            width = Math.Max(width, 10 * dK);
            // Нельзя вылезать за границу страйков???
            width = Math.Min(width, Math.Abs(futPx - minK));
            width = Math.Min(width, Math.Abs(maxK - futPx));
            // Generate left invisible tail
            if (m_generateTails)
            {
                GaussSmile.AppendLeftTail(smileFunc, xs, ys, minK, dK, false);
            }

            SortedDictionary <double, IOptionStrikePair> strikePrices;
            if (!SmileImitation5.TryPrepareImportantPoints(pairs, futPx, futStep, width, out strikePrices))
            {
                string msg = String.Format("[{0}] It looks like there is no suitable points for the smile. pairs.Length:{1}", GetType().Name, pairs.Length);
                if (wasInitialized)
                {
                    m_context.Log(msg, MessageType.Warning, true);
                }
                return(Constants.EmptySeries);
            }

            List <InteractiveObject> controlPoints = new List <InteractiveObject>();
            //for (int j = 0; j < pairs.Length; j++)
            foreach (var kvp in strikePrices)
            {
                bool showPoint = (kvp.Value != null);
                //IOptionStrikePair pair = pairs[j];
                //// Сверхдалекие страйки игнорируем
                //if ((pair.Strike < futPx - width) || (futPx + width < pair.Strike))
                //{
                //    showPoint = false;
                //}

                //double k = pair.Strike;
                double k = kvp.Key;
                double sigma;
                if (!smileFunc.TryGetValue(k, out sigma))
                {
                    continue;
                }
                double vol = sigma;

                if (!DoubleUtil.IsPositive(sigma))
                {
                    continue;
                }

                //InteractivePointActive ip = new InteractivePointActive(k, vol);
                //ip.Color = (optionPxMode == OptionPxMode.Ask) ? Colors.DarkOrange : Colors.DarkCyan;
                //ip.DragableMode = DragableMode.None;
                //ip.Geometry = Geometries.Rect; // (optionPxMode == OptionPxMode.Ask) ? Geometries.Rect : Geometries.Rect;

                // Иначе неправильно выставляются координаты???
                //ip.Tooltip = String.Format("K:{0}; IV:{1:0.00}", k, PctMult * sigma);

                InteractivePointLight ip;
                if (showPoint)
                {
                    var tip = new InteractivePointActive(k, vol);
                    if (k <= futPx) // Puts
                    {
                        SmileImitationDeribit5.FillNodeInfo(tip, futPx, dT, kvp.Value, StrikeType.Put, OptionPxMode.Mid, sigma, false, m_showNodes, scaleMult, ratePct);
                    }
                    else // Calls
                    {
                        SmileImitationDeribit5.FillNodeInfo(tip, futPx, dT, kvp.Value, StrikeType.Call, OptionPxMode.Mid, sigma, false, m_showNodes, scaleMult, ratePct);
                    }
                    ip = tip;
                }
                else
                {
                    ip = new InteractivePointLight(k, vol);
                }

                InteractiveObject obj = new InteractiveObject(ip);

                //if (showPoint)
                // Теперь мы понимаем, что точки либо рисуются
                // потому что это страйки (и тогда они автоматом InteractivePointActive)
                // либо они присутствуют, но не рисуются их узлы. Потому что они InteractivePointLight.
                {
                    controlPoints.Add(obj);
                }

                xs.Add(k);
                ys.Add(vol);
            }

            // ReSharper disable once UseObjectOrCollectionInitializer
            InteractiveSeries res = new InteractiveSeries();
            res.ControlPoints = new ReadOnlyCollection <InteractiveObject>(controlPoints);

            // Generate right invisible tail
            if (m_generateTails)
            {
                GaussSmile.AppendRightTail(smileFunc, xs, ys, maxK, dK, false);
            }

            var      baseSec    = optSer.UnderlyingAsset;
            DateTime scriptTime = baseSec.Bars[baseSec.Bars.Count - 1].Date;

            // ReSharper disable once UseObjectOrCollectionInitializer
            SmileInfo info = new SmileInfo();
            info.F            = futPx;
            info.dT           = dT;
            info.Expiry       = optSer.ExpirationDate;
            info.ScriptTime   = scriptTime;
            info.RiskFreeRate = ratePct;
            info.BaseTicker   = baseSec.Symbol;

            info.ContinuousFunction   = smileFunc;
            info.ContinuousFunctionD1 = smileFunc.DeriveD1();

            res.Tag = info;

            SetHandlerInitialized(now);

            return(res);
        }
示例#37
0
 public static void SaveSafe(this System.Xml.Linq.XDocument doc, XmlWriter writer)
 {
     doc.WriteTo(writer);
 }
示例#38
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///Gather GHA inputs
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            string osmFilePath = string.Empty;

            DA.GetData <string>("OSM Data Location", ref osmFilePath);

            //string userSRStext = "WGS84";
            //DA.GetData<string>(2, ref userSRStext);

            List <string> filterWords = new List <string>();

            DA.GetDataList <string>(2, filterWords);

            List <string> filterKeyValue = new List <string>();

            DA.GetDataList <string>(3, filterKeyValue);

            Transform xformToMetric   = new Transform(Rhino.RhinoMath.UnitScale(RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters));
            Transform xformFromMetric = new Transform(Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, RhinoDoc.ActiveDoc.ModelUnitSystem));

            ///Declare trees
            Rectangle3d recs = new Rectangle3d();
            GH_Structure <GH_String>        fieldNames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fieldValues = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> geometryGoo = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <IGH_GeometricGoo> buildingGoo = new GH_Structure <IGH_GeometricGoo>();


            Point3d max = new Point3d();
            Point3d min = new Point3d();

            if (boundary != null)
            {
                Point3d maxM = boundary.GetBoundingBox(true).Corner(true, false, true);
                max = Heron.Convert.XYZToWGS(maxM);

                Point3d minM = boundary.GetBoundingBox(true).Corner(false, true, true);
                min = Heron.Convert.XYZToWGS(minM);
            }

            /// get extents (why is this not part of OsmSharp?)
            System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load(osmFilePath);
            if (xdoc.Root.Element("bounds") != null)
            {
                double  minlat    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("minlat").Value);
                double  minlon    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("minlon").Value);
                double  maxlat    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("maxlat").Value);
                double  maxlon    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("maxlon").Value);
                Point3d boundsMin = Heron.Convert.WGSToXYZ(new Point3d(minlon, minlat, 0));
                Point3d boundsMax = Heron.Convert.WGSToXYZ(new Point3d(maxlon, maxlat, 0));

                recs = new Rectangle3d(Plane.WorldXY, boundsMin, boundsMax);
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Cannot determine the extents of the OSM file. A 'bounds' element may not be present in the file. " +
                                  "Try turning off clipping in this component's menu.");
            }


            using (var fileStreamSource = File.OpenRead(osmFilePath))
            {
                /// create a source.
                OsmSharp.Streams.XmlOsmStreamSource source = new OsmSharp.Streams.XmlOsmStreamSource(fileStreamSource);

                /// filter by bounding box
                OsmSharp.Streams.OsmStreamSource sourceClipped = source;
                if (clipped)
                {
                    sourceClipped = source.FilterBox((float)max.X, (float)max.Y, (float)min.X, (float)min.Y, true);
                }

                /// create a dictionary of elements
                OsmSharp.Db.Impl.MemorySnapshotDb sourceMem = new OsmSharp.Db.Impl.MemorySnapshotDb(sourceClipped);

                /// filter the source
                var filtered = from osmGeos in sourceClipped
                               where osmGeos.Tags != null
                               select osmGeos;

                if (filterWords.Any())
                {
                    filtered = from osmGeos in filtered
                               where osmGeos.Tags.ContainsAnyKey(filterWords)
                               select osmGeos;
                }

                if (filterKeyValue.Any())
                {
                    List <Tag> tags = new List <Tag>();
                    foreach (string term in filterKeyValue)
                    {
                        string[] kv  = term.Split(',');
                        Tag      tag = new Tag(kv[0], kv[1]);
                        tags.Add(tag);
                    }
                    filtered = from osmGeos in filtered
                               where osmGeos.Tags.Intersect(tags).Any()
                               select osmGeos;
                }

                source.Dispose();

                /// loop over all objects and count them.
                int nodes = 0, ways = 0, relations = 0;

                foreach (OsmSharp.OsmGeo osmGeo in filtered)
                {
                    //NODES
                    if (osmGeo.Type == OsmGeoType.Node)
                    {
                        OsmSharp.Node n         = (OsmSharp.Node)osmGeo;
                        GH_Path       nodesPath = new GH_Path(0, nodes);

                        //populate Fields and Values for each node
                        fieldNames.AppendRange(GetKeys(osmGeo), nodesPath);
                        fieldValues.AppendRange(GetValues(osmGeo), nodesPath);

                        //get geometry for node
                        Point3d nPoint = Heron.Convert.WGSToXYZ(new Point3d((double)n.Longitude, (double)n.Latitude, 0));
                        geometryGoo.Append(new GH_Point(nPoint), nodesPath);

                        //increment nodes
                        nodes++;
                    }

                    ////////////////////////////////////////////////////////////
                    //WAYS
                    if (osmGeo.Type == OsmGeoType.Way)
                    {
                        OsmSharp.Way w        = (OsmSharp.Way)osmGeo;
                        GH_Path      waysPath = new GH_Path(1, ways);

                        //populate Fields and Values for each way
                        fieldNames.AppendRange(GetKeys(osmGeo), waysPath);
                        fieldValues.AppendRange(GetValues(osmGeo), waysPath);

                        //get polyline geometry for way
                        List <Point3d> wayNodes = new List <Point3d>();
                        foreach (long j in w.Nodes)
                        {
                            OsmSharp.Node n = (OsmSharp.Node)sourceMem.Get(OsmGeoType.Node, j);
                            wayNodes.Add(Heron.Convert.WGSToXYZ(new Point3d((double)n.Longitude, (double)n.Latitude, 0)));
                        }

                        PolylineCurve pL = new PolylineCurve(wayNodes);
                        if (pL.IsClosed)
                        {
                            //create base surface
                            Brep[] breps = Brep.CreatePlanarBreps(pL, DocumentTolerance());
                            geometryGoo.Append(new GH_Brep(breps[0]), waysPath);
                        }
                        else
                        {
                            geometryGoo.Append(new GH_Curve(pL), waysPath);
                        }

                        //building massing
                        if (w.Tags.ContainsKey("building") || w.Tags.ContainsKey("building:part"))
                        {
                            if (pL.IsClosed)
                            {
                                CurveOrientation orient = pL.ClosedCurveOrientation(Plane.WorldXY);
                                if (orient != CurveOrientation.CounterClockwise)
                                {
                                    pL.Reverse();
                                }

                                Vector3d hVec = new Vector3d(0, 0, GetBldgHeight(osmGeo));
                                hVec.Transform(xformFromMetric);

                                Extrusion        ex      = Extrusion.Create(pL, hVec.Z, true);
                                IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(ex);
                                buildingGoo.Append(bldgGoo, waysPath);
                            }
                        }

                        //increment ways
                        ways++;
                    }
                    ///////////////////////////////////////////////////////////

                    //RELATIONS
                    if (osmGeo.Type == OsmGeoType.Relation)
                    {
                        OsmSharp.Relation r            = (OsmSharp.Relation)osmGeo;
                        GH_Path           relationPath = new GH_Path(2, relations);

                        //populate Fields and Values for each relation
                        fieldNames.AppendRange(GetKeys(osmGeo), relationPath);
                        fieldValues.AppendRange(GetValues(osmGeo), relationPath);

                        List <Curve> pLines = new List <Curve>();

                        // start members loop
                        for (int mem = 0; mem < r.Members.Length; mem++)
                        {
                            GH_Path memberPath = new GH_Path(2, relations, mem);

                            OsmSharp.RelationMember rMem    = r.Members[mem];
                            OsmSharp.OsmGeo         rMemGeo = sourceMem.Get(rMem.Type, rMem.Id);

                            if (rMemGeo != null)
                            {
                                //get geometry for node
                                if (rMemGeo.Type == OsmGeoType.Node)
                                {
                                    long          memNodeId = rMem.Id;
                                    OsmSharp.Node memN      = (OsmSharp.Node)sourceMem.Get(rMem.Type, rMem.Id);
                                    Point3d       memPoint  = Heron.Convert.WGSToXYZ(new Point3d((double)memN.Longitude, (double)memN.Latitude, 0));
                                    geometryGoo.Append(new GH_Point(memPoint), memberPath);
                                }

                                //get geometry for way
                                if (rMem.Type == OsmGeoType.Way)
                                {
                                    long memWayId = rMem.Id;

                                    OsmSharp.Way memWay = (OsmSharp.Way)rMemGeo;

                                    //get polyline geometry for way
                                    List <Point3d> memNodes = new List <Point3d>();
                                    foreach (long memNodeId in memWay.Nodes)
                                    {
                                        OsmSharp.Node memNode = (OsmSharp.Node)sourceMem.Get(OsmGeoType.Node, memNodeId);
                                        memNodes.Add(Heron.Convert.WGSToXYZ(new Point3d((double)memNode.Longitude, (double)memNode.Latitude, 0)));
                                    }

                                    PolylineCurve memPolyline = new PolylineCurve(memNodes);

                                    geometryGoo.Append(new GH_Curve(memPolyline.ToNurbsCurve()), memberPath);

                                    CurveOrientation orient = memPolyline.ClosedCurveOrientation(Plane.WorldXY);
                                    if (orient != CurveOrientation.CounterClockwise)
                                    {
                                        memPolyline.Reverse();
                                    }

                                    pLines.Add(memPolyline.ToNurbsCurve());
                                }

                                //get nested relations
                                if (rMem.Type == OsmGeoType.Relation)
                                {
                                    ///not sure if this is needed
                                }
                            }
                        }
                        //end members loop

                        bool allClosed = true;
                        foreach (Curve pc in pLines)
                        {
                            if (!pc.IsClosed)
                            {
                                allClosed = false;
                            }
                        }

                        if (pLines.Count > 0 && allClosed)
                        {
                            //create base surface
                            Brep[] breps = Brep.CreatePlanarBreps(pLines, DocumentTolerance());
                            geometryGoo.RemovePath(relationPath);

                            foreach (Brep b in breps)
                            {
                                geometryGoo.Append(new GH_Brep(b), relationPath);

                                //building massing
                                if (r.Tags.ContainsKey("building") || r.Tags.ContainsKey("building:part"))
                                {
                                    Vector3d hVec = new Vector3d(0, 0, GetBldgHeight(osmGeo));
                                    hVec.Transform(xformFromMetric);

                                    //create extrusion from base surface
                                    buildingGoo.Append(new GH_Brep(Brep.CreateFromOffsetFace(b.Faces[0], hVec.Z, DocumentTolerance(), false, true)), relationPath);
                                }
                            }
                        }

                        //increment relations
                        relations++;
                    } ///end relation loop
                }     ///end filtered loop
            }         ///end osm source loop

            if (recs.IsValid)
            {
                DA.SetData(0, recs);
            }
            DA.SetDataTree(1, fieldNames);
            DA.SetDataTree(2, fieldValues);
            DA.SetDataTree(3, geometryGoo);
            DA.SetDataTree(4, buildingGoo);
        } ///end SolveInstance
示例#39
0
 public static void WriteTo(this System.Xml.Linq.XDocument doc, XmlWriter writer)
 {
     writer.Write(doc);
 }
示例#40
0
 partial void OnValueBlobChanging(System.Xml.Linq.XDocument value);
示例#41
0
        public int WriteToFile(string FilePath)
        {
            if (this.Title == "")
            {
                this.Title = null;
            }
            if (this.Link == "")
            {
                this.Link = null;
            }
            if (this.Description == "")
            {
                this.Description = null;
            }
            if (this.Generator == "")
            {
                this.Generator = null;
            }
            if (this.Docs == "")
            {
                this.Docs = null;
            }
            if (this.Language == "")
            {
                this.Language = null;
            }
            if (this.PublicationDate == "")
            {
                this.PublicationDate = null;
            }
            if (this.LastBuildDate == "")
            {
                this.LastBuildDate = null;
            }

            System.Xml.Linq.XElement ListElements = new System.Xml.Linq.XElement("channel",
                                                                                 new System.Xml.Linq.XElement("title", this.Title),
                                                                                 new System.Xml.Linq.XElement("link", this.Link),
                                                                                 new System.Xml.Linq.XElement("description", this.Description),
                                                                                 new System.Xml.Linq.XElement("generator", this.Generator),
                                                                                 new System.Xml.Linq.XElement("docs", this.Docs),
                                                                                 new System.Xml.Linq.XElement("language", this.Language),
                                                                                 new System.Xml.Linq.XElement("pubDate", this.PublicationDate),
                                                                                 new System.Xml.Linq.XElement("lastBuildDate", this.LastBuildDate));

            foreach (item Item in ItemList)
            {
                if (Item.Title == "")
                {
                    Item.Title = null;
                }
                if (Item.Link == "")
                {
                    Item.Link = null;
                }
                if (Item.Description == "")
                {
                    Item.Description = null;
                }
                if (Item.PublicationDate == "")
                {
                    Item.PublicationDate = null;
                }
                ListElements.Add(
                    new System.Xml.Linq.XElement("item",
                                                 new System.Xml.Linq.XElement("title", Item.Title),
                                                 new System.Xml.Linq.XElement("link", Item.Link),
                                                 new System.Xml.Linq.XElement("description", Item.Description),
                                                 new System.Xml.Linq.XElement("pubDate", Item.PublicationDate)));
            }

            System.Xml.Linq.XDocument XmlRSSFile = new System.Xml.Linq.XDocument(
                new System.Xml.Linq.XElement("rss",
                                             new System.Xml.Linq.XAttribute("version", "2.0"),
                                             ListElements));

            XmlRSSFile.Declaration = new System.Xml.Linq.XDeclaration("1.0", "ISO-8859-15", "true");
            try
            {
                XmlRSSFile.Save(FilePath);
            }
            catch
            {
            }
            return(1);
        }
示例#42
0
        /// <summary> Reads the earthquakes from an xml file and adds a pin element for each to the map. </summary>
        private void ParseAtomUsingLinq()
        {
            System.Xml.Linq.XDocument  feedXML  = System.Xml.Linq.XDocument.Load("http://earthquake.usgs.gov/earthquakes/catalogs/7day-M2.5.xml");
            System.Xml.Linq.XNamespace xmlns    = "http://www.w3.org/2005/Atom";  //Atom namespace
            System.Xml.Linq.XNamespace georssns = "http://www.georss.org/georss"; //GeoRSS Namespace

            // time to learn some LINQ
            var posts = (from item in feedXML.Descendants(xmlns + "entry")
                         select new
            {
                Title = item.Element(xmlns + "title").Value,
                Published = DateTime.Parse(item.Element(xmlns + "updated").Value),
                Url = item.Element(xmlns + "link").Attribute("href").Value,
                Description = item.Element(xmlns + "summary").Value,
                Location = CoordinateGeoRssPoint(item.Element(georssns + "point")),
                //Simple GeoRSS <georss:point>X Y</georss.point>
            }).ToList();

            int i = 0;

            // order posts by latitude, so they overlap nicely on the map
            foreach (var post in from post in posts orderby post.Location.Y descending select post)
            {
                if (!double.IsNaN(post.Location.X) && !double.IsNaN(post.Location.Y))
                {
                    // transform wgs to PTVMercator coordinate
                    var mapPoint = GeoTransform.WGSToPtvMercator(post.Location);

                    // create button and set pin template
                    var pin = new Pin
                    {
                        // a bug in SL throws an obscure exception if children share the same name
                        // http://forums.silverlight.net/forums/t/134299.aspx
                        // the name is needed in XAML for data binding, so just create a unique name at runtime
                        Name = "pin" + (i++),
                        // set render transform for power-law scaling
                        RenderTransform = adjustTransform,
                        // scale around lower right
                        RenderTransformOrigin = new System.Windows.Point(1, 1)
                    };

                    // set size by magnitude
                    double magnitude = MagnitudeFromTitle(post.Title);
                    pin.Height = magnitude * 10;
                    pin.Width  = magnitude * 10;

                    // calculate a value between 0 and 1 and use it for a blend color
                    double relativeDanger = Math.Max(0, Math.Min(1, (magnitude - 2.5) / 4));
                    pin.Color = Colors.Red;
                    pin.Color = ColorBlend.Danger.GetColor((float)relativeDanger);

                    // set tool tip information
                    ToolTipService.SetToolTip(pin, post.Title);

                    // set position and add to canvas (invert y-ordinate)
                    // set lower right (pin-tip) as position
                    SetLeft(pin, mapPoint.X - pin.Width);
                    SetTop(pin, -(mapPoint.Y + pin.Height));
                    Children.Add(pin);
                }
            }
        }
示例#43
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///Gather GHA inputs
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            string osmFilePath = string.Empty;

            DA.GetData <string>("OSM Data Location", ref osmFilePath);

            //string userSRStext = "WGS84";
            //DA.GetData<string>(2, ref userSRStext);

            List <string> filterWords = new List <string>();

            DA.GetDataList <string>(2, filterWords);

            List <string> filterKeyValue = new List <string>();

            DA.GetDataList <string>(3, filterKeyValue);

            Transform xformToMetric   = new Transform(scaleToMetric);
            Transform xformFromMetric = new Transform(scaleFromMetric);

            ///Declare trees
            Rectangle3d recs = new Rectangle3d();
            GH_Structure <GH_String>        fieldNames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fieldValues = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> geometryGoo = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <IGH_GeometricGoo> buildingGoo = new GH_Structure <IGH_GeometricGoo>();


            Point3d max = new Point3d();
            Point3d min = new Point3d();

            if (boundary != null)
            {
                Point3d maxM = boundary.GetBoundingBox(true).Corner(true, false, true);
                max = Heron.Convert.XYZToWGS(maxM);

                Point3d minM = boundary.GetBoundingBox(true).Corner(false, true, true);
                min = Heron.Convert.XYZToWGS(minM);
            }

            /// get extents (why is this not part of OsmSharp?)
            System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load(osmFilePath);
            if (xdoc.Root.Element("bounds") != null)
            {
                double  minlat    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("minlat").Value);
                double  minlon    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("minlon").Value);
                double  maxlat    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("maxlat").Value);
                double  maxlon    = System.Convert.ToDouble(xdoc.Root.Element("bounds").Attribute("maxlon").Value);
                Point3d boundsMin = Heron.Convert.WGSToXYZ(new Point3d(minlon, minlat, 0));
                Point3d boundsMax = Heron.Convert.WGSToXYZ(new Point3d(maxlon, maxlat, 0));

                recs = new Rectangle3d(Plane.WorldXY, boundsMin, boundsMax);
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Cannot determine the extents of the OSM file. A 'bounds' element may not be present in the file. " +
                                  "Try turning off clipping in this component's menu.");
            }


            using (var fileStreamSource = File.OpenRead(osmFilePath))
            {
                /// create a source.
                OsmSharp.Streams.XmlOsmStreamSource source = new OsmSharp.Streams.XmlOsmStreamSource(fileStreamSource);

                /// filter by bounding box
                OsmSharp.Streams.OsmStreamSource sourceClipped = source;
                if (clipped)
                {
                    sourceClipped = source.FilterBox((float)max.X, (float)max.Y, (float)min.X, (float)min.Y, true);
                }

                /// create a dictionary of elements
                OsmSharp.Db.Impl.MemorySnapshotDb sourceMem = new OsmSharp.Db.Impl.MemorySnapshotDb(sourceClipped);

                /// filter the source
                var filtered = from osmGeos in sourceClipped
                               where osmGeos.Tags != null
                               select osmGeos;

                if (filterWords.Any())
                {
                    filtered = from osmGeos in filtered
                               where osmGeos.Tags.ContainsAnyKey(filterWords)
                               select osmGeos;
                }

                if (filterKeyValue.Any())
                {
                    List <Tag> tags = new List <Tag>();
                    foreach (string term in filterKeyValue)
                    {
                        string[] kv  = term.Split(',');
                        Tag      tag = new Tag(kv[0], kv[1]);
                        tags.Add(tag);
                    }
                    filtered = from osmGeos in filtered
                               where osmGeos.Tags.Intersect(tags).Any()
                               select osmGeos;
                }

                source.Dispose();

                /// loop over all objects and count them.
                int nodes = 0, ways = 0, relations = 0;
                Dictionary <PolylineCurve, GH_Path> bldgOutlines = new Dictionary <PolylineCurve, GH_Path>();
                List <BuildingPart> buildingParts = new List <BuildingPart>();


                foreach (OsmSharp.OsmGeo osmGeo in filtered)
                {
                    //NODES
                    if (osmGeo.Type == OsmGeoType.Node)
                    {
                        OsmSharp.Node n         = (OsmSharp.Node)osmGeo;
                        GH_Path       nodesPath = new GH_Path(0, nodes);

                        //populate Fields and Values for each node
                        fieldNames.AppendRange(GetKeys(osmGeo), nodesPath);
                        fieldValues.AppendRange(GetValues(osmGeo), nodesPath);

                        //get geometry for node
                        Point3d nPoint = Heron.Convert.WGSToXYZ(new Point3d((double)n.Longitude, (double)n.Latitude, 0));
                        geometryGoo.Append(new GH_Point(nPoint), nodesPath);

                        //increment nodes
                        nodes++;
                    }

                    ////////////////////////////////////////////////////////////
                    //WAYS
                    if (osmGeo.Type == OsmGeoType.Way)
                    {
                        OsmSharp.Way w        = (OsmSharp.Way)osmGeo;
                        GH_Path      waysPath = new GH_Path(1, ways);

                        //populate Fields and Values for each way
                        fieldNames.AppendRange(GetKeys(osmGeo), waysPath);
                        fieldValues.AppendRange(GetValues(osmGeo), waysPath);

                        //get polyline geometry for way
                        List <Point3d> wayNodes = new List <Point3d>();
                        foreach (long j in w.Nodes)
                        {
                            OsmSharp.Node n = (OsmSharp.Node)sourceMem.Get(OsmGeoType.Node, j);
                            wayNodes.Add(Heron.Convert.WGSToXYZ(new Point3d((double)n.Longitude, (double)n.Latitude, 0)));
                        }

                        PolylineCurve pL = new PolylineCurve(wayNodes);
                        if (pL.IsClosed)
                        {
                            //create base surface
                            Brep[] breps = Brep.CreatePlanarBreps(pL, DocumentTolerance());
                            geometryGoo.Append(new GH_Brep(breps[0]), waysPath);
                        }
                        else
                        {
                            geometryGoo.Append(new GH_Curve(pL), waysPath);
                        }

                        //building massing
                        if ((w.Tags.ContainsKey("building") || w.Tags.ContainsKey("building:part")))// && !w.Tags.ContainsKey("construction"))
                        {
                            if (pL.IsClosed)
                            {
                                ///Populate dictionary for sorting building parts later
                                if (w.Tags.ContainsKey("building"))
                                {
                                    bldgOutlines.Add(pL, waysPath);
                                }

                                CurveOrientation orient = pL.ClosedCurveOrientation(Plane.WorldXY);
                                if (orient != CurveOrientation.CounterClockwise)
                                {
                                    pL.Reverse();
                                }

                                ///Move polylines to min height
                                double   minHeightWay = GetMinBldgHeight(osmGeo);
                                Vector3d minVec       = new Vector3d(0, 0, minHeightWay);
                                //minVec.Transform(xformFromMetric);
                                if (minHeightWay > 0.0)
                                {
                                    var minHeightTranslate = Transform.Translation(minVec);
                                    pL.Transform(minHeightTranslate);
                                }

                                Vector3d hVec = new Vector3d(0, 0, GetBldgHeight(osmGeo) - minHeightWay);
                                //hVec.Transform(xformFromMetric);

                                Extrusion        ex      = Extrusion.Create(pL, hVec.Z, true);
                                IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(ex);

                                ///Save building parts for sorting later and remove part from geometry goo tree
                                if (w.Tags.ContainsKey("building:part"))
                                {
                                    BuildingPart bldgPart = new BuildingPart(pL, bldgGoo, fieldNames[waysPath], fieldValues[waysPath], osmGeo);
                                    buildingParts.Add(bldgPart);
                                    fieldNames.RemovePath(waysPath);
                                    fieldValues.RemovePath(waysPath);
                                    geometryGoo.RemovePath(waysPath);
                                    ways = ways - 1;
                                }
                                else
                                {
                                    buildingGoo.Append(bldgGoo, waysPath);
                                }
                            }
                        }

                        //increment ways
                        ways++;
                    }
                    ///////////////////////////////////////////////////////////

                    //RELATIONS
                    if (osmGeo.Type == OsmGeoType.Relation)
                    {
                        OsmSharp.Relation r            = (OsmSharp.Relation)osmGeo;
                        GH_Path           relationPath = new GH_Path(2, relations);

                        //populate Fields and Values for each relation
                        fieldNames.AppendRange(GetKeys(osmGeo), relationPath);
                        fieldValues.AppendRange(GetValues(osmGeo), relationPath);

                        List <Curve> pLines = new List <Curve>();

                        // start members loop
                        for (int mem = 0; mem < r.Members.Length; mem++)
                        {
                            GH_Path memberPath = new GH_Path(2, relations, mem);

                            OsmSharp.RelationMember rMem    = r.Members[mem];
                            OsmSharp.OsmGeo         rMemGeo = sourceMem.Get(rMem.Type, rMem.Id);

                            if (rMemGeo != null)
                            {
                                //get geometry for node
                                if (rMemGeo.Type == OsmGeoType.Node)
                                {
                                    long          memNodeId = rMem.Id;
                                    OsmSharp.Node memN      = (OsmSharp.Node)sourceMem.Get(rMem.Type, rMem.Id);
                                    Point3d       memPoint  = Heron.Convert.WGSToXYZ(new Point3d((double)memN.Longitude, (double)memN.Latitude, 0));
                                    geometryGoo.Append(new GH_Point(memPoint), memberPath);
                                }

                                //get geometry for way
                                if (rMem.Type == OsmGeoType.Way)
                                {
                                    long memWayId = rMem.Id;

                                    OsmSharp.Way memWay = (OsmSharp.Way)rMemGeo;

                                    //get polyline geometry for way
                                    List <Point3d> memNodes = new List <Point3d>();
                                    foreach (long memNodeId in memWay.Nodes)
                                    {
                                        OsmSharp.Node memNode = (OsmSharp.Node)sourceMem.Get(OsmGeoType.Node, memNodeId);
                                        memNodes.Add(Heron.Convert.WGSToXYZ(new Point3d((double)memNode.Longitude, (double)memNode.Latitude, 0)));
                                    }

                                    PolylineCurve memPolyline = new PolylineCurve(memNodes);

                                    geometryGoo.Append(new GH_Curve(memPolyline.ToNurbsCurve()), memberPath);

                                    CurveOrientation orient = memPolyline.ClosedCurveOrientation(Plane.WorldXY);
                                    if (orient != CurveOrientation.CounterClockwise)
                                    {
                                        memPolyline.Reverse();
                                    }

                                    pLines.Add(memPolyline.ToNurbsCurve());
                                }

                                //get nested relations
                                if (rMem.Type == OsmGeoType.Relation)
                                {
                                    ///not sure if this is needed
                                }
                            }
                        }
                        //end members loop

                        bool allClosed = true;
                        foreach (Curve pc in pLines)
                        {
                            if (!pc.IsClosed)
                            {
                                allClosed = false;
                            }
                        }

                        if (pLines.Count > 0 && allClosed)
                        {
                            ///Move polylines to min height
                            double minHeight = GetMinBldgHeight(osmGeo);
                            if (minHeight > 0.0)
                            {
                                Vector3d minVec = new Vector3d(0, 0, minHeight);
                                //minVec.Transform(xformFromMetric);
                                var minHeightTranslate = Transform.Translation(minVec);
                                for (int i = 0; i < pLines.Count; i++)
                                {
                                    pLines[i].Transform(minHeightTranslate);
                                }
                            }
                            ///Create base surface
                            Brep[] breps = Brep.CreatePlanarBreps(pLines, DocumentTolerance());
                            geometryGoo.RemovePath(relationPath);

                            foreach (Brep b in breps)
                            {
                                geometryGoo.Append(new GH_Brep(b), relationPath);

                                ///Building massing
                                if (r.Tags.ContainsKey("building") || r.Tags.ContainsKey("building:part"))
                                {
                                    Vector3d hVec = new Vector3d(0, 0, GetBldgHeight(osmGeo) - minHeight);
                                    //hVec.Transform(xformFromMetric);

                                    ///Create extrusion from base surface
                                    buildingGoo.Append(new GH_Brep(Brep.CreateFromOffsetFace(b.Faces[0], hVec.Z, DocumentTolerance(), false, true)), relationPath);
                                }
                            }
                        }

                        ///Increment relations
                        relations++;
                    } ///End relation loop
                }     ///End filtered loop

                ///Add building parts to sub-branches under main building
                for (int partIndex = 0; partIndex < buildingParts.Count; partIndex++)
                {
                    BuildingPart bldgPart  = buildingParts[partIndex];
                    Point3d      partPoint = bldgPart.PartFootprint.PointAtStart;
                    partPoint.Z = 0;
                    bool          replaceBuidingMass   = false;
                    GH_Path       mainBuildingMassPath = new GH_Path();
                    PolylineCurve massOutline          = new PolylineCurve();

                    bool isRoof = bldgPart.PartOsmGeo.Tags.TryGetValue("roof:shape", out string isRoofString);
                    if (isRoof)
                    {
                        bldgPart.PartGoo = BldgPartToRoof(bldgPart);
                    }

                    foreach (KeyValuePair <PolylineCurve, GH_Path> pair in bldgOutlines)
                    {
                        PointContainment pc = pair.Key.Contains(partPoint, Plane.WorldXY, DocumentTolerance());
                        if (pc != PointContainment.Outside)
                        {
                            ///Create new sub-branch
                            int     numSubBranches = 0;
                            GH_Path partPath       = pair.Value.AppendElement(numSubBranches);
                            while (buildingGoo.PathExists(partPath))
                            {
                                numSubBranches++;
                                partPath = pair.Value.AppendElement(numSubBranches);
                            }

                            ///Add data to sub-branch
                            fieldNames.AppendRange(bldgPart.PartFieldNames, partPath);
                            fieldValues.AppendRange(bldgPart.PartFieldValues, partPath);
                            buildingGoo.Append(bldgPart.PartGoo, partPath);

                            ///Remove the main building mass
                            replaceBuidingMass   = true;
                            mainBuildingMassPath = pair.Value;
                            massOutline          = pair.Key;
                        }
                    }
                    ///Remove the main building mass
                    if (replaceBuidingMass)
                    {
                        buildingGoo.RemovePath(mainBuildingMassPath);
                        buildingGoo.Append(new GH_Curve(massOutline), mainBuildingMassPath);
                    }
                    else
                    {
                        GH_Path extrasPath = new GH_Path(3, partIndex);
                        buildingGoo.Append(bldgPart.PartGoo, extrasPath);
                        fieldNames.AppendRange(bldgPart.PartFieldNames, extrasPath);
                        fieldValues.AppendRange(bldgPart.PartFieldValues, extrasPath);
                    }
                }
            } ///end osm source loop

            if (recs.IsValid)
            {
                DA.SetData(0, recs);
            }
            DA.SetDataTree(1, fieldNames);
            DA.SetDataTree(2, fieldValues);
            DA.SetDataTree(3, geometryGoo);
            DA.SetDataTree(4, buildingGoo);
        } ///end SolveInstance
示例#44
0
 public async Task <TransportResult> SendAsync(System.Xml.Linq.XDocument document)
 {
     return(await Task.FromResult(Send(document)));
 }
示例#45
0
        private string GenerateExport()
        {
            string             templateExport    = TemplateExporter.GenerateXMLExport(this.tdb, this.templates, this.igSettings, true, this.categories);
            LantanaXmlResolver resolver          = new LantanaXmlResolver();
            string             stylesheetContent = string.Empty;

            using (StreamReader stylesheetReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(StylesheetResource)))
            {
                stylesheetContent = stylesheetReader.ReadToEnd();
            }

            var export = TransformFactory.Transform(templateExport, stylesheetContent, StylesheetUri, resolver);

            if (includeVocabulary)
            {
                // Export the vocabulary for the implementation guide in SVS format
                VocabularyService vocService = new VocabularyService(tdb, false);
                string            vocXml     = vocService.GetImplementationGuideVocabulary(igSettings.ImplementationGuideId, 1000, 4, "utf-8");

                // Merge the two ATOM exports together
                XmlDocument exportDoc = new XmlDocument();
                exportDoc.LoadXml(export);

                // Remove extra xmlns attributes from vocabulary xml
                System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Parse(vocXml);
                foreach (var descendant in doc.Root.Descendants())
                {
                    var namespaceDeclarations = descendant.Attributes().Where(y => y.IsNamespaceDeclaration && y.Name.LocalName == "atom");
                    foreach (var namespaceDeclaration in namespaceDeclarations)
                    {
                        namespaceDeclaration.Remove();
                    }
                }
                vocXml = doc.ToString();

                XmlDocument vocDoc = new XmlDocument();
                vocDoc.LoadXml(vocXml);

                XmlNamespaceManager vocNsManager = new XmlNamespaceManager(vocDoc.NameTable);
                vocNsManager.AddNamespace("atom", "http://www.w3.org/2005/Atom");

                XmlNodeList vocEntryNodes = vocDoc.SelectNodes("/atom:feed/atom:entry", vocNsManager);

                foreach (XmlNode vocEntryNode in vocEntryNodes)
                {
                    XmlNode clonedVocEntryNode = exportDoc.ImportNode(vocEntryNode, true);
                    exportDoc.DocumentElement.AppendChild(clonedVocEntryNode);
                }

                // Format the XmlDocument and save it as a string
                using (StringWriter sw = new StringWriter())
                {
                    XmlTextWriter xtw = new XmlTextWriter(sw);
                    xtw.Formatting = Formatting.Indented;

                    exportDoc.WriteContentTo(xtw);
                    export = sw.ToString();
                }
            }

            return(export);
        }
        private void SauvegarderFichier()
        {
            App.MainVM.stop();
            while (App.MainVM.Runnin)
            {
            }

            var MainVMXML = new System.Xml.Linq.XElement("MainVM");

            MainVMXML.Add(new System.Xml.Linq.XElement("Dim", App.MainVM.Dim));
            MainVMXML.Add(new System.Xml.Linq.XElement("TitreApplication", App.MainVM.TitreApplication));
            MainVMXML.Add(new System.Xml.Linq.XElement("VitesseExec", App.MainVM.VitesseExec));
            MainVMXML.Add(new System.Xml.Linq.XElement("Runnin", false));

            var TerrainXML = new System.Xml.Linq.XElement("Terrain");

            TerrainXML.Add(new System.Xml.Linq.XElement("NbTours", App.MainVM.Terrain.NbTours));
            var CasesXML = new System.Xml.Linq.XElement("Cases");

            foreach (CaseAbstrait caseAbs in App.MainVM.Terrain.Cases)
            {
                var CaseXML = new System.Xml.Linq.XElement("Case");
                CaseXML.Add(new System.Xml.Linq.XElement("Class", caseAbs.GetType().Name));
                CaseXML.Add(new System.Xml.Linq.XElement("CordX", caseAbs.CordX));
                CaseXML.Add(new System.Xml.Linq.XElement("CordY", caseAbs.CordY));
                CaseXML.Add(new System.Xml.Linq.XElement("PheromoneMaison", caseAbs.PheromoneMaison));
                CaseXML.Add(new System.Xml.Linq.XElement("PheromoneNourriture", caseAbs.PheromoneNourriture));
                CaseXML.Add(new System.Xml.Linq.XElement("NbTours", caseAbs.NbTours));
                if (caseAbs is CaseNourriture)
                {
                    var NourritureXML = new System.Xml.Linq.XElement("Nourriture");
                    NourritureXML.Add(new System.Xml.Linq.XElement("Poids", ((CaseNourriture)caseAbs).Nourriture.Poids));
                    CaseXML.Add(NourritureXML);
                }
                if (caseAbs is CaseFourmiliere)
                {
                    var FourmiliereXML = new System.Xml.Linq.XElement("Fourmiliere");
                    FourmiliereXML.Add(new System.Xml.Linq.XElement("NombreNourritures", ((CaseFourmiliere)caseAbs).Fourmiliere.NombreNourritures));
                    FourmiliereXML.Add(new System.Xml.Linq.XElement("NombreTours", ((CaseFourmiliere)caseAbs).Fourmiliere.NombreTours));
                    CaseXML.Add(FourmiliereXML);
                }
                var FourmisXML = new System.Xml.Linq.XElement("Fourmis");
                foreach (Fourmi fourmi in caseAbs.Fourmis)
                {
                    var FourmiXML = new System.Xml.Linq.XElement("Fourmi");
                    FourmiXML.Add(new System.Xml.Linq.XElement("Vie", fourmi.Vie));
                    FourmiXML.Add(new System.Xml.Linq.XElement("StrategieFourmi", fourmi.StrategieFourmi.GetType().Name));
                    FourmisXML.Add(FourmiXML);
                }
                CaseXML.Add(FourmisXML);
                CasesXML.Add(CaseXML);
            }
            TerrainXML.Add(CasesXML);
            MainVMXML.Add(TerrainXML);

            var StatistiqueXML = new System.Xml.Linq.XElement("Statistique");

            StatistiqueXML.Add(new System.Xml.Linq.XElement("NombreFourmis", App.MainVM.Statistique.NombreFourmis));
            StatistiqueXML.Add(new System.Xml.Linq.XElement("NombreTours", App.MainVM.Statistique.NombreTours));
            MainVMXML.Add(StatistiqueXML);

            var Sauvegarde = new System.Xml.Linq.XDocument(MainVMXML);

            SaveFileDialog SFDialog = new SaveFileDialog();

            SFDialog.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
            SFDialog.DefaultExt       = "xml";
            SFDialog.AddExtension     = true;
            SFDialog.Filter           = "XML Files|*.xml|All Files|*.*";
            SFDialog.FilterIndex      = 1;
            if (SFDialog.ShowDialog() == true && SFDialog.FileName.Length > 0)
            {
                Sauvegarde.Save(SFDialog.FileName);
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show("Fichier Sauvegardé !", "Sauvegarde", MessageBoxButton.OK);
            }
        }
示例#47
0
        static void Test1(System.Xml.Linq.XDocument doc, System.Type type)
        {
            Contract.Requires(type != null);

            Contract.Assert(doc.Annotations(type) != null);
        }
示例#48
0
 public System.Xml.Linq.XNode Serialize(System.Xml.Linq.XDocument doc)
 {
     //throw new NotImplementedException();
     return(null);
 }
示例#49
0
 partial void OnAdditionalContactInfoChanging(System.Xml.Linq.XDocument value);
 public XDocument(System.Xml.Linq.XDocument other)
 {
 }
示例#51
0
 public void Receive(System.ServiceModel.Channels.Message request, System.Xml.Linq.XDocument soapMessage)
 {
     System.ServiceModel.OperationContext.Current.IncomingMessageProperties.Add("MY.AUTHENTICATION", "This is from AUTHENTICATION");
 }
 public XMLUserAuthenticationProvider(System.IO.StreamReader xmlStream)
 {
     _documentFromStream = LoadDocumentFromStream(xmlStream);
 }
示例#53
0
 public void Respond(System.ServiceModel.Channels.Message response, System.Xml.Linq.XDocument soapMessage)
 {
 }