private static string GetSummary(XDocument xml) { var stringParts = xml?.Descendants("summary").FirstOrDefault()?.DescendantNodes().Select(GetDocumentationText); var result = stringParts == null ? null : string.Join("", stringParts); return(result.ToSingleWhitespaces()); }
public static void AddCustomActions(string scriptPath) { string roamingPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string configFilePath = Path.Combine(roamingPath, SettingsPath); if (!File.Exists(configFilePath)) { throw new GitExtensionsIntegrationHelperException("Cannot find Git Extensions configuration file"); } string gitbash = Path.Combine(GitTools.GetBinaryFolder(), Constants.BashFileName); if (!File.Exists(gitbash)) { throw new GitExtensionsIntegrationHelperException("Cannot find git bash"); } // load XML from disk XDocument document = XDocument.Load(configFilePath); // find a placeholder for scripts XElement ownScripts = document? .Descendants("item") .FirstOrDefault(x => x.Descendants("string").Any(y => y.Value == "ownScripts")); XElement ownScriptsValue = ownScripts?.Element("value")?.Element("string"); if (ownScriptsValue == null) { throw new GitExtensionsIntegrationHelperException("Unexpected format of Git Extensions configuration file"); } // deserialize XML XDocument scripts = XDocument.Parse(ownScriptsValue.Value); if (scripts == null) { throw new GitExtensionsIntegrationHelperException("Unexpected format of Git Extensions configuration file"); } Debug.Assert(document != null); string name = Constants.CreateMergeRequestCustomActionName; // delete previously added element IntegrationHelper.DeleteElements(scripts, "ScriptInfo", "Name", new string[] { name }); // add element int maxHotKeyNumber = getCurrentMaximumHotKeyNumber(scripts); XElement[] elements = new XElement[] { getCreateMergeRequestElement(name, scriptPath, maxHotKeyNumber, gitbash) }; if (!IntegrationHelper.AddElements(scripts, "ArrayOfScriptInfo", elements)) { throw new GitExtensionsIntegrationHelperException("Unexpected format of Git Extensions configuration file"); } // serialize XML and save to disk ownScriptsValue.Value = scripts.ToString(); document.Save(configFilePath); }
public static string GetParamByName(XDocument xml, string paramName) { var val = xml?.Descendants().FirstOrDefault(el => { if (el.Name != "param") { return(false); } var attr = el.Attribute("name"); return(attr != null && attr.Value == paramName); }); return(val?.Value.Trim()); }
/// <summary> /// Обработва отговорите на ЕИСПП /// </summary> /// <returns></returns> private async Task ProcessReplies() { foreach (var item in eisppReplies) { try { XDocument message = XDocument.Parse(item); string correlationId = message?.Descendants("Property") .Where(e => e.Attribute("name")?.Value == "correlation_id") .Select(e => e.Attribute("value")?.Value) .FirstOrDefault(); XElement result = message?.Element("EISPPMessage")?.Element("EISPPPAKET")?.Element("DATA")?.Element("RZT"); XElement exception = result?.Element("Exception"); XElement htmlCard = result?.Element("KartaNPR"); if (correlationId != null) { string eisppNumber = result ?.Descendants() .Where(e => e.NodeType == System.Xml.XmlNodeType.Attribute) .Where(a => a.Name == "nprnmr") .Select(a => a.Value) .FirstOrDefault() ?? ""; await SaveResponse(correlationId, item, eisppNumber); if (exception != null) { SetError(correlationId, exception.Value); } else if (htmlCard != null) { await SaveCard(correlationId, htmlCard.Value, eisppNumber); } else if (result != null) { SetOk(correlationId); } else { SetError(correlationId, "Липсва отговор от ЕИСПП!"); } } } catch (Exception ex) { logger.LogError(ex, "Error processing replies!"); } } }
public IEnumerable <(string recipient, double weight, double value)> GetDeliveries() { // Do not group by recipient, just convert each parcel in a recipient (a tuple of strings), a weight (a double) and the value (another double) var notGroupedParcels = Document?.Descendants("Parcel").Select(item => ( recipient: string.Join(" ", item.Element("Receipient")?.Element("Name")?.Value, item.Element("Receipient")?.Element("Address")?.Element("Street")?.Value, item.Element("Receipient")?.Element("Address")?.Element("HouseNumber")?.Value, item.Element("Receipient")?.Element("Address")?.Element("PostalCode")?.Value, item.Element("Receipient")?.Element("Address")?.Element("City")?.Value), weight: Convert.ToDouble(item.Element("Weight")?.Value), value: Convert.ToDouble(item.Element("Value")?.Value))); var departmentSelection = notGroupedParcels?.Where(item => item.weight >= FromWeight && item.weight < ToWeight); return(departmentSelection); }
public IEnumerable <(string recipient, double weight, double value)> GetDeliveries() { // group deliveries by recipient, because document might be delivered to the same person and address. // It's a waste sending two deliveries. Assume that the cost of insuring a grouped value is less than the cost of sending multiple deliveries. var groupedByReceipient = Document?.Descendants("Parcel").GroupBy(item => new { Name = item.Element("Receipient")?.Element("Name")?.Value, Street = item.Element("Receipient")?.Element("Address")?.Element("Street")?.Value, HouseNumber = item.Element("Receipient")?.Element("Address")?.Element("HouseNumber")?.Value, PostalCode = item.Element("Receipient")?.Element("Address")?.Element("PostalCode")?.Value, City = item.Element("Receipient")?.Element("Address")?.Element("City")?.Value }).Select(group => ( recipient: string.Join(" ", group.Key.Name, group.Key.Street, group.Key.HouseNumber, group.Key.PostalCode, group.Key.City), weight: group.Sum(e => Convert.ToDouble(e.Element("Weight")?.Value)), value: group.Sum(e => Convert.ToDouble(e.Element("Value")?.Value)))); return(groupedByReceipient); }
public CoreProjectVersionChanger(string projectDir) { if (string.IsNullOrEmpty(projectDir)) { throw new ArgumentException("Project dir can't be null or empty!"); } if (!Directory.Exists(projectDir)) { CanChange = false; return; } projectFile = Directory.GetFiles(projectDir, "*.csproj", SearchOption.TopDirectoryOnly) .FirstOrDefault(); if (string.IsNullOrEmpty(projectFile)) { CanChange = false; return; } xml = XDocument.Load(projectFile); XElement versionRoot = xml ?.Descendants("Project")?.FirstOrDefault() ?.Descendants("PropertyGroup")?.FirstOrDefault(); if (versionRoot == null) { CanChange = false; return; } assemblyVersion = versionRoot?.Descendants("AssemblyVersion")?.FirstOrDefault(); fileVersion = versionRoot?.Descendants("FileVersion")?.FirstOrDefault(); }
public async Task <(bool IsValid, List <string> ErrorMessages)> ValidateExpense(XDocument expense) { var isValid = true; var errorMessages = new List <string>(); await Task.Run(() => { var totalValue = expense?.Descendants()?.FirstOrDefault(d => d.Name == XHelper.Total)?.Value; if (string.IsNullOrWhiteSpace(totalValue)) { isValid = false; errorMessages.Add(Constants.MISSING_TOTAL); } var isTotalExists = decimal.TryParse(totalValue, out decimal total); if (isValid && !isTotalExists) { isValid = false; errorMessages.Add(Constants.INVALID_TOTAL); } var duplicates = expense.Descendants() .GroupBy(e => e.ToString()) .Where(g => g.Count() > 1) .Select(g => g.First()) .ToList(); if (duplicates.Any()) { isValid = false; errorMessages.Add(Constants.DUPLICATE_ELEMENTS); errorMessages.AddRange(duplicates.Select(d => d.Name.ToString())); } }); return(isValid, errorMessages); }
/// <summary> /// Update [Content_Types].xml file /// </summary> private void UpdateContentTypes(bool ensureStrings) { if (!(ensureStrings || (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any()))) { // Nothing to update return; } using (Stream stream = this.Archive.GetEntry("[Content_Types].xml").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { //TODO error } bool update = false; List <XElement> overrideElements = document.Descendants().Where(d => d.Name.LocalName == "Override").ToList(); //Ensure SharedStrings if (ensureStrings) { XElement overrideElement = (from element in overrideElements from attribute in element.Attributes() where attribute.Name == "PartName" && attribute.Value.Equals("/xl/sharedStrings.xml", StringComparison.InvariantCultureIgnoreCase) select element).FirstOrDefault(); if (overrideElement == null) { overrideElement = new XElement(document.Root.GetDefaultNamespace() + "Override"); overrideElement.Add(new XAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml")); overrideElement.Add(new XAttribute("PartName", "/xl/sharedStrings.xml")); document.Root.Add(overrideElement); update = true; } } if (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) { foreach (var item in this.DeleteWorksheets) { // the file name is different for each xml file string fileName = string.Format("/xl/worksheets/sheet{0}.xml", item); XElement overrideElement = (from element in overrideElements from attribute in element.Attributes() where attribute.Name == "PartName" && attribute.Value == fileName select element).FirstOrDefault(); if (overrideElement != null) { overrideElement.Remove(); update = true; } } } if (this.AddWorksheets != null && this.AddWorksheets.Any()) { foreach (var item in this.AddWorksheets) { // the file name is different for each xml file string fileName = string.Format("/xl/worksheets/sheet{0}.xml", item.SheetId); XElement overrideElement = new XElement(document.Root.GetDefaultNamespace() + "Override"); overrideElement.Add(new XAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml")); overrideElement.Add(new XAttribute("PartName", fileName)); document.Root.Add(overrideElement); update = true; } } if (update) { // Set the stream to the start stream.Position = 0; // Clear the stream stream.SetLength(0); // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8); document.Save(streamWriter); streamWriter.Flush(); } } }
/// <summary> /// Update xl/_rels/workbook.xml.rels file /// </summary> private void UpdateRelations(bool ensureStrings) { if (!(ensureStrings || (this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any()))) { // Nothing to update return; } using (Stream stream = this.Archive.GetEntry("xl/_rels/workbook.xml.rels").Open()) { XDocument document = XDocument.Load(stream); if (document == null) { //TODO error } bool update = false; List <XElement> relationshipElements = document.Descendants().Where(d => d.Name.LocalName == "Relationship").ToList(); int id = relationshipElements.Count; if (ensureStrings) { //Ensure SharedStrings XElement relationshipElement = (from element in relationshipElements from attribute in element.Attributes() where attribute.Name == "Target" && attribute.Value.Equals("sharedStrings.xml", StringComparison.InvariantCultureIgnoreCase) select element).FirstOrDefault(); if (relationshipElement == null) { relationshipElement = new XElement(document.Root.GetDefaultNamespace() + "Relationship"); relationshipElement.Add(new XAttribute("Target", "sharedStrings.xml")); relationshipElement.Add(new XAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings")); relationshipElement.Add(new XAttribute("Id", string.Format("rId{0}", ++id))); document.Root.Add(relationshipElement); update = true; } } // Remove all references to sheets from this file as they are not requried if ((this.DeleteWorksheets != null && this.DeleteWorksheets.Any()) || (this.AddWorksheets != null && this.AddWorksheets.Any())) { XElement[] worksheetElements = (from element in relationshipElements from attribute in element.Attributes() where attribute.Name == "Type" && attribute.Value == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" select element).ToArray(); for (int i = worksheetElements.Length - 1; i > 0; i--) { worksheetElements[i].Remove(); update = true; } } if (update) { // Set the stream to the start stream.Position = 0; // Clear the stream stream.SetLength(0); // Open the stream so we can override all content of the sheet StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8); document.Save(streamWriter); streamWriter.Flush(); } } }
/// <summary> /// Method to get if anonymous login is enabled /// </summary> /// <returns>true if anonymous login is enabled</returns> public async Task <bool> GetAnonymousLoginAsync() { XDocument document = await this.InvokeAsync("X_AVM-DE_GetAnonymousLogin", null); return(document.Descendants("NewX_AVM-DE_AnonymousLoginEnabled").First().Value == "1"); }
static List <Employee> ParseXml(string filename) { string employeePattern = @"Employee:\s*(?'employee'\d*)\s+Name:\s*(?'name'[^\s]*)\s*Base:\s+(?'base'[^\s]*)\s*Eqpt:\s+(?'eqpt'[^\s]*)\s+Pos:\s+(?'pos'[^\s]*)"; List <Employee> employees = new List <Employee>(); Employee newEmployee = null; List <int> assmentColumnWidths = new List <int>() { 7, 7, 14, 7, 7, 8, 16, 8, 8 }; int lineNo = 0; State state = State.FIND_HEADINGBEGIN; XDocument doc = XDocument.Load(FILENAME); foreach (XElement xLine in doc.Descendants("Line")) { string line = ((string)xLine).Trim(); if (line.Length > 0) { switch (state) { case State.FIND_HEADINGBEGIN: if (line.StartsWith("#HEADINGBEGIN#")) { state = State.HEADINGBEGIN; lineNo = 0; } break; case State.HEADINGBEGIN: if (line.StartsWith("#HEADINGEND#")) { state = State.EMPLOYEE; } else { if (lineNo++ == 0) { newEmployee = new Employee(); employees.Add(newEmployee); Match expr = Regex.Match(line, employeePattern); newEmployee.id = expr.Groups["employee"].Value; newEmployee.name = expr.Groups["name"].Value; newEmployee._base = expr.Groups["base"].Value; newEmployee.eqpt = expr.Groups["eqpt"].Value; newEmployee.pos = expr.Groups["pos"].Value; newEmployee.eqpt = expr.Groups["eqpt"].Value; } } break; case State.EMPLOYEE: if (line.StartsWith("#GROUPNOBREAK#")) { state = State.FIND_GROUPBEGIN; lineNo = 0; } else { List <string> assignmentData = GetFixedWidth(line, assmentColumnWidths); Assignment assignment = new Assignment(); if (newEmployee.assignments == null) { newEmployee.assignments = new List <Assignment>(); } newEmployee.assignments.Add(assignment); assignment.date = assignmentData[0]; assignment.name = assignmentData[1]; assignment.onDuty = assignmentData[2]; assignment.offDuty = assignmentData[3]; assignment.tafb = assignmentData[4]; assignment.dailyBlock = assignmentData[5]; assignment.dailyCredit = assignmentData[6]; assignment.tripGuarantee = assignmentData[7]; assignment.jrMan = assignmentData[8]; } break; case State.FIND_GROUPBEGIN: if (line.StartsWith("#GROUPBEGIN#")) { state = State.GROUP; Total total = new Total(); newEmployee.total = new Total(); } break; case State.GROUP: if (line.StartsWith("#GROUPEND#")) { state = State.FIND_HEADINGBEGIN; } else { string[] splitLine = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); switch (++lineNo) { case 1: newEmployee.total.taxable = splitLine[2]; break; case 2: newEmployee.total.nonTaxable = splitLine[2]; break; case 3: newEmployee.total.total = splitLine[2]; break; } } break; } } } return(employees); }
public void Generate() { _currentTech = null; WriteLine("import core.runtime"); WriteLine(); WriteLine("namespace core"); WriteLine("{"); Indent(); WriteLine("public partial module intrinsics"); WriteLine("{"); Indent(); WriteLine("public partial module x86"); WriteLine("{"); Indent(); foreach (var elt in _doc.Descendants("intrinsic")) { var tech = elt.Attribute("tech")?.Value; if (!Supports.Contains(tech)) { continue; } ///// __m128 _mm_mul_ps (__m128 a, __m128 b) ///// MULPS xmm, xmm/m128 //@FuncImpl(FuncImplOptions.INTERNAL_CALL) //@Intrinsic //public static extern func _mm_mul_ps(left: __m128, right: __m128) -> __m128 var name = elt.Attribute("name")?.Value; Debug.Assert(name != null); // Is this a macro if (name.IndexOf("M") > 0) { continue; } var techName = tech.ToLowerInvariant().Replace(".", string.Empty); var retType = elt.Attribute("rettype")?.Value; var parameters = elt.Elements("parameter"); var isUnsafe = IsUnsafe(retType) || parameters.Any(x => IsUnsafe(x.Attribute("type").Value)); var isMmx = retType.Contains("__m64") || parameters.Any(x => x.Attribute("type").Value.Contains("__m64")); // don't output mmx if (isMmx) { continue; } HandleModule(techName); WriteLine(); //WriteLine("@FuncImpl(FuncImplOptions.INTERNAL_CALL)"); var description = elt.Element("description")?.Value; if (description != null) { description = description.Replace('"', '`'); description = description.Replace("\r\n", " "); description = description.Replace("\n", " "); WriteLine($"/// {description}"); } WriteLine("@Intrinsic"); Write($"public static {(isUnsafe?"unsafe ":string.Empty)}extern func {name}("); bool isFirst = true; foreach (var parameter in elt.Elements("parameter")) { if (!isFirst) { Write(", "); } var param_name = parameter.Attribute("varname")?.Value; var param_type = parameter.Attribute("type")?.Value; if (param_type == "void") { continue; } Write($"{param_name}: {GetStarkType(param_type)}"); isFirst = false; } Write(")"); if (retType != "void") { Write($" -> {GetStarkType(retType)}"); } WriteLine(); } HandleModule(null); DeIndent(); WriteLine("}"); // module x86 DeIndent(); WriteLine("}"); // module intrinsics DeIndent(); WriteLine("}"); // namespace core }
private void buttonApply_Click(object sender, EventArgs e) { if (!m_formLoaded || m_formClosing) { return; } string serviceConfigFile = FilePath.GetAbsolutePath(textBoxConfigFile.Text); if (!File.Exists(serviceConfigFile)) { MessageBox.Show(this, $"Cannot find config file \"{serviceConfigFile}\".", "Cannot Apply Changes", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { XDocument serviceConfig = XDocument.Load(serviceConfigFile); //Guid nodeID = Guid.Parse(serviceConfig // .Descendants("systemSettings") // .SelectMany(systemSettings => systemSettings.Elements("add")) // .Where(element => "NodeID".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)) // .Select(element => (string)element.Attribute("value")) // .FirstOrDefault() ?? Guid.Empty.ToString()); string connectionString = serviceConfig .Descendants("systemSettings") .SelectMany(systemSettings => systemSettings.Elements("add")) .Where(element => "ConnectionString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)) .Select(element => (string)element.Attribute("value")) .FirstOrDefault(); string dataProviderString = serviceConfig .Descendants("systemSettings") .SelectMany(systemSettings => systemSettings.Elements("add")) .Where(element => "DataProviderString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)) .Select(element => (string)element.Attribute("value")) .FirstOrDefault(); string serviceName = serviceConfig .Descendants("securityProvider") .SelectMany(securitySettings => securitySettings.Elements("add")) .Where(element => "ApplicationName".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)) .Select(element => (string)element.Attribute("value")) .FirstOrDefault(); string managerConfigFile = $"{FilePath.GetDirectoryName(serviceConfigFile)}{serviceName}Manager.exe.config"; XDocument managerConfig = null; bool applyManagerChanges = true; if (!File.Exists(managerConfigFile)) { if (MessageBox.Show(this, $"Failed to associated manager config file \"{managerConfigFile}\". Do you want to continue with changes to service only?", "Manager Config Not Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } applyManagerChanges = false; } if (applyManagerChanges) { managerConfig = XDocument.Load(managerConfigFile); } // Attempt to access service controller for the specified Windows service ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase) == 0); if (serviceController != null) { try { if (serviceController.Status == ServiceControllerStatus.Running) { m_log.Publish(MessageLevel.Info, $"Attempting to stop the {serviceName} Windows service..."); serviceController.Stop(); // Can't wait forever for service to stop, so we time-out after 20 seconds serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D)); if (serviceController.Status == ServiceControllerStatus.Stopped) { m_log.Publish(MessageLevel.Info, $"Successfully stopped the {serviceName} Windows service."); } else { m_log.Publish(MessageLevel.Info, $"Failed to stop the {serviceName} Windows service after trying for 20 seconds..."); } } } catch (Exception ex) { Logger.SwallowException(ex, $"Failed to stop the {serviceName} Windows service: {ex.Message}"); } } // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances Process[] instances = Process.GetProcessesByName(serviceName); if (instances.Length > 0) { int total = 0; m_log.Publish(MessageLevel.Info, $"Attempting to stop running instances of the {serviceName}..."); // Terminate all instances of service running on the local computer foreach (Process process in instances) { process.Kill(); total++; } if (total > 0) { m_log.Publish(MessageLevel.Info, $"Stopped {total} {serviceName} instance{(total > 1 ? "s" : "")}."); } } // Mark phasor data source validation to rename all point tags at next configuration reload using (AdoDataConnection connection = new AdoDataConnection(connectionString, dataProviderString)) { string filterExpression = "MethodName = 'PhasorDataSourceValidation'"; TableOperations <DataOperation> dataOperationTable = new TableOperations <DataOperation>(connection); DataOperation record = dataOperationTable.QueryRecordWhere(filterExpression); if (record == null) { string errorMessage = $"Failed to find DataOperation record with {filterExpression}."; m_log.Publish(MessageLevel.Error, "ApplyChanges", errorMessage); MessageBox.Show(this, errorMessage, "Cannot Apply Changes", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } record.Arguments = "renameAllPointTags=true"; dataOperationTable.UpdateRecordWhere(record, filterExpression); } // Update point tag name expression in config files XElement servicePointTagExpression = serviceConfig .Descendants("systemSettings") .SelectMany(securitySettings => securitySettings.Elements("add")) .FirstOrDefault(element => "PointTagNameExpression".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)); XAttribute value = servicePointTagExpression?.Attribute("value"); if (value != null) { value.Value = textBoxExpression.Text; serviceConfig.Save(serviceConfigFile); } XElement managerPointTagExpression = managerConfig? .Descendants("systemSettings") .SelectMany(securitySettings => securitySettings.Elements("add")) .FirstOrDefault(element => "PointTagNameExpression".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)); value = managerPointTagExpression?.Attribute("value"); if (value != null) { value.Value = textBoxExpression.Text; managerConfig.Save(managerConfigFile); } if (checkBoxSetPortNumber.Checked) { // Update STTP port number XElement sttpConfigString = serviceConfig .Descendants("sttpdatapublisher") .SelectMany(securitySettings => securitySettings.Elements("add")) .FirstOrDefault(element => "ConfigurationString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)); value = sttpConfigString?.Attribute("value"); if (value != null) { value.Value = $"port={maskedTextBoxPortNumber.Text}"; serviceConfig.Save(serviceConfigFile); } } // Refresh state in case service process was forcibly stopped serviceController.Refresh(); // Attempt to restart Windows service... serviceController.Start(); Application.Exit(); } catch (Exception ex) { m_log.Publish(MessageLevel.Error, "ApplyChanges", ex.Message, exception: ex); MessageBox.Show(this, $"Exception: {ex.Message}", "Failed to Apply Changes", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void ParseCapabilities(XDocument xDoc) { //Get service info var info = (from Service in xDoc.Descendants("Service") select new { Title = Service.Element("Title") == null ? null : Service.Element("Title").Value, Abstract = Service.Element("Abstract") == null ? null : Service.Element("Abstract").Value }).First(); if (info != null) { this.Title = info.Title; //OnPropertyChanged("Title"); this.Abstract = info.Abstract; //OnPropertyChanged("Abstract"); } //Get a list of layers var layerList = from Layers in xDoc.Descendants("Layer") where Layers.Descendants("Layer").Count() == 0 select new LayerInfo() { Name = Layers.Element("Name") == null ? null : Layers.Element("Name").Value, Title = Layers.Element("Title") == null ? null : Layers.Element("Title").Value, Abstract = Layers.Element("Abstract") == null ? null : Layers.Element("Abstract").Value }; foreach (LayerInfo i in layerList) { this.LayerList.Add(i); } //OnPropertyChanged("LayerList"); try { //Get endpoint for GetMap requests //I wish SL supported XPath... var capabilities = (from c in xDoc.Descendants("Capability") select c).First(); var request = (from c in capabilities.Descendants("Request") select c).First(); var GetMap = (from c in request.Descendants("GetMap") select c).First(); var DCPType = (from c in request.Descendants("DCPType") select c).First(); var HTTP = (from c in request.Descendants("HTTP") select c).First(); var Get = (from c in request.Descendants("Get") select c).First(); var OnlineResource = (from c in request.Descendants("OnlineResource") select c).First(); var href = OnlineResource.Attribute(XName.Get("href", "http://www.w3.org/1999/xlink")); httpGetResource = href.Value; } catch { //Default to WMS url httpGetResource = this.Url; } //Get the full extent of all layers var box = (from Layers in xDoc.Descendants("LatLonBoundingBox") select new { minx = double.Parse(Layers.Attribute("minx").Value), miny = double.Parse(Layers.Attribute("miny").Value), maxx = double.Parse(Layers.Attribute("maxx").Value), maxy = double.Parse(Layers.Attribute("maxy").Value) }).ToList(); var minx = (from minmax in box select minmax.minx).Min(); var miny = (from minmax in box select minmax.miny).Min(); var maxx = (from minmax in box select minmax.maxx).Max(); var maxy = (from minmax in box select minmax.maxy).Max(); this.FullExtent = new Envelope(minx, miny, maxx, maxy) { SpatialReference = new SpatialReference(4326) }; }
public static XmlEntities ParseXml() { XmlEntities xmlEntities = new XmlEntities(); var filename = "Geographic.xml"; var currentDirectory = Directory.GetCurrentDirectory(); var purchaseOrderFilepath = System.IO.Path.Combine(currentDirectory, filename); StringBuilder result = new StringBuilder(); //Load xml XDocument xdoc = XDocument.Load(filename); //Run query var substations = xdoc.Descendants("SubstationEntity") .Select(sub => new SubstationEntity { Id = (long)sub.Element("Id"), Name = (string)sub.Element("Name"), X = (double)sub.Element("X"), Y = (double)sub.Element("Y"), }).ToList(); double longit = 0; double latid = 0; for (int i = 0; i < substations.Count(); i++) { var item = substations[i]; ToLatLon(item.X, item.Y, 34, out latid, out longit); if (latid <= minLatitude || latid >= maxLatitude || longit <= minLongitude || longit >= maxLongitude) { substations.RemoveAt(i); continue; } else { substations[i].Latitude = latid; substations[i].Longitude = longit; xmlEntities.Substations.Add(substations[i]); collectionOfNodesID.Add(substations[i].Id, substations[i]); } } var nodes = xdoc.Descendants("NodeEntity") .Select(node => new NodeEntity { Id = (long)node.Element("Id"), Name = (string)node.Element("Name"), X = (double)node.Element("X"), Y = (double)node.Element("Y"), }).ToList(); for (int i = 0; i < nodes.Count(); i++) { var item = nodes[i]; ToLatLon(item.X, item.Y, 34, out latid, out longit); if (latid <= minLatitude || latid >= maxLatitude || longit <= minLongitude || longit >= maxLongitude) { nodes.RemoveAt(i); continue; } else { nodes[i].Latitude = latid; nodes[i].Longitude = longit; xmlEntities.Nodes.Add(nodes[i]); collectionOfNodesID.Add(nodes[i].Id, nodes[i]); } } var switches = xdoc.Descendants("SwitchEntity") .Select(sw => new SwitchEntity { Id = (long)sw.Element("Id"), Name = (string)sw.Element("Name"), Status = (string)sw.Element("Status"), X = (double)sw.Element("X"), Y = (double)sw.Element("Y"), }).ToList(); for (int i = 0; i < switches.Count(); i++) { var item = switches[i]; ToLatLon(item.X, item.Y, 34, out latid, out longit); if (latid <= minLatitude || latid >= maxLatitude || longit <= minLongitude || longit >= maxLongitude) { switches.RemoveAt(i); continue; } else { switches[i].Latitude = latid; switches[i].Longitude = longit; xmlEntities.Switches.Add(switches[i]); collectionOfNodesID.Add(switches[i].Id, switches[i]); } } var lines = xdoc.Descendants("LineEntity") .Select(line => new LineEntity { Id = (long)line.Element("Id"), Name = (string)line.Element("Name"), ConductorMaterial = (string)line.Element("ConductorMaterial"), IsUnderground = (bool)line.Element("IsUnderground"), R = (float)line.Element("R"), FirstEnd = (long)line.Element("FirstEnd"), SecondEnd = (long)line.Element("SecondEnd"), LineType = (string)line.Element("LineType"), ThermalConstantHeat = (long)line.Element("ThermalConstantHeat"), Vertices = line.Element("Vertices").Descendants("Point").Select(p => new grafikaPZ3.Model.Point { X = (double)p.Element("X"), Y = (double)p.Element("Y"), }).ToList() }).ToList(); for (int i = 0; i < lines.Count(); i++) { if (collectionOfNodesID.ContainsKey(lines[i].SecondEnd) && collectionOfNodesID.ContainsKey(lines[i].FirstEnd)) { var line = lines[i]; foreach (var point in line.Vertices) { ToLatLon(point.X, point.Y, 34, out latid, out longit); point.Latitude = latid; point.Longitude = longit; } xmlEntities.Lines.Add(line); } } return(xmlEntities); }
public bool Equals(string filePath) { bool flag; using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { long length = fileStream.Length; if (this.Size == length) { if (filePath.EndsWith(".kom")) { BinaryReader binaryReader = new BinaryReader(fileStream); fileStream.Seek((long)60, SeekOrigin.Begin); int num = binaryReader.ReadInt32(); if (this.FileTime == num) { fileStream.Seek((long)64, SeekOrigin.Begin); int num1 = binaryReader.ReadInt32(); if (this.Checksum == num1) { fileStream.Seek((long)68, SeekOrigin.Begin); int num2 = binaryReader.ReadInt32(); uint?checksumSize = this.ChecksumSize; long num3 = (long)num2; if (((ulong)checksumSize.GetValueOrDefault() != num3 ? false : checksumSize.HasValue)) { MemoryStream memoryStream = new MemoryStream(binaryReader.ReadBytes(num2)); XDocument xDocument = XDocument.Load(memoryStream); int num4 = xDocument.Descendants("Files").Elements <XElement>("File").Count <XElement>(); uint? checksumCount = this.ChecksumCount; long num5 = (long)num4; if (((ulong)checksumCount.GetValueOrDefault() != num5 ? true : !checksumCount.HasValue)) { flag = false; return(flag); } } else { flag = false; return(flag); } } else { flag = false; return(flag); } } else { flag = false; return(flag); } } else { int num6 = Adler32.ComputeChecksum(fileStream); if (this.Checksum != num6) { flag = false; return(flag); } } return(true); } else { flag = false; } } return(flag); }
public bool WriteTilSFtp(XDocument xdoc) { Guid id1 = clsSQLite.insertStoreXML(Program.sftpName, false, Program.AppEngName, xdoc.ToString(), ""); m_SendqueueId = xdoc.Descendants("Sendqueue").Descendants("Id").First().Value; m_PbsfileId = xdoc.Descendants("Pbsfile").Descendants("Id").First().Value; m_TilPBSFilename = xdoc.Descendants("Pbsfile").Descendants("TilPBSFilename").First().Value; m_Transmisionsdato = DateTime.Parse(xdoc.Descendants("Pbsfile").Descendants("Transmisionsdato").First().Value); m_SendData = xdoc.Descendants("Pbsfile").Descendants("SendData").First().Value; bool success; string TilPBSFilename = m_TilPBSFilename; string TilPBSFile = m_SendData; char[] c_TilPBSFile = TilPBSFile.ToCharArray(); byte[] b_TilPBSFile = System.Text.Encoding.GetEncoding("windows-1252").GetBytes(c_TilPBSFile); int FilesSize = b_TilPBSFile.Length; sendAttachedFile(TilPBSFilename, b_TilPBSFile, true); string fullpath = m_Inbound + "/" + TilPBSFilename; string handle = m_sftp.OpenFile(fullpath, "writeOnly", "createTruncate"); if (handle == null) { throw new Exception(m_sftp.LastErrorText); } success = m_sftp.WriteFileBytes(handle, b_TilPBSFile); if (!success) { throw new Exception(m_sftp.LastErrorText); } success = m_sftp.CloseHandle(handle); if (success != true) { throw new Exception(m_sftp.LastErrorText); } clsSQLite.updateStoreXML(id1, true); XElement xmlPbsfilesUpdate = new XElement("Pbsfiles"); xmlPbsfilesUpdate.Add(new XElement("SendqueueId", m_SendqueueId)); xmlPbsfilesUpdate.Add(new XElement("Id", m_PbsfileId)); xmlPbsfilesUpdate.Add(new XElement("Type", 8)); xmlPbsfilesUpdate.Add(new XElement("Path", m_Inbound)); xmlPbsfilesUpdate.Add(new XElement("Filename", TilPBSFilename)); xmlPbsfilesUpdate.Add(new XElement("Size", FilesSize)); xmlPbsfilesUpdate.Add(new XElement("Atime", DateTime.Now)); xmlPbsfilesUpdate.Add(new XElement("Mtime", DateTime.Now)); xmlPbsfilesUpdate.Add(new XElement("Transmittime", m_Transmisionsdato)); string strxmlPbsfilesUpdate = @"<?xml version=""1.0"" encoding=""utf-8"" ?> " + xmlPbsfilesUpdate.ToString();; Guid id2 = clsSQLite.insertStoreXML(Program.AppEngName, false, Program.sftpName, strxmlPbsfilesUpdate, ""); clsRest objRest = new clsRest(); string strxmldata = objRest.HttpPost2(clsRest.urlBaseType.data, "tilpbs", strxmlPbsfilesUpdate); XDocument xmldata = XDocument.Parse(strxmldata); string Status = xmldata.Descendants("Status").First().Value; if (Status == "True") { clsSQLite.updateStoreXML(id2, true); return(true); } else { return(false); } }
public static string GetConfigurationFileName() { if (!string.IsNullOrEmpty(HostConfigFile) && File.Exists(HostConfigFile)) { return(HostConfigFile); } // Will be faster to load known config file, try a few common ones first string[] knownConfigurationFileNames = { "openPDC.exe.config", "SIEGate.exe.config", "openHistorian.exe.config", "substationSBG.exe.config", "openMIC.exe.config", "PDQTracker.exe.config", "openECA.exe.config" }; // Search for the file name in the list of known configuration files foreach (string fileName in knownConfigurationFileNames) { string absolutePath = FilePath.GetAbsolutePath(fileName); if (File.Exists(absolutePath)) { return(absolutePath); } } // Fall back on manual search foreach (string configFile in FilePath.GetFileList($"{FilePath.AddPathSuffix(FilePath.GetAbsolutePath(""))}*.exe.config")) { try { XDocument serviceConfig = XDocument.Load(configFile); string applicationName = serviceConfig .Descendants("securityProvider") .SelectMany(systemSettings => systemSettings.Elements("add")) .Where(element => "ApplicationName".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase)) .Select(element => (string)element.Attribute("value")) .FirstOrDefault(); if (string.IsNullOrWhiteSpace(applicationName)) { continue; } if (applicationName.Trim().Equals(FilePath.GetFileNameWithoutExtension(FilePath.GetFileNameWithoutExtension(configFile)), StringComparison.OrdinalIgnoreCase)) { return(configFile); } } catch (Exception ex) { // Just move on to the next config file if XML parsing fails Program.Log.Publish(MessageLevel.Warning, "GetConfigurationFileName", $"Failed parse config file \"{configFile}\".", exception: ex); } } return(ConfigurationFile.Current.Configuration.FilePath); }
public ActionResult SiteSearch(string searchString) { String Db = AccessServerPath.FilePath() + "SearchTerms.xml"; XDocument searchObject = XDocument.Load(Db); searchString = Regex.Replace(searchString, @"\t|\n|\r", ""); Model_Results results = new Model_Results(); results.Tag = searchString; foreach (var node in searchObject.Descendants("Result")) { foreach (var tagsNode in node.Descendants("Tags")) { foreach (var tagnode in tagsNode.Descendants("tag")) { string cleaned = Regex.Replace(tagnode.Value, @"\t|\n|\r", ""); if (cleaned.Trim().ToUpper().Contains(" " + searchString.ToUpper() + " ")) { Model_Result result = new Model_Result(); String tagOutput = ""; List <String> upperCleaned = cleaned.Trim().Split(' ').ToList(); foreach (String s in upperCleaned) { tagOutput = tagOutput + " " + (char.ToUpper(s[0]) + s.Substring(1)); } result.Link = tagnode.Parent.Parent.Element("link").Value.Trim(); result.Page = tagnode.Parent.Parent.Element("page").Value.Trim() + " - " + tagOutput; //result.Page = tagnode.Parent.Parent.Element("page").Value.Trim(); results.Results.Add(result); continue; } else if (!cleaned.Trim().Contains(' ') & cleaned.Trim().ToUpper() == searchString.ToUpper()) { Model_Result result = new Model_Result(); String tagOutput = ""; List <String> upperCleaned = cleaned.Trim().Split(' ').ToList(); foreach (String s in upperCleaned) { tagOutput = tagOutput + " " + (char.ToUpper(s[0]) + s.Substring(1)); } result.Link = tagnode.Parent.Parent.Element("link").Value.Trim(); result.Page = tagnode.Parent.Parent.Element("page").Value.Trim() + " - " + tagOutput; //result.Page = tagnode.Parent.Parent.Element("page").Value.Trim(); results.Results.Add(result); continue; } else if (cleaned.Trim().ToUpper().Contains(searchString.ToUpper() + " ")) { Model_Result result = new Model_Result(); String tagOutput = ""; List <String> upperCleaned = cleaned.Trim().Split(' ').ToList(); foreach (String s in upperCleaned) { tagOutput = tagOutput + " " + (char.ToUpper(s[0]) + s.Substring(1)); } result.Link = tagnode.Parent.Parent.Element("link").Value.Trim(); result.Page = tagnode.Parent.Parent.Element("page").Value.Trim() + " - " + tagOutput; //result.Page = tagnode.Parent.Parent.Element("page").Value.Trim(); results.Results.Add(result); continue; } else if (cleaned.Trim().ToUpper().Contains(" " + searchString.ToUpper())) { Model_Result result = new Model_Result(); String tagOutput = ""; List <String> upperCleaned = cleaned.Trim().Split(' ').ToList(); foreach (String s in upperCleaned) { tagOutput = tagOutput + " " + (char.ToUpper(s[0]) + s.Substring(1)); } result.Link = tagnode.Parent.Parent.Element("link").Value.Trim(); result.Page = tagnode.Parent.Parent.Element("page").Value.Trim() + " - " + tagOutput; //result.Page = tagnode.Parent.Parent.Element("page").Value.Trim(); results.Results.Add(result); continue; } } } } return(View("~/Views/Search/Index.cshtml", results)); }
/// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for blobs /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 }; blockBlob.UploadFromByteArray(data, 0, 4); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); byte[] target = new byte[4]; OperationContext opContext = new OperationContext(); IPAddress actualIP = null; opContext.ResponseReceived += (sender, e) => { Stream stream = e.Response.GetResponseStream(); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); XDocument xdocument = XDocument.Parse(text); actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value); } }; bool exceptionThrown = false; try { blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext); } catch (StorageException) { exceptionThrown = true; Assert.IsNotNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = generateFinalIPAddressOrRange(actualIP); blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); blockBlobSAS = new StorageCredentials(blockBlobToken); blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
private void initialize() { try { XDocument connectionXML = XDocument.Load(File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + FILE_CONFIG)); var xmlURLs = (from op in connectionXML.Descendants("HANA") select new { BaseUrl = op.Element("BaseUrl").Value, urlServiceLayer = op.Element("UrlServiceLayer").Value, urlGetEmpresa = op.Element("GetEmpresa").Value, urlGetOrdenVenta = op.Element("GetOrdenVenta").Value, urlGetPagoRecibido = op.Element("GetPagoRecibido").Value, urlGetSocioNegocio = op.Element("GetSocioNegocio").Value, urlGetIncidencia = op.Element("GetIncidencia").Value, urlGetUbicaciones = op.Element("GetUbicaciones").Value, urlGetDevolucion = op.Element("GetDevolucion").Value, urlGetNotaCredito = op.Element("GetNotaCredito").Value, urlPatchOrdenVenta = op.Element("PatchOrdenVenta").Value, urlPatchPagoRecibido = op.Element("PatchPagoRecibido").Value, urlPatchSocioNegocio = op.Element("PatchSocioNegocio").Value, urlPatchIncidencia = op.Element("PatchIncidencia").Value, urlPatchUbicacion = op.Element("PatchUbicacion").Value, urlPatchDevolucion = op.Element("PatchDevolucion").Value, urlPatchNotaCredito = op.Element("PatchNotaCredito").Value, urlValidarOV = op.Element("ValidarOrden").Value, urlValidarPR = op.Element("ValidarPago").Value, urlValidarBP = op.Element("ValidarSocio").Value, urlValidarAC = op.Element("ValidarIncidencia").Value, urlValidarRT = op.Element("ValidarDevolucion").Value, urlValidarNC = op.Element("ValidarNotaCredito").Value, jsonLog = op.Element("Json").Value }).Single(); this.BaseUrl = xmlURLs.BaseUrl; this.urlServiceLayer = xmlURLs.urlServiceLayer; this.urlGetEmpresa = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetEmpresa; this.urlGetOrdenVenta = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetOrdenVenta; this.urlGetPagoRecibido = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetPagoRecibido; this.urlGetSocioNegocio = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetSocioNegocio; this.urlGetIncidencia = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetIncidencia; this.urlGetUbicaciones = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetUbicaciones; this.urlGetDevolucion = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetDevolucion; this.urlGetNotaCredito = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlGetNotaCredito; this.urlPatchOrdenVenta = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchOrdenVenta; this.urlPatchPagoRecibido = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchPagoRecibido; this.urlPatchSocioNegocio = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchSocioNegocio; this.urlPatchIncidencia = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchIncidencia; this.urlPatchUbicacion = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchUbicacion; this.urlPatchDevolucion = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchDevolucion; this.urlPatchNotaCredito = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlPatchNotaCredito; this.pathJSONLog = xmlURLs.jsonLog; this.urlValidarOrdenVenta = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlValidarOV; this.urlValidarPagoRecibido = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlValidarPR; this.urlValidarSocioNegocio = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlValidarBP; this.urlValidarIncidencia = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlValidarAC; this.urlValidarDevolucion = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlValidarRT; this.urlValidarNotaCredito = Util.castURL(this.BaseUrl, "/") + xmlURLs.urlValidarNC; this.datosValidos = true; } catch (Exception ex) { this.datosValidos = false; MainProcess.log.Error("Error en archivo de conexión", ex); } }
private void buttonImportAll_Click(object sender, EventArgs e) { bool mergesentries = false; if (CredentialList.MediaServicesAccounts.Count > 0) // There are entries. Let's ask if user want to delete them or merge { if (System.Windows.Forms.MessageBox.Show(AMSExplorer.Properties.Resources.AMSLogin_buttonImportAll_Click_ThereAreCurrentEntriesInTheListNDoYouWantReplaceThemWithTheNewOnesOrDoAMergeNNSelectYesToReplaceThemNoToMergeThem, AMSExplorer.Properties.Resources.AMSLogin_buttonImportAll_Click_ImportAndReplace, System.Windows.Forms.MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { mergesentries = true; } } DialogResult diares = openFileDialog1.ShowDialog(); if (diares == DialogResult.OK) { if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".xml") // XML file { XDocument xmlimport = new XDocument(); System.IO.Stream myStream = openFileDialog1.OpenFile(); xmlimport = XDocument.Load(myStream); var test = xmlimport.Descendants("Credentials").FirstOrDefault(); Version version = new Version(xmlimport.Descendants("Credentials").Attributes("Version").FirstOrDefault().Value.ToString()); if ((test != null) && (version >= new Version("1.0"))) { if (!mergesentries) { CredentialList.MediaServicesAccounts.Clear(); // let's purge entries if user does not want to keep them } try { foreach (var att in xmlimport.Descendants("Credentials").Elements("Entry")) { string OtherManagementPortal = ""; if ((version >= new Version("1.1")) && (att.Attribute("OtherManagementPortal")) != null) { OtherManagementPortal = att.Attribute("OtherManagementPortal").Value.ToString(); } string OtherAzureEndpoint = ""; if (att.Attribute("OtherAzureEndpoint") != null) { OtherAzureEndpoint = att.Attribute("OtherAzureEndpoint").Value.ToString(); } CredentialList.MediaServicesAccounts.Add(new CredentialsEntry( att.Attribute("AccountName").Value.ToString(), att.Attribute("AccountKey").Value.ToString(), string.Empty, // client id not stored in XML string.Empty, // client secret not stored in XML att.Attribute("StorageKey").Value.ToString(), att.Attribute("Description").Value.ToString(), false, false, att.Attribute("UsePartnerAPI").Value.ToString() == true.ToString() ? true : false, att.Attribute("UseOtherAPI").Value.ToString() == true.ToString() ? true : false, att.Attribute("OtherAPIServer").Value.ToString(), att.Attribute("OtherScope").Value.ToString(), att.Attribute("OtherACSBaseAddress").Value.ToString(), OtherAzureEndpoint, OtherManagementPortal )); } } catch { MessageBox.Show(AMSExplorer.Properties.Resources.AMSLogin_buttonImportAll_Click_FileNotRecognizedOrIncorrect); return; } listViewAccounts.Items.Clear(); DoClearFields(); CredentialList.MediaServicesAccounts.ForEach(c => AddItemToListviewAccounts(c) /* listViewAccounts.Items.Add(ReturnAccountName(c))*/); buttonExport.Enabled = (listViewAccounts.Items.Count > 0); // let's save the list of credentials in settings Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); } else { MessageBox.Show("Wrong XML file."); return; } } else if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".json") { string json = System.IO.File.ReadAllText(openFileDialog1.FileName); if (!mergesentries) { CredentialList.MediaServicesAccounts.Clear(); // let's purge entries if user does not want to keep them } var ImportedCredentialList = (ListCredentials)JsonConvert.DeserializeObject(json, typeof(ListCredentials)); CredentialList.MediaServicesAccounts.AddRange(ImportedCredentialList.MediaServicesAccounts); listViewAccounts.Items.Clear(); DoClearFields(); CredentialList.MediaServicesAccounts.ForEach(c => AddItemToListviewAccounts(c) /* listViewAccounts.Items.Add(ReturnAccountName(c))*/); buttonExport.Enabled = (listViewAccounts.Items.Count > 0); // let's save the list of credentials in settings Properties.Settings.Default.LoginListJSON = JsonConvert.SerializeObject(CredentialList); Program.SaveAndProtectUserConfig(); LoginCredentials = null; } } }
/// <summary> /// 获得单个节点 /// </summary> public XElement GetNode(string name) { return(_document?.Descendants(name).FirstOrDefault()); }
public List <RegionView> Result(int user_id) { List <RegionView> RegionAdd = new List <RegionView>(); List <RegionNameID> regionNames = new List <RegionNameID>(); List <RegionNameID> regionNamesCancels = new List <RegionNameID>(); regionNames.AddRange(userCityGo.Result(user_id)); regionNames.AddRange(userRegionGoDamage.Result(user_id)); regionNamesCancels.AddRange(userRegionGoCancellation.Result(user_id)); foreach (var item in regionNamesCancels) { var counts = 1; var sp = Newtonsoft.Json.JsonConvert.DeserializeObject <CancellationCardNum>(item.data); XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/city_xml.xml")); if (doc != null && sp != null && sp.Customer_City != null) { var nameRegion = doc.Descendants("place").Where(c => c.Element("city").Value.StartsWith(sp.Customer_City)).Select(c => c.Element("city").Value + " - " + c.Element("raion").Value).FirstOrDefault(); if (nameRegion == null) { var reg = RegionAdd.Where(c => c.name == user_id + sp.Customer_City).FirstOrDefault(); if (reg != null) { counts = reg.count; counts++; RegionAdd.Remove(reg); } RegionAdd.Add(new RegionView { name = user_id + sp.Customer_City, id = item.id, count = counts }); } else { if (RegionAdd.Select(s => s.name).Contains(user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2))) { var reg = RegionAdd.Where(c => c.name == user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2)).FirstOrDefault(); counts = reg.count; counts++; RegionAdd.Remove(reg); RegionAdd.Add(new RegionView { name = user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2), id = item.id, count = counts }); } else { RegionAdd.Add(new RegionView { name = user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2), id = item.id, count = 1 }); } } } } foreach (var item in regionNames) { var counts = 1; var sp = Newtonsoft.Json.JsonConvert.DeserializeObject <Abonent>(item.data); XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/city_xml.xml")); if (doc != null && sp.Customer != null && sp.Customer.City != null) { var nameRegion = doc.Descendants("place").Where(c => c.Element("city").Value.StartsWith(sp.Customer.City)).Select(c => c.Element("city").Value + " - " + c.Element("raion").Value).FirstOrDefault(); if (nameRegion == null) { var reg = RegionAdd.Where(c => c.name == user_id + sp.Customer.City).FirstOrDefault(); if (reg != null) { counts = reg.count; counts++; RegionAdd.Remove(reg); } RegionAdd.Add(new RegionView { name = user_id + sp.Customer.City, id = item.id, count = counts }); } else { if (RegionAdd.Select(s => s.name).Contains(user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2))) { var reg = RegionAdd.Where(c => c.name == user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2)).FirstOrDefault(); counts = reg.count; counts++; RegionAdd.Remove(reg); RegionAdd.Add(new RegionView { name = user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2), id = item.id, count = counts }); } else { RegionAdd.Add(new RegionView { name = user_id + nameRegion.Substring(nameRegion.IndexOf("-") + 2), id = item.id, count = 1 }); } } } } return(RegionAdd); //return RegionAdd.GroupBy(p => p.name) // .Select(g => g.First()) // .ToList(); }
public ActionResult NajdiBod(int id_tr, String nazov, Boolean typ) { Bod bod = new Bod(); bod.id_trasy = id_tr; bod.nazov = nazov; bod.typ = typ; String isFree; String isWeekend; var pocetbodov = (from a in db.bod where a.id_trasy == id_tr select a).Count(); bod.poradie = pocetbodov + 1; if (typ) { XDocument xmlMesto = XDocument.Parse(NajdiMesto(nazov)); var soapResponseArea = xmlMesto.Descendants().Where(x => x.Name.LocalName == "area").FirstOrDefault().Value; String responseArea = soapResponseArea.ToString(); bod.rozloha = float.Parse(responseArea, CultureInfo.InvariantCulture.NumberFormat); var soapResponseX = xmlMesto.Descendants().Where(x => x.Name.LocalName == "coord_lat").FirstOrDefault().Value; String responseX = soapResponseX.ToString(); if (responseX == "") { return(RedirectToAction("NenajdenyBod", "Home")); } bod.suradnica_x = float.Parse(responseX, CultureInfo.InvariantCulture.NumberFormat); String surx = (bod.suradnica_x).ToString().Replace(",", "."); var soapResponseY = xmlMesto.Descendants().Where(x => x.Name.LocalName == "coord_lon").FirstOrDefault().Value; String responseY = soapResponseY.ToString(); bod.suradnica_y = float.Parse(responseY, CultureInfo.InvariantCulture.NumberFormat); String sury = (bod.suradnica_y).ToString().Replace(",", "."); XDocument xml = XDocument.Parse(Execute(surx, sury, DateTime.Now.Year.ToString())); var soapResponse = xml.Descendants().Where(x => x.Name.LocalName == "average").FirstOrDefault().Value; String response = soapResponse.ToString(); float poc = float.Parse(response, CultureInfo.InvariantCulture.NumberFormat); bod.pocasie = (float)Math.Round((double)poc, 1); DateTime today = DateTime.Today; XDocument xml3 = XDocument.Parse(JeVikend(today.ToString("yyyy-mm-dd"))); var soapResponse3 = xml3.Descendants().Where(x => x.Name.LocalName == "je_vikend").FirstOrDefault().Value; String response3 = soapResponse3.ToString(); isWeekend = response3; XDocument xml4 = XDocument.Parse(JeSviatok(today.Month, today.Day)); var soapResponse4 = xml4.Descendants().Where(x => x.Name.LocalName == "is_free").FirstOrDefault().Value; String response4 = soapResponse4.ToString(); isFree = response4; int area = int.Parse((bod.rozloha).ToString().Replace(",", ".")); XDocument xml5 = XDocument.Parse(NajdiRestauraciu(area)); var soapResponse5 = xml5.Descendants().Where(x => x.Name.LocalName == "FindRestaurantResult").FirstOrDefault().Value; String response5 = soapResponse5.ToString(); bod.podnik = Convert.ToBoolean(response5); if (bod.podnik) { XDocument xml6 = XDocument.Parse(JeOtvorena(isWeekend, isFree)); var soapResponse6 = xml6.Descendants().Where(x => x.Name.LocalName == "IsOpenResult").FirstOrDefault().Value; String response6 = soapResponse6.ToString(); bod.otvrHodiny = response6; } else { bod.otvrHodiny = "----------"; } } else { XDocument xmlObec = XDocument.Parse(NajdiObec(nazov)); var soapResponseArea2 = xmlObec.Descendants().Where(x => x.Name.LocalName == "area").FirstOrDefault().Value; String responseArea2 = soapResponseArea2.ToString(); bod.rozloha = float.Parse(responseArea2, CultureInfo.InvariantCulture.NumberFormat); var soapResponseX2 = xmlObec.Descendants().Where(x => x.Name.LocalName == "coord_lat").FirstOrDefault().Value; String responseX2 = soapResponseX2.ToString(); if (responseX2 == "") { return(RedirectToAction("NenajdenyBod", "Home")); } bod.suradnica_x = float.Parse(responseX2, CultureInfo.InvariantCulture.NumberFormat); String surx2 = (bod.suradnica_x).ToString().Replace(",", "."); var soapResponseY2 = xmlObec.Descendants().Where(x => x.Name.LocalName == "coord_lon").FirstOrDefault().Value; String responseY2 = soapResponseY2.ToString(); bod.suradnica_y = float.Parse(responseY2, CultureInfo.InvariantCulture.NumberFormat); String sury2 = (bod.suradnica_y).ToString().Replace(",", "."); XDocument xml2 = XDocument.Parse(Execute(surx2, sury2, DateTime.Now.Year.ToString())); var soapResponse2 = xml2.Descendants().Where(x => x.Name.LocalName == "average").FirstOrDefault().Value; String response2 = soapResponse2.ToString(); float poc = float.Parse(response2, CultureInfo.InvariantCulture.NumberFormat); bod.pocasie = (float)Math.Round((double)poc, 1); DateTime today = DateTime.Today; XDocument xml3 = XDocument.Parse(JeVikend(today.ToString("yyyy-mm-dd"))); var soapResponse3 = xml3.Descendants().Where(x => x.Name.LocalName == "je_vikend").FirstOrDefault().Value; String response3 = soapResponse3.ToString(); isWeekend = response3; XDocument xml4 = XDocument.Parse(JeSviatok(today.Month, today.Day)); var soapResponse4 = xml4.Descendants().Where(x => x.Name.LocalName == "is_free").FirstOrDefault().Value; String response4 = soapResponse4.ToString(); isFree = response4; int area = int.Parse((bod.rozloha).ToString().Replace(",", ".")); XDocument xml5 = XDocument.Parse(NajdiRestauraciu(area)); var soapResponse5 = xml5.Descendants().Where(x => x.Name.LocalName == "FindRestaurantResult").FirstOrDefault().Value; String response5 = soapResponse5.ToString(); bod.podnik = Convert.ToBoolean(response5); if (bod.podnik) { XDocument xml6 = XDocument.Parse(JeOtvorena(isWeekend, isFree)); var soapResponse6 = xml6.Descendants().Where(x => x.Name.LocalName == "IsOpenResult").FirstOrDefault().Value; String response6 = soapResponse6.ToString(); bod.otvrHodiny = response6; } else { bod.otvrHodiny = "----------"; } } db.bod.Add(bod); db.SaveChanges(); return(RedirectToAction("ZoznamBodov", "Home", new { id_tr = bod.id_trasy })); }
public IEnumerable <IbuttonObj> GetAll() { return(doc.Descendants(RootXname).Select(element => element.FromXElement <IbuttonObj>())); }
public int ReadFraSFtp() { string homedir = m_sftp.RealPath(".", ""); // Open a directory on the server... string handle = m_sftp.OpenDir(m_Outbound); if (handle == null) { throw new Exception(m_sftp.LastErrorText); } // Download the directory listing: Chilkat.SFtpDir dirListing = null; dirListing = m_sftp.ReadDir(handle); if (dirListing == null) { throw new Exception(m_sftp.LastErrorText); } Program.memPbsnetdir = null; //opret ny memPbsnetdir // Iterate over the files. int i; int n = dirListing.NumFilesAndDirs; if (n > 0) { for (i = 0; i <= n - 1; i++) { Chilkat.SFtpFile fileObj = null; fileObj = dirListing.GetFileObject(i); if (!fileObj.IsDirectory) { DateTime testLastAccessTime = fileObj.LastAccessTime; recPbsnetdir rec = new recPbsnetdir { Type = 8, Path = dirListing.OriginalPath, Filename = fileObj.Filename, Size = (int)fileObj.Size32, Atime = Unspecified2Utc(fileObj.LastAccessTime), Mtime = Unspecified2Utc(fileObj.LastModifiedTime), Gid = fileObj.Gid, Uid = fileObj.Uid, Perm = fileObj.Permissions.ToString() }; Program.memPbsnetdir.Add(rec); } } } // Close the directory bool success = m_sftp.CloseHandle(handle); if (!success) { throw new Exception(m_sftp.LastErrorText); } var leftqry_pbsnetdir = from h in Program.memPbsnetdir select h; int AntalFiler = leftqry_pbsnetdir.Count(); if (leftqry_pbsnetdir.Count() > 0) { foreach (var rec_pbsnetdir in leftqry_pbsnetdir) { // Open a file on the server: string fullpath = rec_pbsnetdir.Path + "/" + rec_pbsnetdir.Filename; string filehandle = m_sftp.OpenFile(fullpath, "readOnly", "openExisting"); if (filehandle == null) { throw new Exception(m_sftp.LastErrorText); } int numBytes = (int)rec_pbsnetdir.Size; if (numBytes < 0) { throw new Exception(m_sftp.LastErrorText); } byte[] b_data = null; b_data = m_sftp.ReadFileBytes(handle, numBytes); if (b_data == null) { throw new Exception(m_sftp.LastErrorText); } sendAttachedFile(rec_pbsnetdir.Filename, b_data, false); char[] c_data = System.Text.Encoding.GetEncoding("windows-1252").GetString(b_data).ToCharArray(); string filecontens = new string(c_data); string filecontens2 = filecontens.TrimEnd('\n'); string filecontens3 = filecontens2.TrimEnd('\r'); string filecontens4 = filecontens3.TrimEnd('\n'); XElement xmlPbsfilesAdd = new XElement("Pbsfiles"); xmlPbsfilesAdd.Add(new XElement("Type", rec_pbsnetdir.Type)); xmlPbsfilesAdd.Add(new XElement("Path", rec_pbsnetdir.Path)); xmlPbsfilesAdd.Add(new XElement("Filename", rec_pbsnetdir.Filename)); xmlPbsfilesAdd.Add(new XElement("Size", rec_pbsnetdir.Size)); xmlPbsfilesAdd.Add(new XElement("Atime", rec_pbsnetdir.Atime)); xmlPbsfilesAdd.Add(new XElement("Mtime", rec_pbsnetdir.Mtime)); xmlPbsfilesAdd.Add(new XElement("Transmittime", DateTime.Now)); xmlPbsfilesAdd.Add(new XElement("Data", filecontens4)); string strxmlPbsfilesAdd = @"<?xml version=""1.0"" encoding=""utf-8"" ?> " + xmlPbsfilesAdd.ToString(); Guid id1 = clsSQLite.insertStoreXML(Program.AppEngName, false, Program.sftpName, strxmlPbsfilesAdd, ""); clsRest objRest = new clsRest(); string strxmldata = objRest.HttpPost2(clsRest.urlBaseType.data, "frapbs", strxmlPbsfilesAdd); XDocument xmldata = XDocument.Parse(strxmldata); string Status = xmldata.Descendants("Status").First().Value; if (Status == "True") { clsSQLite.updateStoreXML(id1, true); } // Close the file. success = m_sftp.CloseHandle(filehandle); if (success != true) { throw new Exception(m_sftp.LastErrorText); } } } return(AntalFiler); }
public IEnumerable <string> GetListOfAssets(XDocument xdoc) { return(xdoc.Descendants() .Where(x => x.Attribute("dependentAsset") != null && !string.IsNullOrWhiteSpace(x.Attribute("dependentAsset").Value)) .Select(x => x.Attribute("dependentAsset").Value)); }
public static void DescendantsWithXNameOnXDocBeforeAndAfter() { XElement a = new XElement("A", "a"), b = new XElement("B", "b"); b.Add(b, b); a.Add(b); XDocument xDoc = new XDocument(a); IEnumerable<XElement> nodes = xDoc.Descendants("B"); Assert.Equal(4, nodes.Count()); b.Remove(); Assert.Equal(0, nodes.Count()); }
public clsSFTP() { clsRest objRest = new clsRest(); string strxmldata = objRest.HttpGet2(clsRest.urlBaseType.data, "sftp/" + Program.sftpName); XDocument xdoc = XDocument.Parse(strxmldata); string Status = xdoc.Descendants("Status").First().Value; if (Status != "True") { throw new Exception("Getting sftp-data for " + Program.sftpName + " failed."); } m_SftpId = xdoc.Descendants("Id").First().Value; m_SftpNavn = xdoc.Descendants("Navn").First().Value; m_Host = xdoc.Descendants("Host").First().Value; m_Port = xdoc.Descendants("Port").First().Value; m_Certificate = xdoc.Descendants("Certificate").First().Value; m_Pincode = xdoc.Descendants("Pincode").First().Value; m_User = xdoc.Descendants("User").First().Value; m_Outbound = xdoc.Descendants("Outbound").First().Value; m_Inbound = xdoc.Descendants("Inbound").First().Value; m_sftp = new SFtp(); bool success = m_sftp.UnlockComponent("HAFSJOSSH_6pspJCMP1QnW"); if (!success) { throw new Exception(m_sftp.LastErrorText); } m_sftp.ConnectTimeoutMs = 60000; m_sftp.IdleTimeoutMs = 55000; success = m_sftp.Connect(m_Host, int.Parse(m_Port)); if (!success) { throw new Exception(m_sftp.LastErrorText); } Chilkat.SshKey key = new Chilkat.SshKey(); string privKey = m_Certificate; if (privKey == null) { throw new Exception(m_sftp.LastErrorText); } key.Password = m_Pincode; success = key.FromOpenSshPrivateKey(privKey); if (!success) { throw new Exception(m_sftp.LastErrorText); } success = m_sftp.AuthenticatePk(m_User, key); if (!success) { throw new Exception(m_sftp.LastErrorText); } // After authenticating, the SFTP subsystem must be initialized: success = m_sftp.InitializeSftp(); if (!success) { throw new Exception(m_sftp.LastErrorText); } }