Inheritance: MonoBehaviour
        public void Start()
        {
            int count = _recElements.Count;
           
            for (int batchNumber = 0; batchNumber < this.BatchCount; batchNumber++)
            {
                XmlHelper h = new XmlHelper(RequestContentElement);

                int start = batchNumber * this.Size;
                int end = start + this.Size;
                if (end > count)
                    end = count;

                for (int i = start; i < end; i++)
                {                
                    XmlElement rec = _recElements[i];
                    h.AddElement(".", rec);                    
                }

                Envelope env = new Envelope(h);
                XmlHelper p = new XmlHelper("<Parameter/>");
                p.AddElement(".", "BatchID", _batchID);
                p.AddElement(".", "BatchNumber", batchNumber.ToString());
                env.Headers.Add(p);

                BackgroundWorker w = new BackgroundWorker();
                w.DoWork += new DoWorkEventHandler(w_DoWork);
                w.RunWorkerCompleted += new RunWorkerCompletedEventHandler(w_RunWorkerCompleted);
                w.RunWorkerAsync(env);
            }
        }
Esempio n. 2
0
        internal UDTHandler(ProjectHandler project, XmlElement source)
        {
            Parent = project;
            Tables = new List<UDTTable>();
            AllUDTTables = new List<UDTTable>();

            _allUDTs = new List<string>();

            XmlHelper h = new XmlHelper(source);

            XmlHelper ph = new XmlHelper(project.Preference);
            List<string> list = new List<string>();
            foreach (XmlElement e in ph.GetElements("Property/UDT"))
            {
                string name = e.GetAttribute("Name");
                list.Add(name.ToLower());
                _allUDTs.Add(name);
            }

            foreach (XmlElement tableElement in h.GetElements("TableName"))
            {
                UDTTable table = new UDTTable(tableElement.InnerText);
                if (list.Contains(table.Name.ToLower()))
                    Tables.Add(table);
                _allUDTs.Add(table.Name.ToLower());
                AllUDTTables.Add(table);
            }
        }
Esempio n. 3
0
        internal Field(XmlElement fieldElement)
        {
            XmlHelper h = new XmlHelper(fieldElement);

            this.Source = fieldElement.GetAttribute("Source");
            this.Target = fieldElement.GetAttribute("Target");
            this.InputConverter = ConverterType.Parse(fieldElement.GetAttribute("InputConverter"));
            this.OutputConverter = ConverterType.Parse(fieldElement.GetAttribute("OutputConverter"));
            this.Quote = h.TryGetBoolean("@Quote", true);
            this.Mandatory = h.TryGetBoolean("@Mandatory", false);
            this.Alias = fieldElement.GetAttribute("Alias");
            this.Required = h.TryGetBoolean("@Required", false);
            this.AutoNumber = h.TryGetBoolean("@AutoNumber", false);

            SourceType sType = SourceType.Request;
            if (!Enum.TryParse<SourceType>(fieldElement.GetAttribute("SourceType"), true, out sType))
                sType = SourceType.Request;
            this.SourceType = sType;

            IOType iType = IOType.Element;
            if (!Enum.TryParse<IOType>(fieldElement.GetAttribute("InputType"), true, out iType))
                iType = IOType.Element;
            this.InputType = iType;

            IOType oType = IOType.Element;
            if (!Enum.TryParse<IOType>(fieldElement.GetAttribute("OutputType"), true, out oType))
                oType = IOType.Element;
            this.OutputType = oType;

        }
Esempio n. 4
0
        private static Dictionary<string, ConfigurationRecord> SendRequest(DSXmlHelper request)
        {
            string srvname = "SmartSchool.Configuration.GetDetailList";
            Dictionary<string, ConfigurationRecord> records = new Dictionary<string, ConfigurationRecord>();

            DSXmlHelper response = DSAServices.CallService(srvname, new DSRequest(request)).GetContent();

            foreach (XmlElement each in response.GetElements("Configuration"))
            {
                XmlHelper helper = new XmlHelper(each);
                string name = helper.GetString("Name");

                XmlElement configdata = null;
                foreach (XmlNode content in helper.GetElement("Content").ChildNodes)
                {
                    if (content.NodeType == XmlNodeType.Element) //內容可能是以「Configurations」為 Root,也可能是舊的格式。
                        configdata = content as XmlElement;
                }

                if (configdata == null)
                    configdata = XmlHelper.LoadXml("<" + ConfigurationRecord.RootName + "/>");

                records.Add(name, new ConfigurationRecord(name, configdata as XmlElement));
            }

            return records;
        }
Esempio n. 5
0
 public void ReadXml(XmlReader reader)
 {
     var xml = new XmlHelper(reader);
     Totals = xml.deserialize<FactionWarfareTotals>("totals");
     Factions = xml.deserializeRowSet<FactionWarfareEntry>("factions");
     FactionWars = xml.deserializeRowSet<FactionWarfareEntry>("factionWars");
 }
        public void SetDefinition(System.Xml.XmlElement definition)
        {
            XmlHelper h = new XmlHelper(definition);
            _initialized = false;

            //Check Basic Tab
            chkBasic.Checked = CheckEnable(h.GetElement("Authentication/Basic"), true);
            cbHashProvider.Text = h.GetText("Authentication/Basic/PasswordHashProvider/@DriverClass");
            txtGetUserDataQuery.Text = h.GetText("Authentication/Basic/UserInfoStorage/DBSchema/GetUserDataQuery");
            txtGetUserRoleQuery.Text = h.GetText("Authentication/Basic/UserInfoStorage/DBSchema/GetUserRolesQuery");

            //Check Session Tab
            chkSession.Checked = h.TryGetBoolean("Authentication/Session/@Enabled", true);
            txtTimeout.Text = h.TryGetInteger("Authentication/Session/@Timeout", 20).ToString();

            //Check Passport Tab
            chkPassport.Checked = CheckEnable(h.GetElement("Authentication/Passport"), false);
            txtIssuer.Text = h.GetText("Authentication/Passport/Issuer/@Name");
            txtCertProvider.Text = h.GetText("Authentication/Passport/Issuer/CertificateProvider");
            cbALTable.Text = h.GetText("Authentication/Passport/AccountLinking/TableName");
            cboMappingField.Text = h.GetText("Authentication/Passport/AccountLinking/MappingField");
            cbUserNameField.Text = h.GetText("Authentication/Passport/AccountLinking/UserNameField");

            dgExtProp.Rows.Clear();
            foreach (XmlElement pe in h.GetElements("Authentication/Passport/AccountLinking/Properties/Property"))
            {
                int index = dgExtProp.Rows.Add();
                DataGridViewRow row = dgExtProp.Rows[index];
                row.Cells[colAlias.Name].Value = pe.GetAttribute("Alias");
                row.Cells[colDBField.Name].Value = pe.GetAttribute("Field");
            }

            CheckTabs();
            _initialized = true;
        }
 public System.Xml.XmlElement GetAuthElement()
 {
     XmlHelper h = new XmlHelper("<Authentication />");
     h.AddElement(".", "Public");
     h.SetAttribute("Public", "Enabled", "true");
     return h.GetElement(".");
 }
        private void EditProxyDeployForm_Load(object sender, EventArgs e)
        {
            if (_siteElement == null) return;

            XmlHelper h = new XmlHelper(_siteElement);

            txtSiteName.Text = _siteElement.GetAttribute("Name");
            txtAccessPoint.Text = h.GetText("AccessPoint");
            txtContract.Text = h.GetText("Contract");
            string authType = h.GetText("Authentication/@Type").ToLower();

            if (authType == "basic")
            {
                rbBasic.Checked = true;
                txtBasicAccount.Text = h.GetText("Authentication/UserName");
                txtBasicPassword.Text = h.GetText("Authentication/Password");
            }
            else
            {
                rbPassport.Checked = true;

                txtIssuer.Text = h.GetText("Authentication/Issuer");
                txtIssuerAccount.Text = h.GetText("Authentication/UserName");
                txtIssuerPassword.Text = h.GetText("Authentication/Password");
            }
        }
        public void Save()
        {
            if (!Valid)
                return;

            IContractEditor edit = Editor as IContractEditor;
            edit.Save();

            IResultGetter result = Editor as IResultGetter;
            XmlElement authElement = result.GetAuthElement();

            XmlHelper h = new XmlHelper("<Definition/>");
            h.AddElement(".", authElement);

            try
            {
                Contract.SetDefinition(h.GetElement("."), _owner);

                MessageBox.Show("儲存完畢!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("儲存失敗!" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 private void BindSiteToRow(DataGridViewRow row, XmlElement siteElement)
 {
     XmlHelper h = new XmlHelper(siteElement);
     row.Cells[colSiteName.Name].Value = siteElement.GetAttribute("Name");
     row.Cells[colAccessPoint.Name].Value = h.GetText("AccessPoint");
     row.Tag = siteElement;
 }
Esempio n. 11
0
 public void ReadXml(XmlReader reader)
 {
     var xml = new XmlHelper(reader);
     Agents = xml.deserializeRowSet<StandingEntry>("agents");
     Corporations = xml.deserializeRowSet<StandingEntry>("NPCCorporations");
     Factions = xml.deserializeRowSet<StandingEntry>("factions");
 }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (rbAll.Checked)
            {
                XmlHelper sh = new XmlHelper();
                XmlHelper th = new XmlHelper();

                Parallel.ForEach(MainForm.CurrentUDS.Contracts, contract =>
                {
                    sh.AddElement(".", "ContractName", contract.Name);
                });
                
                Parallel.ForEach(MainForm.CurrentUDT.Tables, table =>
                {
                    th.AddElement(".", "TableName", table.Name);
                });

                try
                {
                    _project.SendRequest("UDSManagerService.DeleteContracts", new Envelope(sh));
                }
                catch { }
                try
                {
                    _project.SendRequest("UDTService.DDL.DropTables", new Envelope(th));
                }
                catch { }
            }

            MainForm.Projects.RemoveProject(_project.Name);            
            this.Close();
        }
Esempio n. 13
0
 public void ReadXml(XmlReader reader)
 {
     var xml = new XmlHelper(reader);
     PersonalContacts = xml.deserializeRowSet<Contact>("contactList");
     CorporationContacts = xml.deserializeRowSet<Contact>("corporateContactList");
     AllianceContacts = xml.deserializeRowSet<Contact>("allianceContactList");
 }
Esempio n. 14
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MainForm.DefaultDevSite.User = txtUser.Text;
                MainForm.DefaultDevSite.Password = txtPassword.Text;
                MainForm.DefaultDevSite.AccessPoint = txtAP.Text;
                MainForm.DefaultDevSite.ContractName = cboContract.Text;

                XmlHelper apXml = new XmlHelper("<AppContent/>");
                apXml.AddElement(".", "AccessPoint", txtAP.Text);
                apXml.AddElement(".", "ContractName", cboContract.Text);
                apXml.AddElement(".", "User", txtUser.Text);
                apXml.AddElement(".", "Password", txtPassword.Text);

                MainForm.Storage.SetPropertyXml("DevLoginAP", txtAP.Text, apXml.GetElement("."));
                MainForm.Storage.SetProperty("DevLastLoginAP", txtAP.Text);
                MainForm.Storage.SetProperty("DevLastLoginContract", cboContract.Text);
                MainForm.Storage.SetProperty("DevLastLoginName", txtUser.Text);
                MainForm.Storage.SetProperty("DevLastLoginPassword", txtPassword.Text);
                MainForm.Storage.SetProperty("DevAutoLogin", chkAutoLogin.Checked.ToString().ToLower());
                
                MainForm.LoginArgs.StaticPreference = apXml.GetElement("."); ;

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public XmlElement Generate(XmlElement serviceDefinition)
        {
            ServiceEntity service = ServiceEntity.Parse(serviceDefinition);

            XmlHelper h = new XmlHelper("<Request/>");
            XmlElement reqElement = h.GetElement(".");
                        
            XmlElement recElement = h.AddElement(".", service.RequestRecordElement);
            XmlHelper recHelper = new XmlHelper(recElement);
            XmlElement fieldElement = recHelper.GetElement(".");
            if (!string.IsNullOrWhiteSpace(service.FieldList.Source))
                fieldElement = recHelper.AddElement(".", service.FieldList.Source);

            XmlHelper fieldHelper = new XmlHelper(fieldElement);
            List<Field> _requires = new List<Field>();
            List<Field> _notRequries = new List<Field>();

            foreach (Field field in service.FieldList.Fields)
            {
                if (field.SourceType != SourceType.Request) continue;
                if (field.AutoNumber) continue;

                if (field.InputType == IOType.Attribute)
                    fieldElement.SetAttribute(field.Source, string.Empty);
                else if (field.Required)
                    _requires.Add(field);
                else
                    _notRequries.Add(field);
            }

            if (_requires.Count > 0)
            {
                XmlNode node = reqElement.OwnerDocument.CreateComment("以下為必要欄位");
                fieldElement.AppendChild(node);

                foreach (Field field in _requires)
                {
                    string value = string.Empty;
                    if (field.InputType == IOType.Xml)
                        value = "xml";
                    fieldHelper.AddElement(".", field.Source, value);
                }
            }

            if (_notRequries.Count > 0)
            {
                XmlNode node = reqElement.OwnerDocument.CreateComment("以下為非必要欄位");
                fieldElement.AppendChild(node);

                foreach (Field field in _notRequries)
                {
                    string value = string.Empty;
                    if (field.InputType == IOType.Xml)
                        value = "xml";
                    fieldHelper.AddElement(".", field.Source, value);
                }
            }
           
            return reqElement;
        }
Esempio n. 16
0
        public UDSHandler(ProjectHandler project, XmlElement source)
        {
            Parent = project;
            Contracts = new List<ContractHandler>();
            AllContracts = new List<ContractHandler>();

            XmlHelper ph = new XmlHelper(project.Preference);
            List<string> list = new List<string>();
            foreach (XmlElement e in ph.GetElements("Property/Contract"))
            {
                string name = e.GetAttribute("Name");
                list.Add(name);
            }

            XmlHelper h = new XmlHelper(source);
            foreach (XmlElement contractElement in h.GetElements("Contract"))
            {
                ContractHandler ch = new ContractHandler(contractElement);

                if (list.Contains(ch.Name))
                    Contracts.Add(ch);

                AllContracts.Add(ch);
            }
        }
        internal List<string> ListProjects()
        {
            if (_projects != null)
                return _projects;

            XmlHelper req = new XmlHelper("<Request/>");
            req.AddElement(".", "Condition");
            req.AddElement("Condition", "Name", PROJECT_LIST_PS_NAME);
            Envelope evn = MainForm.LoginArgs.GreeningConnection.SendRequest("GetMySpace", new Envelope(req));
            XmlHelper rsp = new XmlHelper(evn.Body);

            _projects = new List<string>();

            if (rsp.GetElement("Space") == null)
            {
                req = new XmlHelper("<Request/>");
                req.AddElement(".", "Space");
                req.AddElement("Space", "Name", PROJECT_LIST_PS_NAME);
                XmlElement content = req.AddElement("Space", "Content");
                XmlCDataSection section = content.OwnerDocument.CreateCDataSection("<ProjectList/>");
                content.AppendChild(section);
                MainForm.LoginArgs.GreeningConnection.SendRequest("CreateSpace", new Envelope(req));
            }
            else
            {
                string content = rsp.GetText("Space/Content");
                XmlHelper h = new XmlHelper(content);

                foreach (XmlElement projectElement in h.GetElements("Project"))
                    _projects.Add(projectElement.GetAttribute("Name"));
            }
            return _projects;
        }
Esempio n. 18
0
        internal ContractHandler AddContract(string ContractName, ExtendType extend)
        {
            XmlHelper req = new XmlHelper("<Request/>");
            req.AddElement(".", "ContractName", ContractName);

            req.AddElement(".", "Definition");
            XmlElement authElement = req.AddElement("Definition", "Authentication");

            if (extend == ExtendType.open)
            {
                XmlElement e = req.AddElement("Definition/Authentication", "Public");
                e.SetAttribute("Enabled", "true");
            }
            else
            {
                if (extend != ExtendType.none && extend != ExtendType.open)
                    authElement.SetAttribute("Extends", extend.ToString());
            }

            Parent.SendRequest("UDSManagerService.CreateContract", new Envelope(req));

            ContractHandler contract = ContractHandler.CreateNew(ContractName, extend);
            JoinProject(contract);
            return contract;
        }
Esempio n. 19
0
 internal XmlElement GetXml()
 {
     XmlHelper h = new XmlHelper("<Order/>");
     h.SetAttribute(".", "Target", Target);
     h.SetAttribute(".", "Source", Source);
     return h.GetElement(".");
 }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtModule.Text == _moduleURL && txtGreening.Text == _greeningURL)
            {
                this.Close();
                return;
            }
            DialogResult dr = MessageBox.Show("設定已變更, 儲存後必須重新啟動程式以套用新設定。\n是否儲存?", "問題", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
                string path = Path.Combine(Environment.CurrentDirectory, "Setup.config");
                //if (File.Exists(path))
                //    File.Delete(path);

                XmlHelper h = new XmlHelper("<Setup/>");
                h.AddElement(".", "GreeningAccessPoint", txtGreening.Text);
                h.AddElement(".", "ModuleAccessPoint", txtModule.Text);
                h.GetElement(".").OwnerDocument.Save(path);

                if (SetupChanged != null)
                    SetupChanged.Invoke(this, e);
                else
                    MessageBox.Show("儲存完畢", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            this.Close();
        }
Esempio n. 21
0
        public EmailService()
        {
            InitializeComponent();

            string currentPath = GetType().Assembly.Location;
            currentPath = currentPath.Substring(0, currentPath.LastIndexOf(@"\")) + "\\";

            string actionConfig = currentPath + "ActionConfig.xml";
            if (!File.Exists(actionConfig))
            {
                _log.Fatal(string.Format("配置文件:{0} 不存在", actionConfig));
            }

            _xmlHelper = new XmlHelper(actionConfig);
            string hourMinute = _xmlHelper.GetAttrValue("DoTime", "Value");

            _doDllStr = _xmlHelper.GetAttrValue("DoAction", "Dll");
            _doDllActionStr = _xmlHelper.GetAttrValue("DoAction", "Action");

            try
            {
                _intHour = Convert.ToInt32(hourMinute.Split(':')[0]);
                _intMinute = Convert.ToInt32(hourMinute.Split(':')[1]);
            }
            catch (Exception ex)
            {
                _log.Fatal(ex.Message);
            }
        }
 public XmlElement Output()
 {
     XmlHelper h = new XmlHelper("<Converter />");
     h.SetAttribute(".", "Name", this.Name);
     h.SetAttribute(".", "Type", this.Type);
     h.AddElement(".", "Key", this.Key);
     return h.GetElement(".");
 }
Esempio n. 23
0
 public void ReadXml(XmlReader reader) {
     var xml = new XmlHelper(reader);
     KillsYesterday = xml.deserializeRowSet<CharacterEntry>("KillsYesterday");
     KillsLastWeek = xml.deserializeRowSet<CharacterEntry>("KillsLastWeek");
     KillsTotal = xml.deserializeRowSet<CharacterEntry>("KillsTotal");
     VictoryPointsYesterday = xml.deserializeRowSet<CharacterEntry>("VictoryPointsYesterday");
     VictoryPointsLastWeek = xml.deserializeRowSet<CharacterEntry>("VictoryPointsLastWeek");
     VictoryPointsTotal = xml.deserializeRowSet<CharacterEntry>("VictoryPointsTotal");
 }
Esempio n. 24
0
        internal void DeleteContract(string contractName)
        {
            XmlHelper h = new XmlHelper();
            h.AddElement(".", "ContractName", contractName);

            Parent.SendRequest("UDSManagerService.DeleteContract", new Envelope(h));

            LeaveProject(contractName);
        }
 private void FilterConditionForm_Load(object sender, EventArgs e)
 {
     cboFields.Items.Clear();
     cboFields.Items.Add(string.Empty);
     XmlHelper h = new XmlHelper(_editForm.Table.GetContent());
     foreach (XmlElement field in h.GetElements("Field"))
         cboFields.Items.Add(field.GetAttribute("Name"));
     txtCondition.Document.LoadLanguageFromXml(Assembly.GetExecutingAssembly().GetManifestResourceStream("ProjectManager.ActiproSoftware.SQL.xml"), 0);
 }
Esempio n. 26
0
 public System.Xml.XmlElement GetXml()
 {
     UUIDVariableEditor editor = this.Editor as UUIDVariableEditor;
     XmlHelper h = new XmlHelper("<Variable/>");
     h.SetAttribute(".", "Name", editor.VariableName);
     h.SetAttribute(".", "Source", this.Source);
     //h.SetAttribute(".", "Key", editor.VariableKey);
     return h.GetElement(".");
 }
 public void Initialize(string serviceFullName, System.Xml.XmlElement source)
 {
     XmlHelper h = new XmlHelper(source);
     this.txtServiceAction.Text = h.GetText("Action");
     this.txtServiceName.Text = serviceFullName;
               
     this.txtDefinition.Text = source.OuterXml;
     _original = this.txtDefinition.Text;
 }
        public XmlElement GetSample()
        {
            XmlHelper h = new XmlHelper("<Converter />");
            h.SetAttribute(".", "Name", this.Name);
            h.SetAttribute(".", "Type", this.Type);

            h.AddElement(".", "Key", "decode_key");

            return h.GetElement(".");
        }
Esempio n. 29
0
        public static void AddService(string contractName, string packageName, ServiceEntity service)
        {
            XmlHelper req = new XmlHelper();
            req.AddElement(".", "ContractName", contractName);
            req.AddElement(".", "PackageName", packageName);
            req.AddElement(".", service.GetServiceXml());
         
            MainForm.CurrentProject.SendRequest("UDSManagerService.CreateService", new Envelope(req));

        }
 private void btnOK_Click(object sender, EventArgs e)
 {
     XmlHelper h = new XmlHelper();
     h.AddElement(".", "UsePassport", rbPassport.Checked.ToString());
     h.AddElement(".", "User", txtUser.Text);
     h.AddElement(".", "Password", txtPwd.Text);
     h.AddElement(".", "Auth", txtProvider.Text);
     MainForm.Storage.SetPropertyXml("ServiceTestTemp", _contractUniqName, h.GetElement("."));
     this.Hide();
 }
Esempio n. 31
0
File: Text.cs Progetto: wllefeb/npoi
 internal void Write(StreamWriter sw, string nodeName)
 {
     sw.Write(string.Format("<a:{0}", nodeName));
     XmlHelper.WriteAttribute(sw, "rot", this.rot);
     XmlHelper.WriteAttribute(sw, "spcFirstLastPara", this.spcFirstLastPara);
     XmlHelper.WriteAttribute(sw, "vertOverflow", this.vertOverflow.ToString());
     XmlHelper.WriteAttribute(sw, "horzOverflow", this.horzOverflow.ToString());
     if (this.vert != ST_TextVerticalType.horz)
     {
         XmlHelper.WriteAttribute(sw, "vert", this.vert.ToString());
     }
     if (this.wrap != ST_TextWrappingType.none)
     {
         XmlHelper.WriteAttribute(sw, "wrap", this.wrap.ToString());
     }
     XmlHelper.WriteAttribute(sw, "lIns", this.lIns);
     XmlHelper.WriteAttribute(sw, "tIns", this.tIns);
     XmlHelper.WriteAttribute(sw, "rIns", this.rIns);
     XmlHelper.WriteAttribute(sw, "bIns", this.bIns);
     XmlHelper.WriteAttribute(sw, "numCol", this.numCol);
     XmlHelper.WriteAttribute(sw, "spcCol", this.spcCol);
     XmlHelper.WriteAttribute(sw, "rtlCol", this.rtlCol);
     XmlHelper.WriteAttribute(sw, "fromWordArt", this.fromWordArt, false);
     XmlHelper.WriteAttribute(sw, "anchor", this.anchor.ToString());
     XmlHelper.WriteAttribute(sw, "anchorCtr", this.anchorCtr, false);
     XmlHelper.WriteAttribute(sw, "forceAA", this.forceAA, false);
     XmlHelper.WriteAttribute(sw, "upright", this.upright);
     XmlHelper.WriteAttribute(sw, "compatLnSpc", this.compatLnSpc);
     sw.Write(">");
     if (this.prstTxWarp != null)
     {
         this.prstTxWarp.Write(sw, "prstTxWarp");
     }
     if (this.noAutofit != null)
     {
         sw.Write("<a:noAutofit/>");
     }
     if (this.normAutofit != null)
     {
         this.normAutofit.Write(sw, "normAutofit");
     }
     if (this.spAutoFit != null)
     {
         sw.Write("<a:spAutoFit/>");
     }
     if (this.scene3d != null)
     {
         this.scene3d.Write(sw, "scene3d");
     }
     if (this.sp3d != null)
     {
         this.sp3d.Write(sw, "sp3d");
     }
     if (this.flatTx != null)
     {
         this.flatTx.Write(sw, "flatTx");
     }
     if (this.extLst != null)
     {
         this.extLst.Write(sw, "extLst");
     }
     sw.Write(string.Format("</a:{0}>", nodeName));
 }
Esempio n. 32
0
        public static EntityMetadata DeSerialiseEntityMetadata(EntityMetadata item, XmlNode entity)
        {
            foreach (XmlNode node in entity.ChildNodes)
            {
                Dictionary <string, object> itemValues = (Dictionary <string, object>)(object) item;
                string localName = XmlHelper.GetLocalName(node);
                string fieldName = localName.Substr(0, 1).ToLowerCase() + localName.Substr(1); // This converts to camel case so we can use the import types from script#

                // Check nil and don't set the value to save time/space
                if (node.Attributes.Count == 1 && node.Attributes[0].Name == "i:nil")
                {
                    continue;
                }
                switch (localName)
                {
                // String values
                case "IconLargeName":
                case "IconMediumName":
                case "IconSmallName":
                case "LogicalName":
                case "PrimaryIdAttribute":
                case "PrimaryNameAttribute":
                case "RecurrenceBaseEntityLogicalName":
                case "ReportViewName":
                case "SchemaName":
                case "PrimaryImageAttribute":
                    itemValues[fieldName] = XmlHelper.GetNodeTextValue(node);
                    break;

                // Bool values
                case "AutoRouteToOwnerQueue":
                case "CanBeInManyToMany":
                case "CanBePrimaryEntityInRelationship":
                case "CanBeRelatedEntityInRelationship":
                case "CanCreateAttributes":
                case "CanCreateCharts":
                case "CanCreateForms":
                case "CanCreateViews":
                case "CanModifyAdditionalSettings":
                case "CanTriggerWorkflow":
                case "IsActivity":
                case "IsActivityParty":
                case "IsAuditEnabled":
                case "IsAvailableOffline":
                case "IsChildEntity":
                case "IsConnectionsEnabled":
                case "IsCustomEntity":
                case "IsCustomizable":
                case "IsDocumentManagementEnabled":
                case "IsDuplicateDetectionEnabled":
                case "IsEnabledForCharts":
                case "IsImportable":
                case "IsIntersect":
                case "IsMailMergeEnabled":
                case "IsManaged":
                case "IsReadingPaneEnabled":
                case "IsRenameable":
                case "IsValidForAdvancedFind":
                case "IsValidForQueue":
                case "IsVisibleInMobile":
                    itemValues[fieldName] = Attribute.DeSerialise(node, AttributeTypes.Boolean_);
                    break;

                // Int Values
                case "ActivityTypeMask":
                case "ObjectTypeCode":
                    itemValues[fieldName] = Attribute.DeSerialise(node, AttributeTypes.Int_);
                    break;

                case "Attributes":
                    item.Attributes = new List <AttributeMetadata>();
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        AttributeMetadata a = new AttributeMetadata();
                        item.Attributes.Add(MetadataSerialiser.DeSerialiseAttributeMetadata(a, childNode));
                    }
                    break;

                ////Label
                case "Description":
                case "DisplayCollectionName":
                case "DisplayName":
                    Label label = new Label();
                    itemValues[fieldName] = MetadataSerialiser.DeSerialiseLabel(label, node);
                    break;
                }
            }
            return(item);
        }
        /// <summary>
        /// Save values into xml string
        /// </summary>
        /// <returns>xml string value</returns>
        public string ToXmlTag()
        {
            var optionsLine = new StringBuilder();

            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.NAMESPACETAG, this.NameSpace));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.COLLECTIONTAG, this.CollectionObjectType.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.CODETYPETAG, this.Language.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLEDATABINDINGTAG, this.EnableDataBinding.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLELAZYLOADINGTAG, this.PropertyParams.EnableLazyLoading.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLETRACKINGCHANGESTAG, this.TrackingChanges.Enabled.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATETRACKINGCLASSESTAG, this.TrackingChanges.GenerateTrackingClasses.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.HIDEPRIVATEFIELDTAG, this.Miscellaneous.HidePrivateFieldInIde.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLESUMMARYCOMMENTTAG, this.Miscellaneous.EnableSummaryComment.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLEVIRTUALPROPERTIESTAG, this.PropertyParams.EnableVirtualProperties.ToString()));

            if (!string.IsNullOrEmpty(this.CollectionBase))
            {
                optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.COLLECTIONBASETAG, this.CollectionBase));
            }

            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.INCLUDESERIALIZEMETHODTAG, this.Serialization.Enabled.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.USEGENERICBASECLASSTAG, this.GenericBaseClass.Enabled.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATEBASECLASSTAG, this.GenericBaseClass.GenerateBaseClass.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATECLONEMETHODTAG, this.GenerateCloneMethod.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATEDATACONTRACTSTAG, this.GenerateDataContracts.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.CODEBASETAG, this.TargetFramework.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.SERIALIZEMETHODNAMETAG, this.Serialization.SerializeMethodName));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.DESERIALIZEMETHODNAMETAG, this.Serialization.DeserializeMethodName));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.SAVETOFILEMETHODNAMETAG, this.Serialization.SaveToFileMethodName));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.LOADFROMFILEMETHODNAMETAG, this.Serialization.LoadFromFileMethodName));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATEXMLATTRIBUTESTAG, this.Serialization.GenerateXmlAttributes.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ORDERXMLATTRIBUTETAG, this.Serialization.GenerateOrderXmlAttributes.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLEENCODINGTAG, this.Serialization.EnableEncoding.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.AUTOMATICPROPERTIESTAG, this.PropertyParams.AutomaticProperties.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATESHOULDSERIALIZETAG, this.PropertyParams.GenerateShouldSerializeProperty.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.DISABLEDEBUGTAG, this.Miscellaneous.DisableDebug.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.GENERATEPROPERTYNAMESPECIFIEDTAG, this.PropertyParams.GeneratePropertyNameSpecified.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.DEFAULTENCODERTAG, this.Serialization.DefaultEncoder.ToString()));

            var customUsingsStr = new StringBuilder();

            if (this.CustomUsings != null)
            {
                foreach (NamespaceParam usingStr in this.CustomUsings.Where(usingStr => usingStr.NameSpace.Length > 0))
                {
                    customUsingsStr.Append(usingStr.NameSpace + ";");
                }

                // remove last ";"
                if (customUsingsStr.Length > 0)
                {
                    if (customUsingsStr[customUsingsStr.Length - 1] == ';')
                    {
                        customUsingsStr = customUsingsStr.Remove(customUsingsStr.Length - 1, 1);
                    }
                }

                optionsLine.Append(XmlHelper.InsertXMLFromStr(
                                       GeneratorContext.CUSTOMUSINGSTAG,
                                       customUsingsStr.ToString()));
            }

            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.EXCLUDEINCLUDEDTYPESTAG, this.Miscellaneous.ExcludeIncludedTypes.ToString()));
            optionsLine.Append(XmlHelper.InsertXMLFromStr(GeneratorContext.ENABLEINITIALIZEFIELDSTAG, this.EnableInitializeFields.ToString()));

            return(optionsLine.ToString());
        }
Esempio n. 34
0
 public ShelfInquiryBll()
 {
     dal = new ShelfInquiryDal();
     xml = new XmlHelper();
 }
Esempio n. 35
0
 /// <summary>
 /// 修改插件节点数据
 /// </summary>
 public bool UpdateNodeValue(string dirPath, string xPath, string value)
 {
     return(XmlHelper.UpdateNodeInnerText(dirPath + DTKeys.FILE_PLUGIN_XML_CONFING, xPath, value));
 }
Esempio n. 36
0
        private void ExecuteSQL()
        {
            string text = txtSQL.Text;

            if (!string.IsNullOrWhiteSpace(txtSQL.SelectedView.SelectedText))
            {
                text = txtSQL.SelectedView.SelectedText;
            }

            text = text.Trim();
            string[] sqls = text.Split(";\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (sqls.Length == 0)
            {
                return;
            }

            List <string> commands = new List <string>();
            List <string> querys   = new List <string>();
            string        lastSQL  = sqls[sqls.Length - 1];

            foreach (string sql in sqls)
            {
                if (sql.StartsWith("select", StringComparison.CurrentCultureIgnoreCase))
                {
                    querys.Add(sql);
                }
                else
                {
                    commands.Add(sql);
                }
            }

            StringBuilder sb         = new StringBuilder();
            Envelope      env        = null;
            bool          showSelect = false;
            bool          occurError = false;
            long          t1         = System.Environment.TickCount;

            if (commands.Count > 0)
            {
                sb.Append("執行 ").Append(commands.Count).Append(" Command\n");

                XmlHelper req = new XmlHelper();
                foreach (string sql in commands)
                {
                    XmlElement      xml     = req.AddElement(".", "Command");
                    XmlCDataSection section = xml.OwnerDocument.CreateCDataSection(sql);
                    xml.AppendChild(section);
                }
                try
                {
                    env = MainForm.CurrentProject.SendRequest("UDTService.DML.Command", new Envelope(req));
                }
                catch (Exception ex)
                {
                    sb.Append("執行 Commands 時發生錯誤.\n").Append(ex.Message).Append("\n");
                    occurError = true;
                }
            }

            if (lastSQL.StartsWith("select", StringComparison.CurrentCultureIgnoreCase))
            {
                sb.Append("執行 SQL Query : ").Append(lastSQL).Append("\n");

                XmlHelper       req     = new XmlHelper();
                XmlElement      xml     = req.AddElement("SQL");
                XmlCDataSection section = xml.OwnerDocument.CreateCDataSection(lastSQL);
                xml.AppendChild(section);

                try
                {
                    env = MainForm.CurrentProject.SendRequest("UDTService.DML.Query", new Envelope(req));
                }
                catch (Exception ex)
                {
                    sb.Append("執行 Query 時發生錯誤.\n").Append(ex.Message).Append("\n");
                    occurError = true;
                }
                showSelect = true;
            }
            long t2 = System.Environment.TickCount;

            tsLabel.Text = "執行時間 : " + (t2 - t1) + "ms";

            dgResult.Rows.Clear();
            dgResult.Columns.Clear();

            if (!occurError)
            {
                XmlHelper rsp = new XmlHelper(env.Body);
                if (showSelect)
                {
                    foreach (XmlElement col in rsp.GetElements("Metadata/Column"))
                    {
                        dgResult.Columns.Add("col" + col.GetAttribute("Index"), col.GetAttribute("Field"));
                    }

                    foreach (XmlElement record in rsp.GetElements("Record"))
                    {
                        int             rowIndex = dgResult.Rows.Add();
                        DataGridViewRow row      = dgResult.Rows[rowIndex];

                        XmlHelper h = new XmlHelper(record);
                        foreach (XmlElement col in h.GetElements("Column"))
                        {
                            string columnName = "col" + col.GetAttribute("Index");
                            string value      = col.InnerText;
                            row.Cells[columnName].Value = value;
                        }
                    }
                }
                else
                {
                    dgResult.Columns.Add("colResult", "Result");
                    dgResult.Rows.Add();
                    dgResult.Rows[0].Cells["colResult"].Value = rsp.TryGetInteger("Update", 0);
                }
            }
            txtInfo.Text = sb.ToString();

            if (occurError)
            {
                tabControl1.SelectedTab = tpInfo;
            }
            else
            {
                tabControl1.SelectedTab = tpResult;
            }
        }
        public IEnumerable <KeyValuePair <string, IEnumerable <object?> > > GetIndexValues(IProperty property, string?culture, string?segment, bool published)
        {
            var result = new List <KeyValuePair <string, IEnumerable <object?> > >();

            var val = property.GetValue(culture, segment, published);

            //if there is a value, it's a string and it's detected as json
            if (val is string rawVal && rawVal.DetectIsJson())
            {
                try
                {
                    GridValue?gridVal = JsonConvert.DeserializeObject <GridValue>(rawVal);

                    //get all values and put them into a single field (using JsonPath)
                    var sb = new StringBuilder();
                    foreach (GridValue.GridRow row in gridVal !.Sections.SelectMany(x => x.Rows))
                    {
                        var rowName = row.Name;

                        foreach (GridValue.GridControl control in row.Areas.SelectMany(x => x.Controls))
                        {
                            JToken?controlVal = control.Value;

                            if (controlVal?.Type == JTokenType.String)
                            {
                                var str = controlVal.Value <string>();
                                str = XmlHelper.CouldItBeXml(str) ? str !.StripHtml() : str;
                                sb.Append(str);
                                sb.Append(" ");

                                //add the row name as an individual field
                                result.Add(new KeyValuePair <string, IEnumerable <object?> >($"{property.Alias}.{rowName}", new[] { str }));
                            }
                            else if (controlVal is JContainer jc)
                            {
                                foreach (JToken s in jc.Descendants().Where(t => t.Type == JTokenType.String))
                                {
                                    sb.Append(s.Value <string>());
                                    sb.Append(" ");
                                }
                            }
                        }
                    }

                    //First save the raw value to a raw field
                    result.Add(new KeyValuePair <string, IEnumerable <object?> >($"{UmbracoExamineFieldNames.RawFieldPrefix}{property.Alias}", new[] { rawVal }));

                    if (sb.Length > 0)
                    {
                        //index the property with the combined/cleaned value
                        result.Add(new KeyValuePair <string, IEnumerable <object?> >(property.Alias, new[] { sb.ToString() }));
                    }
                }
                catch (InvalidCastException)
                {
                    //swallow...on purpose, there's a chance that this isn't the json format we are looking for
                    // and we don't want that to affect the website.
                }
                catch (JsonException)
                {
                    //swallow...on purpose, there's a chance that this isn't json and we don't want that to affect
                    // the website.
                }
                catch (ArgumentException)
                {
                    //swallow on purpose to prevent this error:
                    // Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.
                }
            }

            return(result);
        }
Esempio n. 38
0
 public void AttachToXmlNode(ref XmlElement node)
 {
     XmlHelper.AddNode((object)this.Name, "Name", ref node);
 }
 /// <summary>
 /// this function  reads settings from xml stream
 /// </summary>
 /// <param name="settings">XmlReader stream</param>
 protected void CommonReadSettings(XmlReader settings)
 {
     RegisterOrderIn32mode = (RegisterOrderEnum)XmlHelper.ReadStandardIntegerValue(settings, m_Tag_RegisterOrderIn32mode);
     FloatingPoint         = (FloatingPointType)XmlHelper.ReadStandardIntegerValue(settings, m_Tag_FloatingPoint);
 }
 /// <summary>
 /// this function  writes settings to xml stream
 /// </summary>
 /// <param name="pSettings">XmlWriter stream</param>
 protected void CommonWriteSettings(XmlWriter pSettings)
 {
     XmlHelper.WriteStandardIntegerVale(pSettings, m_Tag_RegisterOrderIn32mode, (int)RegisterOrderIn32mode);
     XmlHelper.WriteStandardIntegerVale(pSettings, m_Tag_FloatingPoint, (int)FloatingPoint);
 }
 /// <summary>
 /// Applies the <paramref name="transformer"/> to all formulas in the <see cref="ExcelConditionalFormattingCollection"/>.
 /// </summary>
 /// <param name="transformer">The transformation to apply.</param>
 public virtual void TransformFormulaReferences(Func <string, string> transformer)
 {
     XmlHelper.TransformValuesInNode(this.TopNode, this.NameSpaceManager, transformer, ".//d:conditionalFormatting//d:formula");
     XmlHelper.TransformAttributesInNode(this.TopNode, this.NameSpaceManager, transformer, ".//d:conditionalFormatting//d:cfvo", Attributes.Val);
 }
        public string GetTestTypeTest(string type, string fullname, string runstate)
        {
            TestNode testNode = new TestNode(XmlHelper.CreateXmlNode(string.Format("<test-run id='1' type='{0}' fullname='{1}' runstate='{2}'><test-suite id='42'/></test-run>", type, fullname, runstate)));

            return(TestPropertiesPresenter.GetTestType(testNode));
        }
Esempio n. 43
0
 protected internal override void CreateNodes(XmlHelper helper, string path)
 {
     throw new NotImplementedException();
 }
Esempio n. 44
0
File: Text.cs Progetto: wllefeb/npoi
        public static CT_TextBodyProperties Parse(XmlNode node, XmlNamespaceManager namespaceManager)
        {
            if (node == null)
            {
                return(null);
            }
            CT_TextBodyProperties ctObj = new CT_TextBodyProperties();

            ctObj.rot = XmlHelper.ReadInt(node.Attributes["rot"]);
            ctObj.spcFirstLastPara = XmlHelper.ReadBool(node.Attributes["spcFirstLastPara"]);
            if (node.Attributes["vertOverflow"] != null)
            {
                ctObj.vertOverflow = (ST_TextVertOverflowType)Enum.Parse(typeof(ST_TextVertOverflowType), node.Attributes["vertOverflow"].Value);
            }
            if (node.Attributes["horzOverflow"] != null)
            {
                ctObj.horzOverflow = (ST_TextHorzOverflowType)Enum.Parse(typeof(ST_TextHorzOverflowType), node.Attributes["horzOverflow"].Value);
            }
            if (node.Attributes["vert"] != null)
            {
                ctObj.vert = (ST_TextVerticalType)Enum.Parse(typeof(ST_TextVerticalType), node.Attributes["vert"].Value);
            }
            if (node.Attributes["wrap"] != null)
            {
                ctObj.wrap = (ST_TextWrappingType)Enum.Parse(typeof(ST_TextWrappingType), node.Attributes["wrap"].Value);
            }
            ctObj.lIns        = XmlHelper.ReadInt(node.Attributes["lIns"]);
            ctObj.tIns        = XmlHelper.ReadInt(node.Attributes["tIns"]);
            ctObj.rIns        = XmlHelper.ReadInt(node.Attributes["rIns"]);
            ctObj.bIns        = XmlHelper.ReadInt(node.Attributes["bIns"]);
            ctObj.numCol      = XmlHelper.ReadInt(node.Attributes["numCol"]);
            ctObj.spcCol      = XmlHelper.ReadInt(node.Attributes["spcCol"]);
            ctObj.rtlCol      = XmlHelper.ReadBool(node.Attributes["rtlCol"]);
            ctObj.fromWordArt = XmlHelper.ReadBool(node.Attributes["fromWordArt"]);
            if (node.Attributes["anchor"] != null)
            {
                ctObj.anchor = (ST_TextAnchoringType)Enum.Parse(typeof(ST_TextAnchoringType), node.Attributes["anchor"].Value);
            }
            ctObj.anchorCtr   = XmlHelper.ReadBool(node.Attributes["anchorCtr"]);
            ctObj.forceAA     = XmlHelper.ReadBool(node.Attributes["forceAA"]);
            ctObj.upright     = XmlHelper.ReadBool(node.Attributes["upright"]);
            ctObj.compatLnSpc = XmlHelper.ReadBool(node.Attributes["compatLnSpc"]);
            foreach (XmlNode childNode in node.ChildNodes)
            {
                if (childNode.LocalName == "prstTxWarp")
                {
                    ctObj.prstTxWarp = CT_PresetTextShape.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "noAutofit")
                {
                    ctObj.noAutofit = new CT_TextNoAutofit();
                }
                else if (childNode.LocalName == "normAutofit")
                {
                    ctObj.normAutofit = CT_TextNormalAutofit.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "spAutoFit")
                {
                    ctObj.spAutoFit = new CT_TextShapeAutofit();
                }
                else if (childNode.LocalName == "scene3d")
                {
                    ctObj.scene3d = CT_Scene3D.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "sp3d")
                {
                    ctObj.sp3d = CT_Shape3D.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "flatTx")
                {
                    ctObj.flatTx = CT_FlatText.Parse(childNode, namespaceManager);
                }
                else if (childNode.LocalName == "extLst")
                {
                    ctObj.extLst = CT_OfficeArtExtensionList.Parse(childNode, namespaceManager);
                }
            }
            return(ctObj);
        }
Esempio n. 45
0
        private bool SerializeTypeCodeValue(object value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet <object> objectsInPath, int depth)
        {
            TypeCode objTypeCode = Convert.GetTypeCode(value);

            if (objTypeCode == TypeCode.Object)
            {
                if (value is Guid || value is TimeSpan || value is MemberInfo || value is Assembly)
                {
                    //object without property, to string
                    QuoteValue(destination, Convert.ToString(value, CultureInfo.InvariantCulture));
                }
                else if (value is DateTimeOffset)
                {
                    QuoteValue(destination, $"{value:yyyy-MM-dd HH:mm:ss zzz}");
                }
                else
                {
                    int originalLength = destination.Length;
                    if (originalLength > MaxJsonLength)
                    {
                        return(false);
                    }

                    try
                    {
                        if (value is Exception && ReferenceEquals(options, instance._serializeOptions))
                        {
                            // Exceptions are seldom under control, and can include random Data-Dictionary-keys, so we sanitize by default
                            options = instance._exceptionSerializeOptions;
                        }

                        using (new SingleItemOptimizedHashSet <object> .SingleItemScopedInsert(value, ref objectsInPath, false))
                        {
                            return(SerializeProperties(value, destination, options, objectsInPath, depth));
                        }
                    }
                    catch
                    {
                        //nothing to add, so return is OK
                        destination.Length = originalLength;
                        return(false);
                    }
                }
            }
            else
            {
                if (IsNumericTypeCode(objTypeCode, false))
                {
                    SerializeNumber(value, destination, options, objTypeCode);
                }
                else
                {
                    string str = XmlHelper.XmlConvertToString(value, objTypeCode);
                    if (str == null)
                    {
                        return(false);
                    }
                    if (SkipQuotes(objTypeCode))
                    {
                        destination.Append(str);
                    }
                    else
                    {
                        QuoteValue(destination, str);
                    }
                }
            }

            return(true);
        }
Esempio n. 46
0
        public void TestSerialize()
        {
            var result = XmlHelper.Serialize(base.personProperCollection);

            base.Consumer.Consume(result);
        }
 /// <summary>
 /// Convert StatusScanResult object from xml
 /// </summary>
 /// <param name="xml"></param>
 /// <returns></returns>
 public static StatusScanResult FromXml(string xml)
 {
     return(XmlHelper.ParseStatusScanResult(xml));
 }
Esempio n. 48
0
        public static bool SaveCurrentLog(bool isTemporary = true)
        {
            if (!isTemporary)
            {
            }

            if (AppViewModel.Instance.ChatHistory.Any())
            {
                try {
                    // setup common save logs info
                    var savedTextLogName  = $"{DateTime.Now:yyyy_MM_dd_HH.mm.ss}.txt";
                    var savedSayBuilder   = new StringBuilder();
                    var savedShoutBuilder = new StringBuilder();
                    var savedPartyBuilder = new StringBuilder();
                    var savedTellBuilder  = new StringBuilder();
                    var savedLS1Builder   = new StringBuilder();
                    var savedLS2Builder   = new StringBuilder();
                    var savedLS3Builder   = new StringBuilder();
                    var savedLS4Builder   = new StringBuilder();
                    var savedLS5Builder   = new StringBuilder();
                    var savedLS6Builder   = new StringBuilder();
                    var savedLS7Builder   = new StringBuilder();
                    var savedLS8Builder   = new StringBuilder();
                    var savedFCBuilder    = new StringBuilder();
                    var savedYellBuilder  = new StringBuilder();

                    // setup full chatlog xml file
                    var       savedLogName = $"{DateTime.Now:yyyy_MM_dd_HH.mm.ss}_ChatHistory.xml";
                    XDocument savedLog     = ResourceHelper.XDocResource(Constants.AppPack + "Defaults/ChatHistory.xml");
                    foreach (ChatLogItem entry in AppViewModel.Instance.ChatHistory)
                    {
                        // process text logging
                        try {
                            if (Settings.Default.SaveLog)
                            {
                                switch (entry.Code)
                                {
                                case "000A":
                                    savedSayBuilder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "000B":
                                    savedShoutBuilder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "000E":
                                    savedPartyBuilder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "000C":
                                case "000D":
                                    savedTellBuilder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0010":
                                    savedLS1Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0011":
                                    savedLS2Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0012":
                                    savedLS3Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0013":
                                    savedLS4Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0014":
                                    savedLS5Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0015":
                                    savedLS6Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0016":
                                    savedLS7Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0017":
                                    savedLS8Builder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "0018":
                                    savedFCBuilder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;

                                case "001E":
                                    savedYellBuilder.AppendLine($"{entry.TimeStamp} {entry.Line}");
                                    break;
                                }
                            }
                        }
                        catch (Exception ex) {
                            Logging.Log(Logger, new LogItem(ex, true));
                        }

                        // process xml log
                        try {
                            var xCode  = entry.Code;
                            var xBytes = entry.Bytes.Aggregate(string.Empty, (current, bytes) => current + bytes + " ").Trim();

                            // var xCombined = entry.Combined;
                            // var xJP = entry.JP.ToString();
                            var xLine = entry.Line;

                            // var xRaw = entry.Raw;
                            var xTimeStamp = entry.TimeStamp.ToString("[HH:mm:ss]");
                            List <XValuePair> keyPairList = new List <XValuePair>();
                            keyPairList.Add(
                                new XValuePair {
                                Key   = "Bytes",
                                Value = xBytes,
                            });

                            // keyPairList.Add(new XValuePair {Key = "Combined", Value = xCombined});
                            // keyPairList.Add(new XValuePair {Key = "JP", Value = xJP});
                            keyPairList.Add(
                                new XValuePair {
                                Key   = "Line",
                                Value = xLine,
                            });

                            // keyPairList.Add(new XValuePair {Key = "Raw", Value = xRaw});
                            keyPairList.Add(
                                new XValuePair {
                                Key   = "TimeStamp",
                                Value = xTimeStamp,
                            });
                            XmlHelper.SaveXmlNode(savedLog, "History", "Entry", xCode, keyPairList);
                        }
                        catch (Exception ex) {
                            Logging.Log(Logger, new LogItem(ex, true));
                        }
                    }

                    // save text logs
                    if (Settings.Default.SaveLog)
                    {
                        try {
                            if (savedSayBuilder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "Say", savedTextLogName);
                                File.WriteAllText(path, savedSayBuilder.ToString());
                            }

                            if (savedShoutBuilder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "Shout", savedTextLogName);
                                File.WriteAllText(path, savedShoutBuilder.ToString());
                            }

                            if (savedPartyBuilder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "Party", savedTextLogName);
                                File.WriteAllText(path, savedPartyBuilder.ToString());
                            }

                            if (savedTellBuilder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "Tell", savedTextLogName);
                                File.WriteAllText(path, savedTellBuilder.ToString());
                            }

                            if (savedLS1Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS1", savedTextLogName);
                                File.WriteAllText(path, savedLS1Builder.ToString());
                            }

                            if (savedLS2Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS2", savedTextLogName);
                                File.WriteAllText(path, savedLS2Builder.ToString());
                            }

                            if (savedLS3Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS3", savedTextLogName);
                                File.WriteAllText(path, savedLS3Builder.ToString());
                            }

                            if (savedLS4Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS4", savedTextLogName);
                                File.WriteAllText(path, savedLS4Builder.ToString());
                            }

                            if (savedLS5Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS5", savedTextLogName);
                                File.WriteAllText(path, savedLS5Builder.ToString());
                            }

                            if (savedLS6Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS6", savedTextLogName);
                                File.WriteAllText(path, savedLS6Builder.ToString());
                            }

                            if (savedLS7Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS7", savedTextLogName);
                                File.WriteAllText(path, savedLS7Builder.ToString());
                            }

                            if (savedLS8Builder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "LS8", savedTextLogName);
                                File.WriteAllText(path, savedLS8Builder.ToString());
                            }

                            if (savedFCBuilder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "FC", savedTextLogName);
                                File.WriteAllText(path, savedFCBuilder.ToString());
                            }

                            if (savedYellBuilder.Length > 0)
                            {
                                var path = Path.Combine(AppViewModel.Instance.LogsPath, "Yell", savedTextLogName);
                                File.WriteAllText(path, savedYellBuilder.ToString());
                            }
                        }
                        catch (Exception ex) {
                            Logging.Log(Logger, new LogItem(ex, true));
                        }
                    }

                    // save xml log
                    try {
                        savedLog.Save(Path.Combine(AppViewModel.Instance.LogsPath, savedLogName));
                    }
                    catch (Exception ex) {
                        Logging.Log(Logger, new LogItem(ex, true));
                    }
                }
                catch (Exception ex) {
                    Logging.Log(Logger, new LogItem(ex, true));
                }
            }

            if (!isTemporary)
            {
                return(true);
            }

            AppViewModel.Instance.ChatHistory.Clear();
            return(true);
        }
Esempio n. 49
0
        /// <summary>
        /// 删除URL映射节点
        /// </summary>
        public bool RemoveNodes(string dirPath, string xPath)
        {
            XmlNodeList xnList = XmlHelper.ReadNodes(dirPath + DTKeys.FILE_PLUGIN_XML_CONFING, xPath);

            return(new url_rewrite().Remove(xnList));
        }
Esempio n. 50
0
 internal void Write(StreamWriter sw, string nodeName)
 {
     sw.Write(string.Format("<a:{0}", nodeName));
     XmlHelper.WriteAttribute(sw, "val", this.val, true);
     sw.Write("/>");
 }
Esempio n. 51
0
 public static void Store <TProperty>(this Element element, string name, TProperty value)
 {
     element.Data[name] = XmlHelper.ToString(value);
 }
Esempio n. 52
0
        private void DataConnectList_Load(object sender, EventArgs e)
        {
            oper = new XmlHelper(string.Format("{0}{1}", Application.StartupPath, dataSetConfigPath), XmlType.Path);

            RefreshList();
        }
Esempio n. 53
0
        public void TestDeserialize()
        {
            var result = XmlHelper.Deserialize <PersonCollection <PersonProper> >(_xml);

            base.Consumer.Consume(result);
        }
        private void LoadInternal(ref XmlHelper xh)
        {
            XmlNode sbc = xh.m_toplevel;

            dpmmX = xh.GetDouble(sbc, "DotsPermmX", 102.4);
            dpmmY = xh.GetDouble(sbc, "DotsPermmY", 76.8);
            xres  = xh.GetInt(sbc, "XResolution", 1024);
            yres  = xh.GetInt(sbc, "YResolution", 768);
            //ZThick = xh.GetDouble(sbc, "SliceHeight", 0.05);
            //layertime_ms = xh.GetInt(sbc, "LayerTime", 1000); // 1 second default
            //firstlayertime_ms = xh.GetInt(sbc, "FirstLayerTime", 5000);
            blanktime_ms = xh.GetInt(sbc, "BlankTime", 2000); // 2 seconds blank
            plat_temp    = xh.GetInt(sbc, "PlatformTemp", 75);
            //exportgcode = xh.GetBool(sbc, "ExportGCode"));

            exportsvg = xh.GetInt(sbc, "ExportSVG", 0); // the problem is this was previously a boolean variable

            if ((exportsvg < 0) || (exportsvg > 4))
            {
                exportsvg = 0;
            }
            export    = xh.GetBool(sbc, "Export", false);;
            exportpng = xh.GetBool(sbc, "ExportPNG", false);;

            XOffset = xh.GetInt(sbc, "XOffset", 0);
            YOffset = xh.GetInt(sbc, "YOffset", 0);
            //numfirstlayers = xh.GetInt(sbc, "NumberofBottomLayers", 3);
            direction        = (eBuildDirection)xh.GetEnum(sbc, "Direction", typeof(eBuildDirection), eBuildDirection.Bottom_Up);
            liftdistance     = xh.GetDouble(sbc, "LiftDistance", 5.0);
            slidetiltval     = xh.GetDouble(sbc, "SlideTiltValue", 0.0);
            antialiasing     = xh.GetBool(sbc, "AntiAliasing", false);
            usemainliftgcode = xh.GetBool(sbc, "UseMainLiftGCode", false);
            aaval            = xh.GetDouble(sbc, "AntiAliasingValue", 1.5);
            liftfeedrate     = xh.GetDouble(sbc, "LiftFeedRate", 50.0);     // 50mm/s
            liftretractrate  = xh.GetDouble(sbc, "LiftRetractRate", 100.0); // 100mm/s
            m_exportopt      = xh.GetString(sbc, "ExportOption", "SUBDIR"); // default to saving in subdirectory
            m_flipX          = xh.GetBool(sbc, "FlipX", false);
            m_flipY          = xh.GetBool(sbc, "FlipY", false);
            m_notes          = xh.GetString(sbc, "Notes", "");
            //m_resinprice = xh.GetDouble(sbc, "ResinPriceL", 0.0);

            m_headercode   = xh.GetString(sbc, "GCodeHeader", DefGCodeHeader());
            m_footercode   = xh.GetString(sbc, "GCodeFooter", DefGCodeFooter());
            m_preslicecode = xh.GetString(sbc, "GCodePreslice", DefGCodePreslice());
            m_liftcode     = xh.GetString(sbc, "GCodeLift", DefGCodeLift());
            selectedInk    = xh.GetString(sbc, "SelectedInk", "Default");
            inks           = new Dictionary <string, InkConfig>();
            List <XmlNode> inkNodes = xh.FindAllChildElement(sbc, "InkConfig");

            foreach (XmlNode xnode in inkNodes)
            {
                string    name = xh.GetString(xnode, "Name", "Default");
                InkConfig ic   = new InkConfig(name);
                ic.Load(xh, xnode);
                inks[name] = ic;
            }
            if (!inks.ContainsKey(selectedInk))
            {
                InkConfig ic = new InkConfig(selectedInk);
                ic.Load(xh, sbc); // try loading legacy settings from parent
                inks[selectedInk] = ic;
            }
            SetCurrentInk(selectedInk);
            minExposure   = xh.GetInt(sbc, "MinTestExposure", 500);
            exposureStep  = xh.GetInt(sbc, "TestExposureStep", 200);
            exportpreview = (PreviewGenerator.ePreview)xh.GetEnum(sbc, "ExportPreview", typeof(PreviewGenerator.ePreview), PreviewGenerator.ePreview.None);
            xh.LoadUserParamList(userParams);
        }
Esempio n. 55
0
        /// <summary>
        /// Gets the mail message as an XML document.
        /// </summary>
        /// <returns></returns>
        public XmlDocument ToXmlDocument()
        {
            // create...
            XmlDocument doc = new XmlDocument();

            // root...
            XmlElement root = doc.CreateElement("MailMessage");

            doc.AppendChild(root);

            // from...
            if (From == null)
            {
                throw new InvalidOperationException("From is null.");
            }
            XmlElement fromElement = doc.CreateElement("From");

            root.AppendChild(fromElement);
            this.From.PopulateXmlElement(fromElement);

            // recipients...
            this.AddRecipientsToXml(root, "To", this.To);
            this.AddRecipientsToXml(root, "Cc", this.Cc);
            this.AddRecipientsToXml(root, "Bcc", this.Bcc);

            if (this.ReplyTo != null)
            {
                var replyToElement = doc.CreateElement("ReplyTo");
                root.AppendChild(replyToElement);
                this.ReplyTo.PopulateXmlElement(replyToElement);
            }

            // basic text stuff...
            XmlHelper.AddElement(root, "Subject", this.Subject);
            XmlHelper.AddElement(root, "Headers", this.Headers);
            XmlHelper.AddElement(root, "MailFormat", this.MailFormat);
            XmlHelper.AddElement(root, "Date", this.Date);

            // body...
            XmlElement bodyElement = doc.CreateElement("Body");

            root.AppendChild(bodyElement);
            bodyElement.AppendChild(doc.CreateCDataSection(this.Body));

            // attachments...
            XmlElement attachmentsElement = doc.CreateElement("Attachments");

            root.AppendChild(attachmentsElement);
            foreach (MailAttachment attachment in this.Attachments)
            {
                XmlElement attachmentElement = doc.CreateElement("Attachment");
                attachmentsElement.AppendChild(attachmentElement);
                attachment.PopulateXmlElement(attachmentElement);
            }

            var embedsElement = root.AddElement("EmbeddedImages");

            foreach (MailEmbeddedImage embed in this.EmbeddedImages)
            {
                var embedElement = embedsElement.AddElement("EmbeddedImage");
                embedElement.AddElement("Name", embed.Name);
                embedElement.AddElement("Data", embed.GetBytesAsBase64String());
                embedElement.AddElement("ContentType", embed.ContentType);
                embedElement.AddElement("ContentId", embed.ContentId);
            }

            // return...
            return(doc);
        }
Esempio n. 56
0
        public override void Setup()
        {
            base.Setup();

            _xml = XmlHelper.Serialize(base.personProperCollection);
        }
Esempio n. 57
0
        public override void XmlLoad(XmlNode node)
        {
            this.Key     = XmlHelper.GetAttributeValue(node, "key", string.Empty);
            _enforce     = XmlHelper.GetAttributeValue(node, "enforce", _def_enforce);
            _description = XmlHelper.GetAttributeValue(node, "description", _def_description);

            _deleteAction = (DeleteActionConstants)Enum.Parse(typeof(DeleteActionConstants), XmlHelper.GetAttributeValue(node, "deleteAction", _def_deleteAction.ToString()));

            var columnRelationshipsNode = node.SelectSingleNode("columnRelationships"); //deprecated, use "crl"

            if (columnRelationshipsNode == null)
            {
                columnRelationshipsNode = node.SelectSingleNode("crl");
            }
            ColumnRelationships.XmlLoad(columnRelationshipsNode);

            var childTableRefNode = node.SelectSingleNode("childTableRef"); //deprecated, use "ct"

            if (childTableRefNode == null)
            {
                childTableRefNode = node.SelectSingleNode("ct");
            }
            if (this.ChildTableRef == null)
            {
                _childTableRef = new Reference(this.Root);
            }
            this.ChildTableRef.XmlLoad(childTableRefNode);

            var parentTableRefNode = node.SelectSingleNode("parentTableRef"); //deprecated, use "pt"

            if (parentTableRefNode == null)
            {
                parentTableRefNode = node.SelectSingleNode("pt");
            }
            if (this.ParentTableRef == null)
            {
                _parentTableRef = new Reference(this.Root);
            }
            this.ParentTableRef.XmlLoad(parentTableRefNode);

            this.ResetId(XmlHelper.GetAttributeValue(node, "id", this.Id));

            var roleName = XmlHelper.GetAttributeValue(node, "roleName", _def_roleName);

            if (roleName == "fk")
            {
                roleName = string.Empty;                   //Error correct from earlier versions
            }
            this.RoleName = roleName;

            this.ConstraintName = XmlHelper.GetAttributeValue(node, "constraintName", _def_constraintname);
        }
Esempio n. 58
0
        private static void CancelarNota(notaVO nota)
        {
            Log.registrarInfo("Solicitando cancelamento da nota " + nota.NFe_ide_nNF + ", série " + nota.serie + " e CNPJ " + nota.NFe_emit_CNPJ, "CancelamentoService");

            var empresa = empresaDAO.obterEmpresa(nota.NFe_emit_CNPJ, string.Empty);

            var cancNFe        = new XmlDocument();
            var pathCancNfeXml = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"XML\cancNFe.xml");

            cancNFe.Load(pathCancNfeXml);

            var pathCabecMsgXml = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"XML\cabecMsg_canc.xml");//tive que mudar para um cabeçalho proprio pois era versao antiga
            var cabecMsg        = new XmlDocument();

            var justificativa = justificativas.obterJustificativa(int.Parse(nota.NFe_ide_nNF.ToString()), nota.serie, nota.NFe_emit_CNPJ);

            // Obtendo id da nota original

            var    pathProtocolo = Path.Combine(nota.pastaDeTrabalho, nota.NFe_ide_nNF + "_procNFe.xml");
            string idNota;

            // Se o arquivo de protocolo não existir
            if (!File.Exists(pathProtocolo))
            {
                // Carregamos o primeiro arquivo de nota
                var pathNotaOriginal = Path.Combine(nota.pastaDeTrabalho, nota.NFe_ide_nNF + ".xml");

                // Se o arquivo de nota não existir... Usamos o que tem no banco mesmo
                if (!File.Exists(pathNotaOriginal))
                {
                    idNota = "ID" + nota.NFe_infNFe_id;
                }
                else // Se existir
                {
                    var xmlOriginal = new XmlDocument();
                    xmlOriginal.Load(pathNotaOriginal);

                    // Carregamos o nó que contém o Id
                    var no = xmlOriginal.SelectSingleNode("/NFe/infNFe/@Id");

                    // Se o nó for nulo, mesma coisa que se o arquivo não existisse
                    if (no == null)
                    {
                        idNota = "ID" + nota.NFe_infNFe_id;
                    }
                    else
                    {
                        var idAntigo = no.InnerText;
                        idNota = idAntigo.Replace("NFe", string.Empty);
                    }
                }
            }
            else
            {
                idNota = nota.NFe_infNFe_id;
            }


            if (justificativa == null)
            {
                throw new InvalidOperationException("Não foi encontrada justificativa para cancelar essa nota.");
            }

            cabecMsg.Load(pathCabecMsgXml);

            cancNFe.SelectSingleNode("/*[local-name()='cancNFe' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]/@Id").InnerText = "ID" + idNota;
            cancNFe.SelectSingleNode("/*[local-name()='cancNFe' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]/*[local-name()='tpAmb' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]").InnerText = (empresa.homologacao + 1).ToString();
            cancNFe.SelectSingleNode("/*[local-name()='cancNFe' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]/*[local-name()='chNFe' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]").InnerText = nota.NFe_infNFe_id;
            cancNFe.SelectSingleNode("/*[local-name()='cancNFe' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]/*[local-name()='nProt' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]").InnerText = nota.protNfe_nProt;
            cancNFe.SelectSingleNode("/*[local-name()='cancNFe' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]/*[local-name()='xJust' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]").InnerText = justificativa.descricao;

            cancNFe = XmlHelper.assinarNFeXML(cancNFe, cancNFe.GetElementsByTagName("infCanc")[0].Attributes["Id"].InnerText, empresa.idEmpresa);

            var ws = new NFe.Cancelamento.NfeCancelamento2();

            var certificado = Geral.ObterCertificadoPorEmpresa(empresa.idEmpresa);

            if (certificado.Handle == IntPtr.Zero)
            {
                // desfaz cancelamento

                nota.statusDaNota = 22;

                notas.alterarNota(nota);

                Log.registrarErro("Certificado da empresa " + empresa.nome + "/" + empresa.cnpj + " não encontrado.", Servico);
            }

            ws.ClientCertificates.Add(Geral.ObterCertificadoPorEmpresa(empresa.idEmpresa));

            cancNFe.Save(Path.Combine(nota.pastaDeTrabalho, "cancNFe.xml"));

            InserirHistorico("19", string.Empty, nota);

            string uf;

            if (UfsSemWebServices.SVAN.Contains(empresa.uf))
            {
                uf = "SVAN";
            }
            else if (UfsSemWebServices.SVRS.Contains(empresa.uf))
            {
                uf = "SVRS";
            }
            else
            {
                uf = empresa.uf;
            }

            var webservice = webservices.obterURLWebservice(uf, "NfeCancelamento",
                                                            Geral.get_Parametro("VersaoProduto"), empresa.homologacao);

            if (webservice == null)
            {
                throw new Exception("Webservice de cancelamento não localizado.");
            }

            ws.Url = webservice.url;
            ws.nfeCabecMsgValue = new NFe.Cancelamento.nfeCabecMsg
            {
                versaoDados = cabecMsg.InnerText,
                cUF         = UFs.ListaDeCodigos[empresa.uf].ToString()
            };

            var retorno = ws.nfeCancelamentoNF2(cancNFe);

            var resultado = retorno.SelectSingleNode("/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='cStat' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]").InnerText;
            var motivo    = retorno.SelectSingleNode("/*[local-name()='infCanc' and namespace-uri()='http://www.portalfiscal.inf.br/nfe']/*[local-name()='xMotivo' and namespace-uri()='http://www.portalfiscal.inf.br/nfe'][1]").InnerText;

            if (resultado.Equals("101") || resultado.Equals("151"))
            {
                nota.statusDaNota       = 4;
                nota.retEnviNFe_xMotivo = motivo;
                nota.retEnviNFe_cStat   = resultado;
                InserirHistorico("20", motivo, nota);
                notas.alterarNota(nota);
            }
            else if (resultado.Equals("420") || resultado.Equals("218"))
            {
                nota.statusDaNota = 4;
                notas.alterarNota(nota);
                InserirHistorico("21", motivo, nota);
            }
            else
            {
                nota.statusDaNota = 22;
                notas.alterarNota(nota);

                InserirHistorico("21", motivo, nota);
            }

            ws.Dispose();

            var xmlRetorno    = new XmlDocument();
            var stringWriter  = new StringWriter();
            var xmlTextWriter = new XmlTextWriter(stringWriter);

            retorno.WriteTo(xmlTextWriter);

            xmlRetorno.LoadXml(stringWriter.ToString());

            xmlRetorno.Save(Path.Combine(nota.pastaDeTrabalho, "retorno_cancNFe.xml"));
        }
Esempio n. 59
0
        /// <summary>
        /// Converts the data value to XML.
        /// </summary>
        /// <param name="data">The data to convert to XML.</param>
        /// <returns>Returns the XML node for the data-type's value.</returns>
        public override XmlNode ToXMl(XmlDocument data)
        {
            // check that the value isn't null
            if (this.Value != null)
            {
                var value = this.Value.ToString();
                var xd    = new XmlDocument();

                // if the value is coming from a translation task, it will always be XML
                if (Helper.Xml.CouldItBeXml(value))
                {
                    xd.LoadXml(value);
                    return(data.ImportNode(xd.DocumentElement, true));
                }

                // load the values into a string array/list.
                var deserializer = new JavaScriptSerializer();
                var values       = deserializer.Deserialize <List <string[]> >(value);

                if (values != null && values.Count > 0)
                {
                    // load the values into an XML document.
                    xd.LoadXml("<TextstringArray/>");

                    // load the config options
                    if (this.options.ShowColumnLabels && !string.IsNullOrWhiteSpace(this.options.ColumnLabels))
                    {
                        var xlabels = xd.CreateElement("labels");

                        // loop through the labels.
                        foreach (var label in this.options.ColumnLabels.Split(new[] { Environment.NewLine }, StringSplitOptions.None))
                        {
                            // add each label to the XML document.
                            var xlabel = XmlHelper.AddTextNode(xd, "label", label);
                            xlabels.AppendChild(xlabel);
                        }

                        xd.DocumentElement.AppendChild(xlabels);
                    }

                    // loop through the list/array items.
                    foreach (var row in values)
                    {
                        // add each row to the XML document.
                        var xrow = xd.CreateElement("values");

                        foreach (var item in row)
                        {
                            // add each value to the XML document.
                            var xvalue = XmlHelper.AddTextNode(xd, "value", item);
                            xrow.AppendChild(xvalue);
                        }

                        xd.DocumentElement.AppendChild(xrow);
                    }

                    // return the XML node.
                    return(data.ImportNode(xd.DocumentElement, true));
                }
            }

            // otherwise render the value as default (in CDATA)
            return(base.ToXMl(data));
        }
Esempio n. 60
0
 public TestNode(string xmlText) : this(XmlHelper.CreateXmlNode(xmlText))
 {
 }