string XMLSerialize(object oResult) // http://msdn.microsoft.com/en-us/library/58a18dwa(v=VS.100).aspx { IXmlWritable wResult = oResult as IXmlWritable; if (wResult != null) { XmlSerializer ser = new XmlSerializer(typeof(XmlElement)); TextWriter writer = new Utf8StringWriter(); XmlContext context = new XmlContext(); // context.Document = new XmlDocument(); // XmlElement wElement = wResult.ToXml(context);; // XmlElement rootElement = context.CreateElement("Root"); rootElement.Attributes.Append(context.CreateAttribute("randSeed", MiscUtil.RandSeed)); rootElement.AppendChild(wElement); // context.Document.AppendChild(rootElement); // ser.Serialize(writer, context.Document); writer.Close(); return writer.ToString(); } return null; }
public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.ContentType = "application/xml"; using (var txtWriter = new Utf8StringWriter()) { var xmlWriter = XmlWriter.Create(txtWriter, new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, OmitXmlDeclaration = false }); // Write the Processing Instruction node. var xsltHeader = string.Format("type=\"text/xsl\" href=\"{0}\"", _model.RootBlogNode.UrlWithDomain().EnsureEndsWith('/') + "rss/xslt"); xmlWriter.WriteProcessingInstruction("xml-stylesheet", xsltHeader); var formatter = _feed.GetRss20Formatter(); formatter.WriteTo(xmlWriter); xmlWriter.Flush(); context.HttpContext.Response.Write(txtWriter.ToString()); } }
/// <summary> /// Returns the document encoded with UTF-8. /// </summary> public static string ToUtf8DocumentString(this XDocument doc) { var writer = new Utf8StringWriter(); doc.Declaration = new XDeclaration("1.0", "utf-8", null); doc.Save(writer, SaveOptions.None); return writer.ToString(); }
public ENMLWriter() { Contents = new Utf8StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Auto; //writer = XmlWriter.Create(Contents, settings) writer = XmlWriter.Create(Contents); writer.WriteDocType("en-note", null, "http://xml.evernote.com/pub/enml2.dtd", null); }
String Serialize() { // Additional information: Could not load file or assembly 'CyPhy2CAD_CSharp.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8adbc89a2d94c2a4' or one of its dependencies. The system cannot find the file specified. XmlSerializer xs = new XmlSerializer(this.GetType()); // n.b. An exception is expected here. It is caught inside of the .NET framework code StringWriter sw = new Utf8StringWriter(); //StringWriter sw = new StringWriter(); xs.Serialize(sw, this); return sw.ToString(); }
public StudyXmlNode(XmlNode node) { using (TextWriter writer = new Utf8StringWriter()) { using (XmlWriter xmlWriter = XmlWriter.Create(writer,new XmlWriterSettings(){ConformanceLevel = ConformanceLevel.Fragment})) { node.WriteTo(xmlWriter); } XmlElementFragment = writer.ToString(); } }
public static string ConvertToADX(ADIFData data) { var serializer = new XmlSerializer(typeof(ADIFData)); var ns = new XmlSerializerNamespaces(); ns.Add("", ""); using (var sw = new Utf8StringWriter()) { serializer.Serialize(sw, data, ns); return sw.ToString(); } }
public void reproduce_xml_enocoding_issue() { string xml = @"<some-element>© JNCC</some-element>"; var doc = XDocument.Parse(xml); doc.Declaration = new XDeclaration("1.0", "utf-8", null); var writer = new Utf8StringWriter(); doc.Save(writer, SaveOptions.None); string metaXmlDoc = writer.ToString(); // // string xml = @"<some-element>© JNCC</some-element>"; // var doc = XDocument.Parse(xml); // doc.ToString().Should().Contain("©"); // doc.ToString().Should().NotContain("©"); }
public static XmlDocument ToXML(this Object oObject) { XmlDocument xmlDoc = new XmlDocument(); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer xmlSerializer = new XmlSerializer(oObject.GetType()); using (StringWriter writer = new Utf8StringWriter()) { xmlSerializer.Serialize(writer, oObject, ns); var utf8 = writer.ToString(); var XmlDoc = new XmlDocument(); XmlDoc.LoadXml(utf8); return XmlDoc; } }
// NOTE: Good to have // - automatic nuget package download // - stylecop file or directory exclude list static CodeAnalysisVsHook() { ProjectFilesGenerator.ProjectFileGeneration += (name, content) => { var rulesetPath = GetRulesetFile(); if (string.IsNullOrEmpty(rulesetPath)) return content; var getStyleCopAnalyzersPath = GetStyleCopAnalyzersPath(); if (string.IsNullOrEmpty(getStyleCopAnalyzersPath)) return content; // Insert a ruleset file and StyleCop.Analyzers into a project file var document = XDocument.Parse(content); var ns = document.Root.Name.Namespace; var propertyGroup = document.Root.Descendants(ns + "PropertyGroup").FirstOrDefault(); if (propertyGroup != null) { propertyGroup.Add(new XElement(ns + "CodeAnalysisRuleSet", rulesetPath)); } var itemGroup = document.Root.Descendants(ns + "ItemGroup").LastOrDefault(); if (itemGroup != null) { var newItemGroup = new XElement(ns + "ItemGroup"); foreach (var file in Directory.GetFiles(getStyleCopAnalyzersPath + @"\analyzers\dotnet\cs", "*.dll")) { newItemGroup.Add(new XElement(ns + "Analyzer", new XAttribute("Include", file))); } itemGroup.AddAfterSelf(newItemGroup); } var str = new Utf8StringWriter(); document.Save(str); return str.ToString(); }; }
/// <summary> /// Returns the dgml representation of the graph /// </summary> /// <returns>Graph as dgml string</returns> public string ToDgml() { XmlRootAttribute root = new XmlRootAttribute("DirectedGraph") { Namespace = "http://schemas.microsoft.com/vs/2009/dgml", }; XmlSerializer serializer = new XmlSerializer(typeof(Graph), root); XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8, }; StringWriter dgml = new Utf8StringWriter(); using (XmlWriter xmlWriter = XmlWriter.Create(dgml, settings)) { serializer.Serialize(xmlWriter, this); } return dgml.ToString(); }
/// <summary> /// Exports given AttributeSets, Entities and Templates to an XML and returns the XML as string. /// </summary> /// <returns></returns> public string GenerateNiceXml() { var doc = ExportXDocument; // Will be used to show an export protocoll in future Messages = null; // Write XDocument to string and return it var xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, Indent = true }; using (var stringWriter = new Utf8StringWriter()) { using (var writer = XmlWriter.Create(stringWriter, xmlSettings)) doc.Save(writer); return stringWriter.ToString(); } }
static StyleCopAnalyzerHook() { ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) => { var document = XDocument.Parse(content); var x = new XElement("ItemGroup", new XElement("Analyzer", new XAttribute("Include", "packages\\StyleCop.Analyzers.1.0.0\\analyzers\\dotnet\\cs\\StyleCop.Analyzers.CodeFixes.dll")), new XElement("Analyzer", new XAttribute("Include", "packages\\StyleCop.Analyzers.1.0.0\\analyzers\\dotnet\\cs\\StyleCop.Analyzers.dll")) ); Debug.Log("[Hook]" + name + " " + document); XElement projectNode = FindElement(document, "Project"); if (projectNode == null) { Debug.LogError("Could not find project node"); } XElement includeNode = FindElement(projectNode, "Import"); if (includeNode == null) { Debug.LogError("Could not find import node"); } includeNode.AddBeforeSelf(x); // Prevents the save adding a xmlns attribute by inheriting the namespace (xmlns) of the parent, removing the need for it in the child x.Attributes("xmlns").Remove(); x.Name = x.Parent.Name.Namespace + x.Name.LocalName; var str = new Utf8StringWriter(); document.Save(str); return(str.ToString()); }; }
/// <summary> /// Serializes the object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj">Object to serialize.</param> /// <seealso cref="https://stackoverflow.com/questions/1081325/c-sharp-how-to-xml-deserialize-object-itself"/> public static string SerializeObjectToXml <T>(this T obj) { if (obj == null) { return(string.Empty); } try { XmlSerializer XmlSerializer = new XmlSerializer(obj.GetType()); XmlWriterSettings Settings = new XmlWriterSettings(); XmlSerializerNamespaces XmlSerializerNs = new XmlSerializerNamespaces(); Settings.Encoding = Encoding.UTF8; Settings.Indent = true; Settings.OmitXmlDeclaration = true; Settings.NewLineHandling = NewLineHandling.None; XmlSerializerNs.Add(string.Empty, string.Empty); using (Utf8StringWriter Utf8Writer = new Utf8StringWriter()) { using (XmlWriter Writer = XmlWriter.Create(Utf8Writer, Settings)) { XmlSerializer.Serialize(Writer, obj, XmlSerializerNs); } return(Utf8Writer.ToString()); } } catch (Exception ex) { throw new Exception("SerializeObjectToXml: An error occurred", ex); } }
/// <summary> /// Exports given AttributeSets, Entities and Templates to an XML and returns the XML as string. /// </summary> /// <returns></returns> public string GenerateNiceXml() { EnsureThisIsInitialized(); var doc = ExportXDocument; // Will be used to show an export protocoll in future Messages = null; // Write XDocument to string and return it var xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, Indent = true }; using (var stringWriter = new Utf8StringWriter()) { using (var writer = XmlWriter.Create(stringWriter, xmlSettings)) doc.Save(writer); return(stringWriter.ToString()); } }
private ContentResult ListOfItemsXml() { _logger.LogInformation("responde with ListOfItemsXml"); var stations = _stationsRepo.GetAllAsync().Result.Take(8); var doc = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("ListOfItems", new XElement("ItemCount", stations.Count()), stations.Select(x => new XElement("Item", new XElement("ItemType", x.Item.ItemType), new XElement("StationName", x.Item.StationName), new XElement("StationUrl", x.Item.StationUrl) ) )) ); var wr = new Utf8StringWriter(); doc.Save(wr, SaveOptions.None); var xml = wr.ToString(); //Response.ContentLength = xml.Length; Response.ContentType = "text/html"; return(Content(xml)); }
public static string Serialize <T>(T anything, bool includeDeclaration = false, bool includeNamespaces = false) { using var writer = new Utf8StringWriter(CultureInfo.InvariantCulture); var settings = new XmlWriterSettings { OmitXmlDeclaration = !includeDeclaration, Encoding = Encoding.UTF8 }; var names = new XmlSerializerNamespaces(); names.Add("", ""); using var xmlWriter = XmlWriter.Create(writer, settings); var serializer = GetCachedOrCreate(typeof(T)); if (includeNamespaces) { serializer.Serialize(xmlWriter, anything); } else { serializer.Serialize(xmlWriter, anything, names); } return(writer.ToString()); }
private string GetSitemapIndexXMLString() { using (StringWriter str = new Utf8StringWriter()) using (XmlWriter writer = XmlWriter.Create(str)) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9"); XmlSerializer xser = new XmlSerializer(typeof(SiteMapIndexModel)); var obj = new SiteMapIndexModel { SiteMapIndexUrls = { new SiteMapIndexNodeModel { Url = "userpages.xml" }, new SiteMapIndexNodeModel { Url = "testpage.xml" } } }; xser.Serialize(writer, obj, ns); return(str.ToString()); } }
public void Save(string path) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); //Add an empty namespace and empty value ns.Add("", ""); XmlSerializer serializer = new XmlSerializer(typeof(GanttProject)); var subReq = this; var xml = ""; var stringWriter = new Utf8StringWriter(); var settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8, }; using (var ms = new MemoryStream()) { using (var xw = XmlWriter.Create(ms, settings)) // Remember to stop using XmlTextWriter { serializer = new XmlSerializer(typeof(GanttProject)); serializer.Serialize(xw, this, ns); xw.Flush(); } ms.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(ms, Encoding.UTF8)) { xml = sr.ReadToEnd(); } } Console.WriteLine(xml); File.WriteAllText(@"D:\Repos\GanttProjectDotNet\test.gan", xml, Encoding.UTF8); }
public RobotsMiddleware(SitemapSettings settings, ILocationHelper locationHelper) { var sw = new Utf8StringWriter(); foreach (var item in settings.GetUserAgents()) { sw.Write("User-agent: {0}\n", item.UserAgent); foreach (var allow in item.Allows) { sw.Write("Allow: {0}\n", allow); } foreach (var disallow in item.Disallows) { sw.Write("Disallow: {0}\n", disallow); } sw.WriteLine(); } sw.Write("Sitemap: " + locationHelper.GetSitemapUrl(settings.SitemapPath)); Content = sw.ToString(); }
/// <summary> /// Formats the <paramref name="report"/> with line breaks and white spaces. /// </summary> /// <param name="report">The report to format.</param> /// <exception cref="XmlException"><paramref name="report"/> is no valid xml.</exception> /// <returns><b>null</b>, if <paramref name="report"/> is <b>null</b>, otherwise the formatted report.</returns> string IXmlFormatService.FormatDeployReport(string report) { if (report == null) { return(null); } var doc = XDocument.Parse(report); var settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace }; using (var stringWriter = new Utf8StringWriter()) { using (var xmlWriter = XmlWriter.Create(stringWriter, settings)) doc.Save(xmlWriter); return(stringWriter.ToString()); } }
public static void SerializeToXml(string path, IEnumerable <ShortcutInfo> shortcuts) { var doc = new XDocument( new XElement( new XElement( "Shortcuts", shortcuts.Select(f => new XElement( nameof(ShortcutInfo), new XAttribute(nameof(f.Value), f.Value), new XAttribute(nameof(f.Description), f.Description), new XAttribute(nameof(f.Comment), f.Comment), new XElement(nameof(f.Languages), f.Languages.Select(language => new XElement(nameof(Language), language.ToString()))), new XElement(nameof(f.Tags), f.Tags.Select(tag => new XElement("Tag", tag))) ) ) ) ) ); using (var stringWriter = new Utf8StringWriter()) { var xmlWriterSettings = new XmlWriterSettings() { OmitXmlDeclaration = false, NewLineChars = "\r\n", IndentChars = " ", Indent = true }; using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings)) doc.WriteTo(xmlWriter); IOUtility.WriteAllText(path, stringWriter.ToString()); } }
public override string ToString() { var root = new XElement("rsp", new XAttribute("stat", this.Stat.ToString())); if (Stat == ResponseStat.failed || Stat == ResponseStat.fail) root.Add(new XElement("err", new XAttribute("code", ErrorCode), new XAttribute("msg", ErrorMessage ?? ""))); else { switch (this.Type) { case ResponseType.SessionInitiate: root.Add(new XElement("sid", this.Sid ?? ""), new XElement("salt", this.Salt ?? "")); break; case ResponseType.SessionLogin: root.Add(new XElement("sid", this.Sid ?? "")); break; case ResponseType.SettingList: root.Add(new XElement("Version", this.Version ?? ""), new XElement("NextPVRVersion", this.NextPvrVersion ?? ""), new XElement("ChannelsUseSegmenter", this.ChannelsUseSegmenter), new XElement("RecordingsUseSegmenter", this.RecordingsUseSegmenter), new XElement("ChannelDetailsLevel", this.ChannelDetailsLevel), new XElement("StreamingPort", this.StreamingPort)); break; case ResponseType.ChannelListings: { XElement listings = new XElement("listings", new XElement("channel_id", this.ChannelOid)); listings.Add(this.Listings.Select(x => new XElement("l", new XElement("id", x.OID), new XElement("name", x.Title), new XElement("description", x.Description), new XElement("start", x.StartTime.ToUnixTime()), new XElement("end", x.EndTime.ToUnixTime()), new XElement("genre", x.EncodedGenres)))); root.Add(listings); } break; case ResponseType.ChannelList: { //todo: change type from hardcoded 0x1 (which I assume is live tv...) // 0xa == radio, any other value will be treated like channel root.Add(new XElement("channels", this.Channels.Select(x => new XElement("channel", new XElement("id", x.Oid), new XElement("name", x.Name), new XElement("number", x.Number), new XElement("type", "0x1"), new XElement("icon", x.HasIcon.ToString().ToLower()))))); } break; case ResponseType.ChannelGroups: { root.Add(new XElement("groups", this.Groups.Select(x => new XElement("group", new XElement("id", x.Name), new XElement("name", x.Name))))); } break; case ResponseType.RecordingList: { Func<NUtility.RecordingStatus, string> statusToString = delegate(NUtility.RecordingStatus status) { switch(status){ case NUtility.RecordingStatus.STATUS_PENDING: return "Pending"; } return String.Empty; }; Dictionary<int, NUtility.RecurringRecording> recurring = Helpers.NpvrCoreHelper.RecurringRecordingLoadAll().ToDictionary(x => x.OID); root.Add(new XElement("recordings", this.Recordings.Select(x => new XElement("recording", new XElement("id", x.OID), new XElement("recurring_parent", x.RecurrenceOid), new XElement("name", x.Name), new XElement("desc", x.Name), // this is a desc, but original service sets this to the same as the name... new XElement("start_time", TimeZone.CurrentTimeZone.ToLocalTime(x.StartTime).ToString("d/M/yyyy h:mm:ss tt")), new XElement("start_time_ticks", x.StartTime.ToUnixTime()), new XElement("duration", x.EndTime.Subtract(x.StartTime).ToString("hh':'mm")), new XElement("duration_seconds", ((int)x.EndTime.Subtract(x.StartTime).TotalSeconds)), new XElement("status", statusToString(x.Status)), new XElement("quality", x.Quality == null ? "QUALITY_DEFAULT" : x.Quality.ToString()), new XElement("channel", x.ChannelOID), new XElement("channel_id", x.ChannelOID), new XElement("recurring", x.RecurrenceOid > 0), new XElement("daymask", x.RecurrenceOid > 0 && recurring.ContainsKey(x.RecurrenceOid) ? recurring[x.RecurrenceOid].DayMask.ToString() : ""), new XElement("recurring_start", x.RecurrenceOid > 0 && recurring.ContainsKey(x.RecurrenceOid) ? recurring[x.RecurrenceOid].StartTime.ToString("d/M/yyyy h:mm:ss tt") : ""), new XElement("recurring_start_ticks", x.RecurrenceOid > 0 && recurring.ContainsKey(x.RecurrenceOid) ? recurring[x.RecurrenceOid].StartTime.Ticks.ToString() : ""), new XElement("recurring_end", x.RecurrenceOid > 0 && recurring.ContainsKey(x.RecurrenceOid) ? recurring[x.RecurrenceOid].EndTime.ToString("d/M/yyyy h:mm:ss tt") : ""), new XElement("recurring_end_ticks", x.RecurrenceOid > 0 && recurring.ContainsKey(x.RecurrenceOid) ? recurring[x.RecurrenceOid].EndTime.Ticks.ToString() : "") )))); } break; } } XDocument doc = new XDocument(root); StringBuilder builder = new StringBuilder(); using (System.IO.TextWriter writer = new Utf8StringWriter(builder)) { doc.Save(writer); } string result = builder.ToString(); result = result.Replace("\"?>", "\" ?>"); return result + Environment.NewLine; }
public ENMLWriter() { Contents = new Utf8StringWriter(); writer = XmlWriter.Create(Contents); writer.WriteDocType("en-note", null, "http://xml.evernote.com/pub/enml2.dtd", null); }
/// <summary> /// Serializes an object as xml. /// </summary> /// <param name="objToSerialize">The object to serialize.</param> /// <returns>The serialized xml string.</returns> /// <remarks><paramref name="objToSerialize"/> must me XmlSerializable. /// </remarks> public static string SerializeAsXmlText(object objToSerialize) { string retval = ""; using (StringWriter writer = new Utf8StringWriter()) { new XmlSerializer(objToSerialize.GetType()).Serialize(writer, objToSerialize); retval = writer.ToString(); } return retval; }
/// <summary> /// 持卡人身分驗證 /// </summary> private static void CreditVerify() { var url = testUrl + verify; var requestXml = ""; #region API文件測試資料 //var otherInfo = new OtherInfo //{ // tag90 = "AB41E66700D097C5C09E22A15AB09243", // tag91 = "03", // tag92 = "BD5A109098FEA61B" //}; //var model = new CreditVerifyReq //{ // mti = "0100", // cardNumber = "4907060600015101", // processingCode = "003001", // amt = "000000000000", // traceNumber = "191025", // localTime = "191025", // localDate = "20180508", // posEntryMode = "812", // expiredDate = "60101674DE3FAD13", // acqBank = "006", // terminalId = "00010002", // merchantId = "006263015610001", // otherInfo = JsonConvert.SerializeObject(otherInfo), //}; //model.verifyCode = GetVerifyCode(model.acqBank, model.localDate, model.localTime, model.merchantId, model.terminalId, model.mti, model.processingCode); // 文件p.51範例 var testCodeP51 = GetVerifyCode("943", "20170314", "031410", "943000000000001", "00010001", "0800", "000000", "112233445566"); var testCodeP33 = GetVerifyCode("006", "20180508", "191025", "006263015610001", "00010002", "0100", "003001"); #endregion var otherInfo = new CreditVerifyOtherInfo { // 加密方式加入Padding = PaddingMode.None則與API文件結果相符 // 舊格式2021/06/30停止支援,須改用新格式 tag90 = GetTag90Old("113005", "A123456789"), // 新格式2020/12/31才啟用 //tag90 = GetTag90("113005", "A123456789", "0900111111", "20991111"), tag91 = "03", // 加密方式加入Padding = PaddingMode.None則與API文件結果相符 tag92 = GetTag92("113005", "123") }; // test 解密 var tag92d = GetTag92Decryptor(otherInfo.tag92); var model = new CreditVerifyReq { // 查詢res 0100 mti = "0100", cardNumber = "4907060600015101", // 查詢:003001 processingCode = "003001", // 固定000000000000 amt = "000000000000", // 交易識別碼(訂單編號) traceNumber = "191025", localTime = "191025", localDate = "20180508", // 設備輸入型態 預設812 posEntryMode = "812", // 加密方式加入Padding = PaddingMode.None則與API文件結果相符 expiredDate = GetExpiredDate("113005", "2318"), acqBank = "006", terminalId = "00010002", merchantId = "006263015610001", otherInfo = JsonConvert.SerializeObject(otherInfo), }; model.verifyCode = GetVerifyCode(model.acqBank, model.localDate, model.localTime, model.merchantId, model.terminalId, model.mti, model.processingCode); using (var stringwriter = new Utf8StringWriter()) { var serializer = new XmlSerializer(typeof(CreditVerifyReq)); var xmlNS = new XmlSerializerNamespaces(); // 加入下行會刪除NameSpance xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" //xmlNS.Add("", "http://www.focas.fisc.com.tw/FiscII/auth2525"); //serializer.Serialize(stringwriter, model, xmlNS); serializer.Serialize(stringwriter, model); requestXml = stringwriter.ToString(); } var response = PostXMLData(url, requestXml); var result = LoadFromXMLString <CreditVerifyResp>(response); }
public bool CreateAndLoadBuffer() { DestroyBuffer(); var pkg = PackageManager.Package as Package; IServiceProvider serviceProvider = pkg; var textLinesType = typeof(VSTextManagerInterop.IVsTextLines); var riid = textLinesType.GUID; var clsid = typeof(VSTextManagerInterop.VsTextBufferClass).GUID; _underlyingBuffer = pkg.CreateInstance(ref clsid, ref riid, textLinesType); Debug.Assert(_underlyingBuffer != null, "Failure while creating buffer."); var buffer = _underlyingBuffer as VSTextManagerInterop.IVsTextLines; Debug.Assert(buffer != null, "Why does buffer not implement IVsTextLines?"); var ows = buffer as IObjectWithSite; if (ows != null) { ows.SetSite(serviceProvider.GetService(typeof(IOleServiceProvider))); } // We want to set the LanguageService SID explicitly to the XML Language Service. // We need turn off GUID_VsBufferDetectLangSID before calling LoadDocData so that the // TextBuffer does not do the work to detect the LanguageService SID from the file extension. var userData = buffer as VSTextManagerInterop.IVsUserData; if (userData != null) { var VsBufferDetectLangSID = new Guid("{17F375AC-C814-11d1-88AD-0000F87579D2}"); //GUID_VsBufferDetectLangSID; VSErrorHandler.ThrowOnFailure(userData.SetData(ref VsBufferDetectLangSID, false)); } var langSid = CommonPackageConstants.xmlEditorLanguageService; VSErrorHandler.ThrowOnFailure(buffer.SetLanguageServiceID(ref langSid)); var persistDocData = buffer as IVsPersistDocData; if (persistDocData != null) { persistDocData.LoadDocData(FileName); var artifactUri = new Uri(FileName); var artifact = PackageManager.Package.ModelManager.GetArtifact(artifactUri); if (artifact != null && artifact.IsCodeGenArtifact) { var standaloneProvider = artifact.XmlModelProvider as StandaloneXmlModelProvider; if (standaloneProvider.ExtensionErrors == null || standaloneProvider.ExtensionErrors.Count == 0) { // If there is a cached code gen artifact, it will have loaded its text buffer using extensions already. // Therefore we can grab the text buffer from that artifact for our docdata buffer, and dispose the // code gen artifact since it's using a XmlProvider that is standalone and won't be supported by the // designer. var projectItem = VsUtils.GetProjectItem(Hierarchy, ItemId); if (projectItem != null) { if (VSHelpers.CheckOutFilesIfEditable(ServiceProvider, new[] { FileName })) { string artifactText = null; using (var writer = new Utf8StringWriter()) { artifact.XDocument.Save(writer, SaveOptions.None); artifactText = writer.ToString(); } if (!String.IsNullOrWhiteSpace(artifactText)) { VsUtils.SetTextForVsTextLines(VsBuffer, artifactText); } } else { ErrorListHelper.LogExtensionErrors( new List <ExtensionError> { new ExtensionError( string.Format( CultureInfo.CurrentCulture, Resources.ExtensionError_SourceControlLock, Path.GetFileName(FileName)), ErrorCodes.ExtensionsError_BufferNotEditable, ExtensionErrorSeverity.Error) }, projectItem); } } PackageManager.Package.ModelManager.ClearArtifact(artifactUri); } else { // If the extensions ran into errors whilst loading, we'll need to re-run extensions anyway so we ignore the cache PackageManager.Package.ModelManager.ClearArtifact(artifactUri); DispatchLoadToExtensions(); } } else { DispatchLoadToExtensions(); } } // DSL exposes the FileNameChanged event which we subscribe to so we can update the moniker inside // the text buffer, which is required to update our model as well as keep the XmlModel in sync. FileNameChanged += OnFileNameChanged; RegisterUndoTracking(); return(true); }
public static string CreateDefaultConfigFile( IEnumerable <RefactoringMetadata> refactorings, IEnumerable <CodeFixMetadata> codeFixes) { using (var stringWriter = new Utf8StringWriter()) { using (XmlWriter writer = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Indent = true, IndentChars = " " })) { string newLineChars = writer.Settings.NewLineChars; string indentChars = writer.Settings.IndentChars; writer.WriteStartDocument(); writer.WriteStartElement("Roslynator"); writer.WriteStartElement("Settings"); writer.WriteStartElement("General"); writer.WriteElementString("PrefixFieldIdentifierWithUnderscore", "true"); writer.WriteEndElement(); writer.WriteStartElement("Refactorings"); foreach (RefactoringMetadata refactoring in refactorings .Where(f => !f.IsObsolete) .OrderBy(f => f.Id)) { writer.WriteWhitespace(newLineChars); writer.WriteWhitespace(indentChars); writer.WriteWhitespace(indentChars); writer.WriteStartElement("Refactoring"); writer.WriteAttributeString("Id", refactoring.Id); writer.WriteAttributeString("IsEnabled", (refactoring.IsEnabledByDefault) ? "true" : "false"); writer.WriteEndElement(); writer.WriteWhitespace(" "); writer.WriteComment($" {refactoring.Title} "); } writer.WriteWhitespace(newLineChars); writer.WriteWhitespace(indentChars); writer.WriteEndElement(); writer.WriteStartElement("CodeFixes"); foreach (CodeFixMetadata codeFix in codeFixes .Where(f => !f.IsObsolete) .OrderBy(f => f.Id)) { writer.WriteWhitespace(newLineChars); writer.WriteWhitespace(indentChars); writer.WriteWhitespace(indentChars); writer.WriteStartElement("CodeFix"); writer.WriteAttributeString("Id", codeFix.Id); writer.WriteAttributeString("IsEnabled", (codeFix.IsEnabledByDefault) ? "true" : "false"); writer.WriteEndElement(); writer.WriteWhitespace(" "); writer.WriteComment($" {codeFix.Title} (fixes {string.Join(", ", codeFix.FixableDiagnosticIds)}) "); } writer.WriteWhitespace(newLineChars); writer.WriteWhitespace(indentChars); writer.WriteEndElement(); } return(stringWriter.ToString()); } }
public static Dictionary <string, string> DecompileToMemory(Stream ms) { Dictionary <string, string> fileMapping = new Dictionary <string, string>(); var coal = new CoalescedFileXml(); coal.Deserialize(ms); XDocument xDoc; XElement rootElement; foreach (var file in coal.Files) { var fileId = Path.GetFileNameWithoutExtension(file.Name); fileId = ProperNames.FirstOrDefault(s => s.Equals(fileId, StringComparison.InvariantCultureIgnoreCase)); xDoc = new XDocument(); rootElement = new XElement("CoalesceAsset"); rootElement.SetAttributeValue("id", fileId); rootElement.SetAttributeValue("name", Path.GetFileName(file.Name)); rootElement.SetAttributeValue("source", file.Name); var sectionsElement = new XElement("Sections"); foreach (var section in file.Sections) { var sectionElement = new XElement("Section"); sectionElement.SetAttributeValue("name", section.Key); // //var classes = Namespace.FromStrings(section.Value.Keys); // foreach (var property in section.Value) { var propertyElement = new XElement("Property"); propertyElement.SetAttributeValue("name", property.Key); if (property.Value.Count > 1) { foreach (var value in property.Value) { var valueElement = new XElement("Value"); var propertyValue = value.Value; valueElement.SetAttributeValue("type", value.Type); if (!string.IsNullOrEmpty(propertyValue)) { propertyValue = SpecialCharacters.Aggregate(propertyValue, (current, c) => current.Replace(c.Key, c.Value)); } valueElement.SetValue(propertyValue ?? "null"); propertyElement.Add(valueElement); } } else { switch (property.Value.Count) { case 1: { propertyElement.SetAttributeValue("type", property.Value[0].Type); var propertyValue = property.Value[0].Value; if (!string.IsNullOrEmpty(propertyValue)) { propertyValue = SpecialCharacters.Aggregate(propertyValue, (current, c) => current.Replace(c.Key, c.Value)); } propertyElement.SetValue(propertyValue ?? "null"); break; } case 0: { propertyElement.SetAttributeValue("type", CoalesceProperty.DefaultValueType); propertyElement.SetValue(""); break; } } } sectionElement.Add(propertyElement); } sectionsElement.Add(sectionElement); } rootElement.Add(sectionsElement); xDoc.Add(rootElement); // using (StringWriter writer = new Utf8StringWriter()) { // Build Xml with xw. //xw.IndentChar = '\t'; //xw.Indentation = 1; //xw.Formatting = Formatting.Indented; //xDoc.Save(xw); ; xDoc.Save(writer, SaveOptions.None); fileMapping[$"{fileId}.xml"] = writer.ToString(); } // //xDoc.Save(iniPath, SaveOptions.None); } return(fileMapping); }
public ContentResult PickupKml() { var ns = XNamespace.Get("http://www.opengis.net/kml/2.2"); var xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement(ns + "kml", new XElement("Document", new XElement("name", "Untitled layer"), new XElement("Placemark", new XElement("styleUrl", "#poly-000000-1-76"), new XElement("name", "Right Now"), new XElement("description", new XCData("June 6 - June 8")), new XElement("Polygon", new XElement("outerBoundaryIs", new XElement("LinearRing", new XElement("tessellate", 1), new XElement("coordinates", "-85.75172424447373,38.245528009039305,0.0 -85.75184226052443,38.24491290647846,0.0 -85.75260400903062,38.240859826739666,0.0 -85.75266838204698,38.237708211493356,0.0 -85.75060844552354,38.2337979962848,0.0 -85.75095176827745,38.23062921938785,0.0 -85.75181007516221,38.2271231776859,0.0 -85.75078010690049,38.22476324676824,0.0 -85.7511234296544,38.221526645583815,0.0 -85.7522392286046,38.217210953348776,0.0 -85.75284004342393,38.21208573634768,0.0 -85.75181007516221,38.21154621882361,0.0 -85.74786186349229,38.21201829687593,0.0 -85.74623108041123,38.21316475939731,0.0 -85.74288368356065,38.21458095287149,0.0 -85.74099540841416,38.215862247029214,0.0 -85.73601722848252,38.21869450142766,0.0 -85.7331848157628,38.220784904198574,0.0 -85.73052406442002,38.22395410997175,0.0 -85.72812080514268,38.2255049475923,0.0 -85.72468757760362,38.22489810202603,0.0 -85.7196235669835,38.2268534751703,0.0 -85.71541786324815,38.229078491017624,0.0 -85.71104049813584,38.223549538198554,0.0 -85.70820808541612,38.21694121408469,0.0 -85.69490432870225,38.2107369350385,0.0 -85.69378852975206,38.20621826852288,0.0 -85.69155693185166,38.203318081031455,0.0 -85.68614959847764,38.20109227738781,0.0 -85.67954063546495,38.195223923424315,0.0 -85.6646919263585,38.20284594655093,0.0 -85.66640854012803,38.205139142488704,0.0 -85.66864013802842,38.20756715356951,0.0 -85.67413330209092,38.215053011238545,0.0 -85.68511963021592,38.223212391277734,0.0 -85.6936168683751,38.22415639295685,0.0 -85.7042598737462,38.230561795045205,0.0 -85.7089805616124,38.23170796539162,0.0 -85.72443008553819,38.2402025472158,0.0 -85.72116851937608,38.24188786213779,0.0 -85.72340011727647,38.2447191032579,0.0 -85.72726249825791,38.24357313799235,0.0 -85.75172424447373,38.245528009039305,0.0") ) ) ) ), new XElement("Style", new XAttribute("id", "poly-000000-1-76"), new XElement("LineStyle", new XElement("color", "ff000000"), new XElement("width", 1) ), new XElement("PolyStyle", new XElement("color", "4C000000"), new XElement("fill", 1), new XElement("outline", 1) ) ) ) ) ); var wr = new Utf8StringWriter(); xmlDoc.Save(wr); return Content(wr.GetStringBuilder().ToString(), "text/xml"); }
protected void Page_Load(object sender, EventArgs e) { using (VendingModelContainer dc = new VendingModelContainer()) { using (var dbContextTransaction = dc.Database.BeginTransaction()) { try { long wvdid = Convert.ToInt64(Request.QueryString["wvdid"]); string prg = Request["prg"]; if (prg != null && wvdid != 0) { DateTime dt = DateTime.Now; //убиваем неподтвержденные заявки на регистрацию, которым больше 3 часов. кто не успел - тот опоздал, блять) long regrequestoldestdatetime = Convert.ToInt64(dt.AddHours(-3).ToString("yyyyMMddHHmmss")); dc.WaterDevices.RemoveRange(dc.WaterDevices.Where(x => x.RegistrationRequestDateTime < regrequestoldestdatetime)); long cdt = Convert.ToInt64(dt.ToString("yyyyMMddHHmmss")); string cdtstr = dt.ToString("dd.MM.yyyy HH:mm:ss"); WaterDevices tmpwd = dc.WaterDevices.Where(x => x.PendingRegistration && x.PendingRegistrationGUID == prg && x.ID == wvdid && !x.PendingRegConfirmed).First(); CryptoHelper ch = new CryptoHelper(); SHA512 sha512 = new SHA512Managed(); //вычисляем хеш открытого ключа устройства byte[] hash = sha512.ComputeHash(tmpwd.PublicKey); //подписываем хеш открытого ключа устройства и формируем ответ. В ответе указываем текущее распределение лицензий с учетом текущей Uri url = new Uri(Request.Url.Authority); string output = url.GetLeftPart(UriPartial.Authority); WaterDeviceRegistrationResponse authresp = new WaterDeviceRegistrationResponse { RegID = tmpwd.ID, ServerEndPoint = output }; authresp.Signature = Convert.ToBase64String(ch.SignHashedData(hash)); int activedevicescount = dc.WaterDevices.Where(x => x.AccountID == tmpwd.AccountID && x.Valid && !x.Suspended && !x.PendingRegistration).Count(); int pendingdevicescount = dc.WaterDevices.Where(x => x.AccountID == tmpwd.AccountID && x.Valid && !x.Suspended && x.PendingRegistration).Count(); Accounts tmpacc = dc.Accounts.Where(x => x.ID == tmpwd.AccountID && x.Valid && !x.Suspended).First(); authresp.AuthResponse = "SUCCESS " + (activedevicescount + 1).ToString() + "/" + (pendingdevicescount - 1).ToString() + "/" + tmpacc.DeviceCountLimit.ToString(); //Сериализуем объект авторизации в XML документ var xs = new XmlSerializer(authresp.GetType()); var xml = new Utf8StringWriter(); xs.Serialize(xml, authresp); tmpwd.RegistrationResponse = xml.ToString(); tmpwd.PendingRegistration = false; tmpwd.PendingRegConfirmationIP = Request.UserHostAddress; tmpwd.PendingRegConfirmed = true; tmpwd.PendingRegConfirmationDateTime = cdt; tmpwd.PendingRegConfirmationDateTimeStr = cdtstr; tmpwd.RegistrationDateTime = cdt; tmpwd.RegistrationDateTimeStr = cdtstr; dc.SaveChanges(); dbContextTransaction.Commit(); Logger.AccountLog(Request.UserHostAddress, "Подтверждение регистрации устройства №" + tmpwd.ID + " получено", tmpwd.HardwareID, tmpacc.ID); Logger.SystemLog(Request.UserHostAddress, "Пользователь подтвердил регистрацию устройства №" + tmpwd.ID, tmpacc.UserID, "Server"); confirmresult.ForeColor = System.Drawing.Color.Lime; confirmresult.Text = "Подтверждение получено"; MailMessage mail = new MailMessage(); mail.To.Add(tmpacc.UserID); mail.From = new MailAddress(WWWVars.MailFromAddress, WWWVars.EMailDisplayName, Encoding.UTF8); mail.Subject = "Регистрация устройства завершена"; mail.SubjectEncoding = Encoding.UTF8; mail.Body = "Добрый день, уважаемый\\ая сэр\\мадам.<br>" + "<p>В системе успешно зарегистрировано новое устройство: <br>" + "Номер: " + tmpwd.ID.ToString() + "<br>" + "Идентификатор: " + tmpwd.PendingRegistrationGUID + "<br>" + "Для завершения регистрации устройство должно быть включено и подключено в Интернету.<br><p>" + "=======================================<br>" + "письмо сгенерировано автоматически, отвечать на него не нужно. Контакты для обратной связи см. на сайте: <br>" + output; mail.BodyEncoding = Encoding.UTF8; mail.IsBodyHtml = true; mail.Priority = MailPriority.High; SmtpClient client = new SmtpClient { UseDefaultCredentials = !WWWVars.MailUseSMTPAuth, Port = WWWVars.SMTPPort, Host = WWWVars.SMTPHost, EnableSsl = WWWVars.SMTPUseSSL, }; if (!client.UseDefaultCredentials) { client.Credentials = new System.Net.NetworkCredential(WWWVars.MailLogin, WWWVars.MailPassword); } client.Send(mail); Logger.AccountLog("Server", "Отправлено письмо с подтверждением регистрации устройства", tmpacc.UserID, tmpacc.ID); Logger.SystemLog("Server", "Отправлено письмо с подтверждением регистрации устройства", tmpacc.UserID, "Server"); } } catch (Exception ex) { confirmresult.ForeColor = System.Drawing.Color.Red; confirmresult.Text = "Ошибка: " + ex.HResult.ToString(); Logger.SystemLog(Request.UserHostAddress, "Ошибка при отправке письма с подтверждением регистрации устройства", ex.Message, "Server"); } } } }
public string SerializeCommonData(){ using( StringWriter textWriter = new Utf8StringWriter() ) { var serializer = new XmlSerializer(typeof( CommonData )); serializer.Serialize(textWriter, data); return textWriter.ToString(); } }
public async Task <HttpResponseMessage> LOCK(HttpRequestMessage httpRequestMessage) { string owner = string.Empty, lockscope = string.Empty, locktype = string.Empty, locktoken = string.Empty; Item item = getItem(httpRequestMessage); string timeout = "Second-3600"; HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); KeyValuePair <string, IEnumerable <string> > timeoutHeader = httpRequestMessage.Headers .Where(h => h.Key == "Timeout").FirstOrDefault(); if (!string.IsNullOrEmpty(timeoutHeader.Value.FirstOrDefault())) { timeout = timeoutHeader.Value.FirstOrDefault(); } Stream stream = httpRequestMessage.Content.ReadAsStreamAsync().Result; if (stream.Length > 0) //New Lock { httpResponseMessage.StatusCode = HttpStatusCode.Created; XDocument xRequestDocument = XDocument.Load(stream); owner = xRequestDocument.Descendants(d + "owner").First().Descendants(d + "href").First().Value; lockscope = xRequestDocument.Descendants(d + "lockscope").First().Descendants().First().Name.LocalName; locktype = xRequestDocument.Descendants(d + "locktype").First().Descendants().First().Name.LocalName; locktoken = "opaquelocktoken:" + Guid.NewGuid().ToString(); } else // Renew existing lock { httpResponseMessage.StatusCode = HttpStatusCode.OK; KeyValuePair <string, IEnumerable <string> > ifHeader = httpRequestMessage.Headers .Where(h => h.Key == "If").FirstOrDefault(); if (!string.IsNullOrEmpty(ifHeader.Value.FirstOrDefault())) { locktoken = ifHeader.Value.First().Substring(2, ifHeader.Value.First().Length - 4); } string filter = "RowKey eq '" + locktoken + "'"; TableQuery <Lock> query = new TableQuery <Lock>().Where(filter); IEnumerable <Lock> locks = lockTable.ExecuteQuery(query); Lock lockItem = locks.First(); lockscope = lockItem.Scope; locktype = lockItem.Type; owner = lockItem.Owner; } Lock itemLock = new Lock() { PartitionKey = item.BlobName, RowKey = locktoken, Expires = DateTime.Now.AddSeconds(int.Parse(timeout.Substring(timeout.IndexOf("-") + 1))), Scope = lockscope, Type = locktype, Owner = owner }; TableOperation insertOperation = TableOperation.InsertOrReplace(itemLock); lockTable.Execute(insertOperation); XDocument xDocument = new XDocument( new XElement(d + "prop", new XElement(d + "lockdiscovery", new XElement(d + "activelock", new XElement(d + "locktype", new XElement(d + locktype) ), new XElement(d + "lockscope", new XElement(d + lockscope) ), new XElement(d + "depth", "infinity" //0 ), new XElement(d + "locktoken", new XElement(d + "href", locktoken) ), new XElement(d + "timeout", timeout), new XElement(d + "owner", owner), new XElement(d + "lockroot", new XElement(d + "href", Host(httpRequestMessage) + httpRequestMessage.RequestUri.LocalPath) ) ) ), new XAttribute(XNamespace.Xmlns + "d", "DAV:") ) ); xDocument.Declaration = new XDeclaration("1.0", "utf-8", "true"); Utf8StringWriter utf8writer = new Utf8StringWriter(); xDocument.Save(utf8writer); StringBuilder sb = utf8writer.GetStringBuilder(); httpResponseMessage.Content = new StringContent(sb.ToString(), Encoding.UTF8, "application/xml"); httpResponseMessage.Content.Headers.Add("Lock-Token", "<" + locktoken + ">"); return(httpResponseMessage); }
public void ExportResources(FileBasedLanguageResourcesTemplate template, string filePathTo, Settings settings) { using (var package = GetExcelPackage(filePathTo)) { foreach (var languageResourceBundle in template.LanguageResourceBundles) { var worksheet = package.Workbook.Worksheets.Add(languageResourceBundle.Language.Name); worksheet.Column(1).Width = 20; worksheet.Column(2).Width = 20; worksheet.Column(3).Width = 20; worksheet.Column(4).Width = 100; //every column that has its Style.Locked set to true will be read-only if IsProtected is also set to true; //we need to make just the segmentation rules column read-only worksheet.Column(1).Style.Locked = false; worksheet.Column(2).Style.Locked = false; worksheet.Column(3).Style.Locked = false; worksheet.Column(4).Style.Locked = true; worksheet.Protection.IsProtected = true; var lineNumber = 1; SetCellStyle(worksheet, "A", lineNumber, "Abbreviations"); if (settings.AbbreviationsChecked && languageResourceBundle.Abbreviations != null) { foreach (var abbreviation in languageResourceBundle.Abbreviations.Items) { worksheet.Cells["A" + ++lineNumber].Value = abbreviation; } } lineNumber = 1; SetCellStyle(worksheet, "B", lineNumber, "OrdinalFollowers"); if (settings.OrdinalFollowersChecked && languageResourceBundle.OrdinalFollowers != null) { foreach (var ordinalFollower in languageResourceBundle.OrdinalFollowers.Items) { worksheet.Cells["B" + ++lineNumber].Value = ordinalFollower; } } lineNumber = 1; SetCellStyle(worksheet, "C", lineNumber, "Variables"); if (settings.VariablesChecked && languageResourceBundle.Variables != null) { foreach (var variable in languageResourceBundle.Variables.Items) { worksheet.Cells["C" + ++lineNumber].Value = variable; } } lineNumber = 1; SetCellStyle(worksheet, "D", lineNumber, "SegmentationRules"); if (settings.SegmentationRulesChecked && languageResourceBundle.SegmentationRules != null) { foreach (var segmentationRule in languageResourceBundle.SegmentationRules.Rules) { var stringWriter = new Utf8StringWriter(); var xmlSerializer = new XmlSerializer(typeof(SegmentationRule)); xmlSerializer.Serialize(stringWriter, segmentationRule); worksheet.Cells["D" + ++lineNumber].Value = stringWriter.ToString(); } } } package.Save(); } }
public bool Save(string pathToSaveFile, bool overwrite = false) { if (!IsValidPath(pathToSaveFile)) { Debug.LogError("EgoXproject: Invalid Save Path: " + pathToSaveFile); return(false); } if (!overwrite) { if (_path != pathToSaveFile && File.Exists(pathToSaveFile)) { Debug.LogError("EgoXproject: File exists: " + pathToSaveFile); return(false); } } XDocument doc = new XDocument(_decl); bool dtd = false; if (_loaded) { if (_usedDocType != null) { doc.AddFirst(_usedDocType); dtd = true; } } else { doc.AddFirst(_docType); dtd = true; } XElement plist = new XElement("plist"); plist.SetAttributeValue("version", _version); plist.Add(_dict.Xml()); doc.Add(plist); var stringWriter = new Utf8StringWriter(); doc.Save(stringWriter); var content = stringWriter.GetStringBuilder().ToString(); //http://stackoverflow.com/questions/10303315/convert-stringwriter-to-string string[] separator = { System.Environment.NewLine }; string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries); //Remove the spurious [] that get added to DOCTYPE. Grrr. if (dtd) { for (int ii = 0; ii < lines.Length; ii++) { var line = lines[ii]; if (line.Contains("<!DOCTYPE") && line.Contains("[]")) { lines[ii] = line.Replace("[]", ""); break; } } } File.WriteAllLines(pathToSaveFile, lines); //TODO this is a crap check. bool bSaved = File.Exists(pathToSaveFile); if (bSaved) { _path = pathToSaveFile; } return(bSaved); }
public string GenerateTRXReport ( TestSummary testSummary ) { var runId = _guidService.NewGuid().ToString(); var testSettingsGuid = _guidService.NewGuid().ToString(); var testLists = new TestList[] { new TestList { Id = _guidService.NewGuid().ToString(), Name = TEST_LIST_NAME_RESULTS_NOT_IN_A_LIST }, new TestList { Id = _guidService.NewGuid().ToString(), Name = TEST_LIST_NAME_ALL_LOADED_TESTS } }; var testRun = new TestRun { Id = runId, Name = $"{ TEST_RUN_NAME} {testSummary.StartDateTime.ToString(@"yyyy-MM-dd HH:mm:ss")}", RunUser = TEST_RUN_USER, Times = new Times { Creation = testSummary.StartDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"), Finsh = testSummary.EndDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"), Queuing = testSummary.StartDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"), Start = testSummary.StartDateTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00") }, TestSettings = new TestSettings { Deployment = new Deployment { RunDeploymentRoot = RUN_DEPLOYMENT_ROOT }, Name = DEPLOYMENT_NAME, Id = testSettingsGuid.ToString() }, Results = testSummary.TestResults.Select(testResult => new UnitTestResult { ComputerName = COMPUTER_NAME, Duration = testResult.Duration.ToString(), StartTime = testResult.StartTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"), EndTime = testResult.EndTime.ToString(@"yyyy-MM-ddTHH:mm:ss.FFFFFFF+00:00"), ExecutionId = testResult.ExecutionId.ToString(), Outcome = testResult.Pass ? "passed" : "failed", RelativeResultsDirectory = RELATIVE_RESULTS_DIRECTORY, TestId = testResult.TestId.ToString(), TestListId = testLists[0].Id, TestName = testResult.TestName, TestType = testResult.TestType.ToString(), }).ToArray(), TestDefinitions = testSummary.TestResults.Select(testResult => new UnitTest { Execution = new Execution { Id = testResult.ExecutionId.ToString() }, Id = testResult.TestId.ToString(), Name = testResult.TestName, Storage = UNIT_TEST_PATH, TestMethod = new TestMethod { AdapterTypeName = ADAPTER_TYPE_NAME, ClassName = testResult.ClassName, CodeBase = CODE_BASE, Name = testResult.TestName } }).ToArray(), TestEntries = testSummary.TestResults.Select(testResult => new TestEntry { ExecutionId = testResult.ExecutionId.ToString(), TestId = testResult.TestId.ToString(), TestListId = testLists[0].Id }).ToArray(), TestLists = testLists, ResultSummary = new ResultSummary { Outcome = RESULT_OUTCOME, Counters = new Counters { Total = testSummary.TestResults.Count(), Executed = testSummary.TestResults.Count(), Passed = testSummary.TestResults.Count(testresult => testresult.Pass), Failed = testSummary.TestResults.Count(testresult => !testresult.Pass) } } }; XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer xmlSerializer = new XmlSerializer(testRun.GetType()); using Utf8StringWriter textWriter = new Utf8StringWriter(); xmlSerializer.Serialize(textWriter, testRun, ns); return(textWriter.ToString()); }
protected void Page_Load(object sender, EventArgs e) { using (VendingModelContainer dc = new VendingModelContainer()) { using (var dbContextTransaction = dc.Database.BeginTransaction()) { Uri url = new Uri(Request.Url.Authority); string output = url.GetLeftPart(UriPartial.Authority); WaterDeviceRegistrationResponse authresp = new WaterDeviceRegistrationResponse { RegID = -1, ServerEndPoint = output }; try { DateTime dt = DateTime.Now; long cdt = Convert.ToInt64(dt.ToString("yyyyMMddHHmmss")); string cdtstr = dt.ToString("dd.MM.yyyy HH:mm:ss"); var waterdevices = dc.WaterDevices; //считываем запрос string rawrequest = Request.Form["RegistrationRequest"]; byte[] bytes = Convert.FromBase64String(rawrequest); string requestxml = Encoding.UTF8.GetString(bytes); //создаем объект запроса регистрации WaterDeviceRegistrationRequest tmpreq = Deserialize <WaterDeviceRegistrationRequest>(requestxml); RSACryptoServiceProvider rsaProvider = null; CryptoHelper ch = new CryptoHelper(); //расшифровываем запрос byte[] plaintextbytes = ch.DecryptData(tmpreq.AuthorizationString); byte[] tmphwidbytes = new byte[] { }; byte[] tmpuidbytes = new byte[] { }; //делим массив данных на две части, разделитель byte[3] { 254, 11, 254 } for (int i = 0; i < plaintextbytes.Length; i++) { if (plaintextbytes[i] == 254 && plaintextbytes[i + 1] == 11 && plaintextbytes[i + 2] == 254) { Array.Resize(ref tmphwidbytes, i); Array.Copy(plaintextbytes, 0, tmphwidbytes, 0, tmphwidbytes.Length); Array.Resize(ref tmpuidbytes, plaintextbytes.Length - i - 3); Array.Copy(plaintextbytes, i + 3, tmpuidbytes, 0, tmpuidbytes.Length); break; } } //поля запроса: учетная запись и аппаратный идентификатор устройства string userid = Encoding.UTF8.GetString(tmpuidbytes); string hwid = Encoding.UTF8.GetString(tmphwidbytes); //инициализируем криптодвижок для проверки подписи присланных данных rsaProvider = new RSACryptoServiceProvider(); rsaProvider.ImportCspBlob(tmpreq.PublicKey); SHA512 sha512 = new SHA512Managed(); //вычисляем хеш присланных данных byte[] hash = sha512.ComputeHash(plaintextbytes); int activedevicescount; int pendingdevicescount; Accounts tmpacc; //проверяем подпись bool signcorrect = rsaProvider.VerifyData(plaintextbytes, CryptoConfig.MapNameToOID("SHA512"), tmpreq.AuthSignature); if (signcorrect) { //подпись корректна, ищем акаунт tmpacc = dc.Accounts.First(x => x.UserID == userid && x.Valid && !x.Suspended); activedevicescount = waterdevices.Where(x => x.AccountID == tmpacc.ID && x.Valid && !x.Suspended && !x.PendingRegistration).Count(); pendingdevicescount = waterdevices.Where(x => x.AccountID == tmpacc.ID && x.Valid && !x.Suspended && x.PendingRegistration).Count(); WaterDevices tmpdev = null; //пробуем найти акаунт с таким же аппаратным идентификатором, чтобы исключить дубликаты try { tmpdev = waterdevices.Where(x => x.HardwareID == hwid /* && x.AccountID == tmpacc.ID && x.Valid && !x.Suspended*/).First(); //если устройство нашлось и зарегистрировано, отсылаем содержимое лицензии if (!tmpdev.PendingRegistration) { authresp = Deserialize <WaterDeviceRegistrationResponse>(tmpdev.RegistrationResponse); } else //если устройство нашлось и ожидает регистрации { authresp.Signature = ""; authresp.AuthResponse = "OK_PENDING"; } } catch { } //если в базе нет устройства if (tmpdev == null) { //есть неиспользованные лицензии, формируем запись нового устройства if (activedevicescount < tmpacc.DeviceCountLimit) { WaterDevices newwaterdevice = new WaterDevices() { CustomerServiceContactPhone = tmpacc.DefaultContactPhone, HardwareID = hwid, AccountID = tmpacc.ID, LocationAddress = "", LocationLatitude = 0, LocationLongtitude = 0, ProductName = "Вода питьевая", PendingRegistration = true, PRICE_PER_ITEM_MDE = 500, PublicKey = tmpreq.PublicKey, RegistrationRequest = requestxml, Suspended = false, Valid = true, RegistrationDateTime = 0, RegistrationRequestDateTime = cdt, RegistrationDateTimeStr = "", RegistrationRequestDateTimeStr = cdtstr, RegistrationResponse = "", PendingRegistrationGUID = Guid.NewGuid().ToString(), PendingRegConfirmed = false, PendingRegConfirmationIP = "", PendingRegConfirmationDateTime = 0, PendingRegConfirmationDateTimeStr = "" }; //добавляем запись в БД waterdevices.Add(newwaterdevice); dc.SaveChanges(); Logger.AccountLog(Request.UserHostAddress, "Принята заявка на регистрацию нового устройства", newwaterdevice.HardwareID, tmpacc.ID); Logger.SystemLog(Request.UserHostAddress, "Регистрация нового устройства", tmpacc.UserID, "Server"); MailMessage mail = new MailMessage(); mail.To.Add(tmpacc.UserID); mail.From = new MailAddress(WWWVars.MailFromAddress, WWWVars.EMailDisplayName, Encoding.UTF8); mail.Subject = WWWVars.RegDeviceMailSubject; mail.SubjectEncoding = Encoding.UTF8; string confirmurl = output + "/User/ConfirmRegistration.aspx?wvdid=" + newwaterdevice.ID.ToString() + "&prg=" + newwaterdevice.PendingRegistrationGUID; mail.Body = "Добрый день, уважаемый\\ая сэр\\мадам.<br>" + "<p>В систему добавлена заявка на регистрацию нового устройства. Для подтверждения пройдите по ссылке ниже:<br>" + "<a href=\"" + confirmurl + "\">" + confirmurl + "</a><br>" + "<b><font color=\"red\">Внимание: Ссылка будет активной в течение 3 часов!<br> Если вы не завершите регистрацию до " + DateTime.Now.AddHours(3).ToString("dd.MM.yyyy HH:mm:ss") + ", процедуру регистрации необходимо будет повторить на устройстве с использованием файла лицензии.</font></b><br></p>" + "=======================================<br>" + "письмо сгенерировано автоматически, отвечать на него не нужно. Контакты для обратной связи см. на сайте: <br>" + output; mail.BodyEncoding = Encoding.UTF8; mail.IsBodyHtml = true; mail.Priority = MailPriority.High; SmtpClient client = new SmtpClient { UseDefaultCredentials = !WWWVars.MailUseSMTPAuth, Port = WWWVars.SMTPPort, Host = WWWVars.SMTPHost, EnableSsl = WWWVars.SMTPUseSSL, }; if (!client.UseDefaultCredentials) { client.Credentials = new System.Net.NetworkCredential(WWWVars.MailLogin, WWWVars.MailPassword); } client.Send(mail); authresp.AuthResponse = "OK_PENDING"; Logger.AccountLog("Server", "Отправлено электронное письмо о регистрации нового устройства", tmpacc.UserID, tmpacc.ID); Logger.SystemLog("Server", "Отправлено письмо о регистрации нового устройства", tmpacc.UserID, "Server"); } //превышен лимит лицензий, отказ регистрации else { authresp.Signature = ""; authresp.AuthResponse = "DENY_OVERQUOTA"; } } else //устройство уже есть в БД, ничего не делаем { } } else //подпись некорректна, отказ регистрации { authresp.Signature = ""; authresp.AuthResponse = "DENY_SIGNATURE_MISMATCH"; } //сохраняем изменения в БД dbContextTransaction.Commit(); } catch (Exception ex) { //что-то пошло не так, ошибка на любом этапе, прерываем регистрацию, откатываем изменения в БД if (ex.HResult != -2146233040) { dbContextTransaction.Rollback(); authresp.Signature = ""; authresp.AuthResponse = "ABORT CODE: " + ex.HResult.ToString(); Logger.SystemLog(Request.UserHostAddress, "Ошибка при регистрации устройства: " + ex.Message, "", "Server"); } } finally { //Сериализуем объект авторизации в XML документ var xs = new XmlSerializer(authresp.GetType()); var xml = new Utf8StringWriter(); xs.Serialize(xml, authresp); //переводим в массив байт, кодируем в Base64 для передачи по http byte[] xmlbytes = Encoding.UTF8.GetBytes(xml.ToString()); string xmlbytesbase64 = Convert.ToBase64String(xmlbytes); //отсылаем ответ устройству Response.Clear(); Response.Write(xmlbytesbase64); } } } }
public string Format(CoverageResult result) { XmlDocument xml = new XmlDocument(); XmlElement coverage = xml.CreateElement("CoverageSession"); XmlElement coverageSummary = xml.CreateElement("Summary"); XmlElement modules = xml.CreateElement("Modules"); int numSequencePoints = 0, numBranchPoints = 0, numClasses = 0, numMethods = 0; int visitedSequencePoints = 0, visitedBranchPoints = 0, visitedClasses = 0, visitedMethods = 0; int i = 1; foreach (var mod in result.Modules) { XmlElement module = xml.CreateElement("Module"); module.SetAttribute("hash", Guid.NewGuid().ToString().ToUpper()); XmlElement path = xml.CreateElement("ModulePath"); path.AppendChild(xml.CreateTextNode(mod.Key)); XmlElement time = xml.CreateElement("ModuleTime"); time.AppendChild(xml.CreateTextNode(DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ss"))); XmlElement name = xml.CreateElement("ModuleName"); name.AppendChild(xml.CreateTextNode(Path.GetFileNameWithoutExtension(mod.Key))); module.AppendChild(path); module.AppendChild(time); module.AppendChild(name); XmlElement files = xml.CreateElement("Files"); XmlElement classes = xml.CreateElement("Classes"); foreach (var doc in mod.Value) { XmlElement file = xml.CreateElement("File"); file.SetAttribute("uid", i.ToString()); file.SetAttribute("fullPath", doc.Key); files.AppendChild(file); foreach (var cls in doc.Value) { XmlElement @class = xml.CreateElement("Class"); XmlElement classSummary = xml.CreateElement("Summary"); XmlElement className = xml.CreateElement("FullName"); className.AppendChild(xml.CreateTextNode(cls.Key)); XmlElement methods = xml.CreateElement("Methods"); int j = 0; var classVisited = false; foreach (var meth in cls.Value) { XmlElement method = xml.CreateElement("Method"); method.SetAttribute("cyclomaticComplexity", "0"); method.SetAttribute("nPathComplexity", "0"); method.SetAttribute("sequenceCoverage", "0"); method.SetAttribute("branchCoverage", "0"); method.SetAttribute("isConstructor", meth.Key.Contains("ctor").ToString()); method.SetAttribute("isGetter", meth.Key.Contains("get_").ToString()); method.SetAttribute("isSetter", meth.Key.Contains("set_").ToString()); method.SetAttribute("isStatic", (!meth.Key.Contains("get_") || !meth.Key.Contains("set_")).ToString()); XmlElement methodName = xml.CreateElement("Name"); methodName.AppendChild(xml.CreateTextNode(meth.Key)); XmlElement fileRef = xml.CreateElement("FileRef"); fileRef.SetAttribute("uid", i.ToString()); XmlElement methodPoint = xml.CreateElement("MethodPoint"); methodPoint.SetAttribute("vc", meth.Value.Select(l => l.Value.Hits).Sum().ToString()); methodPoint.SetAttribute("upsid", "0"); methodPoint.SetAttribute("type", "xsi", "SequencePoint"); methodPoint.SetAttribute("ordinal", j.ToString()); methodPoint.SetAttribute("offset", j.ToString()); methodPoint.SetAttribute("sc", "0"); methodPoint.SetAttribute("sl", meth.Value.First().Key.ToString()); methodPoint.SetAttribute("ec", "1"); methodPoint.SetAttribute("el", meth.Value.Last().Key.ToString()); methodPoint.SetAttribute("bec", "0"); methodPoint.SetAttribute("bev", "0"); methodPoint.SetAttribute("fileid", i.ToString()); // They're really just lines XmlElement sequencePoints = xml.CreateElement("SequencePoints"); XmlElement branchPoints = xml.CreateElement("BranchPoints"); XmlElement methodSummary = xml.CreateElement("Summary"); int k = 0; int kBr = 0; var methodVisited = false; foreach (var lines in meth.Value) { XmlElement sequencePoint = xml.CreateElement("SequencePoint"); sequencePoint.SetAttribute("vc", lines.Value.Hits.ToString()); sequencePoint.SetAttribute("upsid", lines.Key.ToString()); sequencePoint.SetAttribute("ordinal", k.ToString()); sequencePoint.SetAttribute("sl", lines.Key.ToString()); sequencePoint.SetAttribute("sc", "1"); sequencePoint.SetAttribute("el", lines.Key.ToString()); sequencePoint.SetAttribute("ec", "2"); sequencePoint.SetAttribute("bec", "0"); sequencePoint.SetAttribute("bev", "0"); sequencePoint.SetAttribute("fileid", i.ToString()); sequencePoints.AppendChild(sequencePoint); if (lines.Value.IsBranchPoint) { XmlElement branchPoint = xml.CreateElement("BranchPoint"); branchPoint.SetAttribute("vc", lines.Value.Hits.ToString()); branchPoint.SetAttribute("upsid", lines.Key.ToString()); branchPoint.SetAttribute("ordinal", kBr.ToString()); branchPoint.SetAttribute("sl", lines.Key.ToString()); branchPoint.SetAttribute("fileid", i.ToString()); branchPoints.AppendChild(branchPoint); kBr++; numBranchPoints++; } numSequencePoints++; if (lines.Value.Hits > 0) { visitedSequencePoints++; classVisited = true; methodVisited = true; if (lines.Value.IsBranchPoint) { visitedBranchPoints++; } } k++; } numMethods++; if (methodVisited) { visitedMethods++; } methodSummary.SetAttribute("numSequencePoints", meth.Value.Count().ToString()); methodSummary.SetAttribute("visitedSequencePoints", meth.Value.Where(l => l.Value.Hits > 0).Count().ToString()); methodSummary.SetAttribute("numBranchPoints", meth.Value.Where(l => l.Value.IsBranchPoint).Count().ToString()); methodSummary.SetAttribute("visitedBranchPoints", meth.Value.Where(l => l.Value.IsBranchPoint && l.Value.Hits > 0).Count().ToString()); methodSummary.SetAttribute("sequenceCoverage", "0"); methodSummary.SetAttribute("branchCoverage", "0"); methodSummary.SetAttribute("maxCyclomaticComplexity", "0"); methodSummary.SetAttribute("minCyclomaticComplexity", "0"); methodSummary.SetAttribute("visitedClasses", "0"); methodSummary.SetAttribute("numClasses", "0"); methodSummary.SetAttribute("visitedMethods", methodVisited ? "1" : "0"); methodSummary.SetAttribute("numMethods", "1"); method.AppendChild(methodSummary); method.AppendChild(xml.CreateElement("MetadataToken")); method.AppendChild(methodName); method.AppendChild(fileRef); method.AppendChild(sequencePoints); method.AppendChild(branchPoints); method.AppendChild(methodPoint); methods.AppendChild(method); j++; } numClasses++; if (classVisited) { visitedClasses++; } classSummary.SetAttribute("numSequencePoints", cls.Value.Select(c => c.Value.Count).Sum().ToString()); classSummary.SetAttribute("visitedSequencePoints", cls.Value.Select(c => c.Value.Where(l => l.Value.Hits > 0).Count()).Sum().ToString()); classSummary.SetAttribute("numBranchPoints", cls.Value.Select(c => c.Value.Count(l => l.Value.IsBranchPoint)).Sum().ToString()); classSummary.SetAttribute("visitedBranchPoints", cls.Value.Select(c => c.Value.Where(l => l.Value.Hits > 0 && l.Value.IsBranchPoint).Count()).Sum().ToString()); classSummary.SetAttribute("sequenceCoverage", "0"); classSummary.SetAttribute("branchCoverage", "0"); classSummary.SetAttribute("maxCyclomaticComplexity", "0"); classSummary.SetAttribute("minCyclomaticComplexity", "0"); classSummary.SetAttribute("visitedClasses", classVisited ? "1" : "0"); classSummary.SetAttribute("numClasses", "1"); classSummary.SetAttribute("visitedMethods", "0"); classSummary.SetAttribute("numMethods", cls.Value.Count.ToString()); @class.AppendChild(classSummary); @class.AppendChild(className); @class.AppendChild(methods); classes.AppendChild(@class); } i++; } module.AppendChild(files); module.AppendChild(classes); modules.AppendChild(module); } coverageSummary.SetAttribute("numSequencePoints", numSequencePoints.ToString()); coverageSummary.SetAttribute("visitedSequencePoints", visitedSequencePoints.ToString()); coverageSummary.SetAttribute("numBranchPoints", numBranchPoints.ToString()); coverageSummary.SetAttribute("visitedBranchPoints", visitedBranchPoints.ToString()); coverageSummary.SetAttribute("sequenceCoverage", "0"); coverageSummary.SetAttribute("branchCoverage", "0"); coverageSummary.SetAttribute("maxCyclomaticComplexity", "0"); coverageSummary.SetAttribute("minCyclomaticComplexity", "0"); coverageSummary.SetAttribute("visitedClasses", visitedClasses.ToString()); coverageSummary.SetAttribute("numClasses", numClasses.ToString()); coverageSummary.SetAttribute("visitedMethods", visitedMethods.ToString()); coverageSummary.SetAttribute("numMethods", numMethods.ToString()); coverage.AppendChild(coverageSummary); coverage.AppendChild(modules); xml.AppendChild(coverage); Utf8StringWriter writer = new Utf8StringWriter(); xml.Save(writer); return(writer.ToString()); }
public static string ToXmlString(this XDocument xml) { using var writer = new Utf8StringWriter(); xml.Save(writer); return(writer.ToString()); }
private static string Post(string fileName, string fileContent) { var files = AssetDatabase.GetAllAssetPaths(); var project = CheckString(fileName); XDocument CON = XDocument.Parse(fileContent); foreach (var fileProjectPathName in files) { if (!fileProjectPathName.Contains("Assets")) { continue; } ///后缀名 var extension = Path.GetExtension(fileProjectPathName); if (extension == ".xsd" || extension == "xsd") { var res = CheckFile(fileProjectPathName); if (project.IsEditor != res.IsEditor) { //Todo continue; } if (project.IsPlugins != res.IsPlugins) { //Todo continue; } ///转换 / string fileProjectPathNameFIX = fileProjectPathName.Replace('/', '\\'); ///xss文件路径名 string xssName = Path.ChangeExtension(fileProjectPathNameFIX, ".xss"); ///xsc文件路径名 string xscName = Path.ChangeExtension(fileProjectPathNameFIX, ".xsc"); ///对应的数据集脚本名字 string scName = Path.ChangeExtension(fileProjectPathNameFIX, ".cs"); ///对应的数据集设计器脚本名字 string designercsName = Path.ChangeExtension(fileProjectPathNameFIX, "Designer.cs"); ///xsd文件短名 string shortFileName = Path.GetFileName(fileProjectPathNameFIX); ///获取所以元素 var elements = CON.Descendants(); ///cs文件引用元素 元素名为Compile var csDes = from a in elements where a.Name.LocalName == "Compile" && a.Attribute("Include") != null && (a.Attribute("Include").Value == scName || a.Attribute("Include").Value == designercsName) select a; foreach (var cs in csDes) { var csName = cs.Attribute("Include").Value; if (csName == designercsName) { ///如果是设计器 额外加入两个元素描述 cs.Add(new XElement(XName.Get("AutoGen", cs.Name.NamespaceName)) { Value = "True" }); cs.Add(new XElement(XName.Get("DesignTime", cs.Name.NamespaceName)) { Value = "True" }); } cs.Add(new XElement(XName.Get("DependentUpon", cs.Name.NamespaceName)) { Value = shortFileName }); } /////设计器文件引用元素 元素名为None //var desingerDes = from a in elements // where a.Name.LocalName == "None" && a.Attribute("Include") != null // && (a.Attribute("Include").Value == fileProjectPathNameFIX // || a.Attribute("Include").Value == xssName // || a.Attribute("Include").Value == xscName) // select a; //foreach (var desingerEle in desingerDes) //{ // string desinfileName = desingerEle.Attribute("Include").Value; // if (desinfileName == fileProjectPathNameFIX) // { // desingerEle.Add(new XElement(XName.Get("SubType", desingerEle.Name.NamespaceName)) { Value = "Designer" }); // desingerEle.Add(new XElement(XName.Get("Generator", desingerEle.Name.NamespaceName)) { Value = "MSDataSetGenerator" }); // desingerEle.Add(new XElement(XName.Get("LastGenOutput", desingerEle.Name.NamespaceName)) // { Value = Path.GetFileName(designercsName) }); // } // else // { // desingerEle.Add(new XElement(XName.Get("DependentUpon", desingerEle.Name.NamespaceName)) // { Value = Path.GetFileName(fileProjectPathNameFIX) }); // } //} XElement xsdGroup = new XElement(XName.Get("ItemGroup", CON.Root.Name.NamespaceName)); XElement xsd = new XElement(XName.Get("None", xsdGroup.Name.NamespaceName)); xsd.Add(new XAttribute("Include", fileProjectPathNameFIX)); xsd.Add(new XElement(XName.Get("SubType", xsd.Name.NamespaceName)) { Value = "Designer" }); xsd.Add(new XElement(XName.Get("Generator", xsd.Name.NamespaceName)) { Value = "MSDataSetGenerator" }); xsd.Add(new XElement(XName.Get("LastGenOutput", xsd.Name.NamespaceName)) { Value = Path.GetFileName(designercsName) }); xsdGroup.Add(xsd); XElement xss = new XElement(XName.Get("None", xsdGroup.Name.NamespaceName)); xss.Add(new XAttribute("Include", xssName)); xss.Add(new XElement(XName.Get("DependentUpon", xss.Name.NamespaceName)) { Value = Path.GetFileName(fileProjectPathNameFIX) }); xsdGroup.Add(xss); XElement xsc = new XElement(XName.Get("None", xsdGroup.Name.NamespaceName)); xsc.Add(new XAttribute("Include", xscName)); xsc.Add(new XElement(XName.Get("DependentUpon", xsc.Name.NamespaceName)) { Value = Path.GetFileName(fileProjectPathNameFIX) }); xsdGroup.Add(xsc); var last = CON.Descendants(XName.Get("ItemGroup", xsd.Name.NamespaceName)).LastOrDefault(); if (last != null) { last.AddAfterSelf(xsdGroup); } else { CON.Descendants(XName.Get("Project", xsd.Name.NamespaceName)).FirstOrDefault().Add(xsdGroup); } } } var writer = new Utf8StringWriter(); CON.Save(writer); return(writer.ToString()); }
public void ExportResourcesToExcel(ILanguageResourcesContainer resourceContainer, string filePathTo, Settings settings) { using var package = GetExcelPackage(filePathTo); int lineNumber; foreach (var languageResourceBundle in resourceContainer.LanguageResourceBundles) { if (languageResourceBundle == null) { continue; } var worksheet = package.Workbook.Worksheets.Add(languageResourceBundle.Language.Name); PrepareWorksheet(worksheet); lineNumber = 1; if (settings.AbbreviationsChecked && languageResourceBundle.Abbreviations != null) { foreach (var abbreviation in languageResourceBundle.Abbreviations.Items) { worksheet.Cells["A" + ++lineNumber].Value = abbreviation; } } lineNumber = 1; if (settings.OrdinalFollowersChecked && languageResourceBundle.OrdinalFollowers != null) { foreach (var ordinalFollower in languageResourceBundle.OrdinalFollowers.Items) { worksheet.Cells["B" + ++lineNumber].Value = ordinalFollower; } } lineNumber = 1; if (settings.VariablesChecked && languageResourceBundle.Variables != null) { foreach (var variable in languageResourceBundle.Variables.Items) { worksheet.Cells["C" + ++lineNumber].Value = variable; } } lineNumber = 1; if (settings.SegmentationRulesChecked && languageResourceBundle.SegmentationRules != null) { foreach (var segmentationRule in languageResourceBundle.SegmentationRules.Rules) { var stringWriter = new Utf8StringWriter(); var xmlSerializer = new XmlSerializer(typeof(SegmentationRule)); xmlSerializer.Serialize(stringWriter, segmentationRule); worksheet.Cells["D" + ++lineNumber].Value = stringWriter.ToString(); } } lineNumber = 1; if (settings.DatesChecked && languageResourceBundle.LongDateFormats != null) { var longDates = new List <string>(); if (languageResourceBundle.LongDateFormats != null) { longDates.AddRange(languageResourceBundle.LongDateFormats); } foreach (var date in longDates) { worksheet.Cells["E" + ++lineNumber].Value = date; } } lineNumber = 1; if (settings.DatesChecked && languageResourceBundle.ShortDateFormats != null) { var shortDates = new List <string>(); if (languageResourceBundle.ShortDateFormats != null) { shortDates.AddRange(languageResourceBundle.ShortDateFormats); } foreach (var date in shortDates) { worksheet.Cells["F" + ++lineNumber].Value = date; } } lineNumber = 1; if (settings.TimesChecked && languageResourceBundle.LongTimeFormats != null) { var longTimes = new List <string>(); if (languageResourceBundle.LongTimeFormats != null) { longTimes.AddRange(languageResourceBundle.LongTimeFormats); } foreach (var time in longTimes) { worksheet.Cells["G" + ++lineNumber].Value = time; } } lineNumber = 1; if (settings.TimesChecked && languageResourceBundle.ShortTimeFormats != null) { var shortTimes = new List <string>(); if (languageResourceBundle.ShortTimeFormats != null) { shortTimes.AddRange(languageResourceBundle.ShortTimeFormats); } foreach (var time in shortTimes) { worksheet.Cells["H" + ++lineNumber].Value = time; } } lineNumber = 1; if (settings.NumbersChecked && languageResourceBundle.NumbersSeparators != null) { foreach (var separator in languageResourceBundle.NumbersSeparators) { worksheet.Cells["I" + ++lineNumber].Value = $"{{{separator.GroupSeparators} {separator.DecimalSeparators}}}"; } } lineNumber = 1; if (settings.MeasurementsChecked && languageResourceBundle.MeasurementUnits != null) { foreach (var unit in languageResourceBundle.MeasurementUnits) { worksheet.Cells["J" + ++lineNumber].Value = unit.Key; } } lineNumber = 1; if (settings.CurrenciesChecked && languageResourceBundle.CurrencyFormats != null) { foreach (var currency in languageResourceBundle.CurrencyFormats) { worksheet.Cells["K" + ++lineNumber].Value = $"{currency.Symbol} - {currency.CurrencySymbolPositions[0]}"; } } } var globalSettingsWorksheet = package.Workbook.Worksheets.Add(PluginResources.GlobalSettings); PrepareGlobalSettingsWorksheet(globalSettingsWorksheet); if (settings.RecognizersChecked && resourceContainer.Recognizers != null) { var recognizers = resourceContainer.Recognizers.ToString().Split(','); lineNumber = 1; foreach (var recognizer in recognizers) { globalSettingsWorksheet.Cells[$"A{++lineNumber}"].Value = recognizer; } } if (settings.WordCountFlagsChecked && resourceContainer.WordCountFlags != null) { var wordCountFlags = resourceContainer.WordCountFlags.ToString().Split(','); lineNumber = 1; foreach (var wordCountFlag in wordCountFlags) { globalSettingsWorksheet.Cells[$"B{++lineNumber}"].Value = wordCountFlag; } } package.Save(); }
/// <summary> /// Orders and beautifies an XML document. /// </summary> /// <param name="source">The source XML document to order and beautify.</param> /// <param name="extension">The extension. Used to determine tab spacing.</param> /// <returns>The text of the scrubbed and beautified document.</returns> private static string ScrubDocument(string source, string extension) { // Used to write the final document in the form of a long string. using (Utf8StringWriter stringWriter = new Utf8StringWriter()) { try { // Read the source document. using (StringReader stringReader = new StringReader(source)) { XmlSchemaDocument xmlSchemaDocument = new XmlSchemaDocument(stringReader.ReadToEnd()); // Regurgitate the schema as an XDocument XElement schemaElement = new XElement( ScrubXsdCommand.xs + "schema", new XAttribute("id", xmlSchemaDocument.Name), new XAttribute("targetNamespace", xmlSchemaDocument.TargetNamespace)); XDocument targetDocument = new XDocument(schemaElement); // This will populate the namespace manager from the namespaces in the root element. foreach (XAttribute xAttribute in xmlSchemaDocument.Root.Attributes()) { if (xAttribute.IsNamespaceDeclaration) { // Place the remaining namespace attributes in the root element of the schema description. schemaElement.Add(new XAttribute(xAttribute.Name, xAttribute.Value)); } } // <xs:element name="Domain"> XElement dataModelElement = new XElement(ScrubXsdCommand.xs + "element", new XAttribute("name", xmlSchemaDocument.Name)); // This specifies the data domain used by the REST generated code. if (xmlSchemaDocument.Domain != null) { dataModelElement.SetAttributeValue(XmlSchemaDocument.DomainName, xmlSchemaDocument.Domain); } // This flag indicates that the API uses tokens for authentication. if (xmlSchemaDocument.IsSecure.HasValue) { dataModelElement.SetAttributeValue(XmlSchemaDocument.IsSecureName, xmlSchemaDocument.IsSecure.Value); } // This flag indicates that the interface is not committed to a peristent store. if (xmlSchemaDocument.IsVolatile.HasValue) { dataModelElement.SetAttributeValue(XmlSchemaDocument.IsVolatileName, xmlSchemaDocument.IsVolatile.Value); } // <xs:complexType> XElement dataModelComlexTypeElement = new XElement(ScrubXsdCommand.xs + "complexType"); // <xs:choice maxOccurs="unbounded"> XElement dataModelChoices = new XElement(ScrubXsdCommand.xs + "choice", new XAttribute("maxOccurs", "unbounded")); // This will scrub and add each of the tables to the schema in alphabetical order. foreach (TableElement tableElement in xmlSchemaDocument.Tables.OrderBy(t => t.Name)) { dataModelChoices.Add(ScrubXsdCommand.CreateTable(tableElement)); } // The complex types that define the tables. dataModelComlexTypeElement.Add(dataModelChoices); dataModelElement.Add(dataModelComlexTypeElement); // This will order the primary keys. List <UniqueKeyElement> primaryKeyList = new List <UniqueKeyElement>(); foreach (TableElement tableElement in xmlSchemaDocument.Tables) { primaryKeyList.AddRange(tableElement.UniqueKeys); } foreach (UniqueKeyElement uniqueConstraintSchema in primaryKeyList.OrderBy(pke => pke.Name)) { dataModelElement.Add(CreateUniqueKey(uniqueConstraintSchema)); } // This will order the foreign primary keys. List <ForeignKeyElement> foreignKeyList = new List <ForeignKeyElement>(); foreach (TableElement tableElement in xmlSchemaDocument.Tables) { foreignKeyList.AddRange(tableElement.ForeignKeys); } foreach (ForeignKeyElement foreignConstraintSchema in foreignKeyList.OrderBy(fke => fke.Name)) { dataModelElement.Add(CreateForeignKey(foreignConstraintSchema)); } // Add the data model element to the document. schemaElement.Add(dataModelElement); // Save the regurgitated output. targetDocument.Save(stringWriter); } } catch (Exception exception) { // Show a message box to prove we were here VsShellUtilities.ShowMessageBox( ScrubXsdCommand.serviceProvider, exception.Message, Resources.EditorExtensionsTitle, OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } // The result of beautifying a long string of XML is another long string that is scrubbed and beautified. This string will be used // to replace the original content of the module. return(stringWriter.ToString()); } }
/// <summary>Formats the input BPL object into the output XML document.</summary> public override bool Format(BplObject input) { if (!PrepareFormatter(input)) return false; try { OutputXml = new XDocument { Declaration = new XDeclaration("1.0", "UTF-8", "yes") }; _serializeObject(OutputXml, Input, null); NSMapping.Write(OutputXml.Root); } catch (Exception e) { AddException(e); } if (Success) { try { using (var strWriter = new Utf8StringWriter(CultureInfo.InvariantCulture)) { using (var xmlWriter = XmlWriter.Create(strWriter, _getWriterSettings())) { OutputXml.Save(xmlWriter); } Output = strWriter.ToString(); } } catch (Exception e) { AddException(e); } } if (!Success) { Output = null; OutputXml = null; } return Success; }
public void UsingAnXmlStringTakenFromApiDocumenation_CreateASecurePayMessageObject_ConvertBothToString_AndDiff_ExpectIdentical() { //Very important test to ensure that the SecurePayMessage XML deserialization doesn't miss any elements // Arrange var xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?> <SecurePayMessage> <MessageInfo> <messageID>889a1e7f66f04169bd17013c08fb89</messageID> <messageTimestamp>20121009170032054000+600</messageTimestamp> <apiVersion>spxml-3.0</apiVersion> </MessageInfo> <RequestType>Periodic</RequestType> <MerchantInfo> <merchantID>ABC0001</merchantID> </MerchantInfo> <Status> <statusCode>0</statusCode> <statusDescription>Normal</statusDescription> </Status> <Periodic> <PeriodicList count=""2""> <PeriodicItem ID=""1""> <actionType>trigger</actionType> <clientID>first</clientID> <responseCode>00</responseCode> <responseText>Approved</responseText> <successful>yes</successful> <txnType>3</txnType> <amount>138400</amount> <currency>AUD</currency> <txnID>412667</txnID> <receipt>702295</receipt> <ponum>702295ca60182b75d649e8bf1f</ponum> <settlementDate>20120910</settlementDate> <CreditCardInfo> <pan>444433...111</pan> <expiryDate>10/15</expiryDate> <recurringFlag>no</recurringFlag> <cardType>6</cardType> <cardDescription>Visa</cardDescription> </CreditCardInfo> </PeriodicItem> <PeriodicItem ID=""2""> <actionType>trigger</actionType> <clientID>second</clientID> <responseCode>00</responseCode> <responseText>Approved</responseText> <successful>yes</successful> <txnType>3</txnType> <amount>138400</amount> <currency>AUD</currency> <txnID>412667</txnID> <receipt>702295</receipt> <ponum>702295ca60182b75d649e8bf1f</ponum> <settlementDate>20120910</settlementDate> <CreditCardInfo> <pan>444433...111</pan> <expiryDate>10/15</expiryDate> <recurringFlag>no</recurringFlag> <cardType>6</cardType> <cardDescription>Visa</cardDescription> </CreditCardInfo> </PeriodicItem> </PeriodicList> </Periodic> </SecurePayMessage>"; // Act var secPayMessageCreatedFromXml = xml.As<SecurePayMessage>(); // Assert Assert.IsNotNull(secPayMessageCreatedFromXml); Assert.IsNotNullOrEmpty(secPayMessageCreatedFromXml.MessageInfo.MessageId); Assert.That(secPayMessageCreatedFromXml.Periodic.PeriodicList.Count, Is.EqualTo(2)); Assert.IsNotEmpty(secPayMessageCreatedFromXml.Periodic.PeriodicList.PeriodicItem); Assert.IsTrue(secPayMessageCreatedFromXml.Periodic.PeriodicList.PeriodicItem.Count == 2); Assert.IsTrue(secPayMessageCreatedFromXml.Periodic.PeriodicList.PeriodicItem[0].Id == 1); Assert.IsTrue(secPayMessageCreatedFromXml.Periodic.PeriodicList.PeriodicItem[1].Id == 2); var builder = new StringBuilder(); using (var writer = new Utf8StringWriter(builder)) { var x = new XmlSerializer(secPayMessageCreatedFromXml.GetType()); x.Serialize(writer, secPayMessageCreatedFromXml); } var stringsToRemove = new List<string>() { @"xmlns:xsd=""http://www.w3.org/2001/XMLSchema""", @"xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""", @"standalone=""no""" }; var result = builder.ToString().ExceptBlanks().Replace(">00<", ">0<").Replace(">000<", ">0<").ToLower(); var source = xml.ExceptBlanks().Replace(">00<", ">0<").Replace(">000<", ">0<").ToLower(); stringsToRemove.ForEach(s => { result = result.Replace(s.ToLower(), ""); source = source.Replace(s.ToLower(), ""); }); /*Console.WriteLine("Src:"); Console.WriteLine(source); Console.WriteLine("Response:"); Console.WriteLine(result);*/ Assert.AreEqual(result, source); }
public virtual string getColumnImpactResult(bool analyzeDlineage) { if (string.ReferenceEquals(sqlContent, null)) { Document doc = null; Element columnImpactResult = null; doc = new Document(); XDeclaration declaration = new XDeclaration("1.0", "utf-8", "no"); doc.Declaration = declaration; columnImpactResult = new XElement("columnImpactResult"); doc.Add(columnImpactResult); if (sqlDir != null && sqlDir.Attributes.HasFlag(FileAttributes.Directory)) { Element dirNode = new Element("dir"); dirNode.Add(new XAttribute("name", sqlDir.FullName)); columnImpactResult.Add(dirNode); } FileInfo[] children = sqlFiles == null?listFiles(sqlDir) : sqlFiles; for (int i = 0; i < children.Length; i++) { FileInfo child = children[i]; if (child.Attributes.HasFlag(FileAttributes.Directory)) { continue; } if (child != null) { Element fileNode = new Element("file"); fileNode.Add(new XAttribute("name", child.FullName)); ColumnImpact impact = new ColumnImpact(fileNode, vendor, tableColumns, strict); impact.Debug = false; impact.ShowUIInfo = showUIInfo; impact.TraceErrorMessage = false; impact.AnalyzeDlineage = analyzeDlineage; impact.ignoreTopSelect(false); impact.impactSQL(); if (!string.ReferenceEquals(impact.ErrorMessage, null) && impact.ErrorMessage.Trim().Length > 0) { Console.Error.WriteLine(impact.ErrorMessage.Trim()); } if (fileNode.HasElements) { columnImpactResult.Add(fileNode); } } } if (doc != null) { try { StringBuilder xmlBuffer = new StringBuilder(); using (StringWriter writer = new Utf8StringWriter(xmlBuffer)) { doc.Save(writer, SaveOptions.None); } string result = xmlBuffer.ToString().Trim(); return(result); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } } } else { ColumnImpact impact = new ColumnImpact(sqlContent, vendor, tableColumns, strict); impact.Debug = false; impact.ShowUIInfo = showUIInfo; impact.TraceErrorMessage = false; impact.AnalyzeDlineage = true; impact.impactSQL(); if (!string.ReferenceEquals(impact.ErrorMessage, null) && impact.ErrorMessage.Trim().Length > 0) { Console.Error.WriteLine(impact.ErrorMessage.Trim()); } return(impact.ImpactResult); } return(null); }
internal string DispatchSaveToExtensions( IServiceProvider serviceProvider, ProjectItem projectItem, string fileContents, Lazy <IModelConversionExtension, IEntityDesignerConversionData>[] converters, Lazy <IModelTransformExtension>[] serializers) { Debug.Assert(projectItem != null, "projectItem != null"); Debug.Assert(fileContents != null, "bufferText != null"); Debug.Assert(serializers != null && converters != null, "extensions must not be null"); Debug.Assert(serializers.Any() || converters.Any(), "at least one extension expected"); ModelTransformContextImpl transformContext = null; ModelConversionContextImpl conversionContext = null; try { var original = XDocument.Parse(fileContents, LoadOptions.PreserveWhitespace); var targetSchemaVersion = EdmUtils.GetEntityFrameworkVersion(projectItem.ContainingProject, serviceProvider); Debug.Assert(targetSchemaVersion != null, "we should not get here for Misc projects"); transformContext = new ModelTransformContextImpl(projectItem, targetSchemaVersion, original); // call the extensions that can save EDMX files first (even if we aren't going to end up in an EDMX file, let them process) VSArtifact.DispatchToSerializationExtensions(serializers, transformContext, loading: false); // get the extension of the file being loaded (might not be EDMX); this API will include the preceeding "." var fileInfo = new FileInfo(FileName); var fileExtension = fileInfo.Extension; // now if this is not an EDMX file, hand off to the extension who can convert it to the writable content if (!string.Equals(fileExtension, EntityDesignArtifact.ExtensionEdmx, StringComparison.OrdinalIgnoreCase)) { // the current document coming from the serializers becomes our original conversionContext = new ModelConversionContextImpl( projectItem.ContainingProject, projectItem, fileInfo, targetSchemaVersion, transformContext.CurrentDocument); // we aren't loading an EDMX file, so call the extensions who can process this file extension // when this finishes, then output should be a valid EDMX document VSArtifact.DispatchToConversionExtensions(converters, fileExtension, conversionContext, false); // we are done saving, so get bufferText from the OriginalDocument // TODO use Utf8StringWriter here somehow? return(conversionContext.OriginalDocument); } else { // we are saving an EDMX file, so get bufferText from the XDocument using (var writer = new Utf8StringWriter()) { transformContext.CurrentDocument.Save(writer, SaveOptions.None); return(writer.ToString()); } } } catch (XmlException) { // Don't do anything here. We will want to gracefully step out of the extension loading // and let the core designer handle this. return(fileContents); } finally { var errorList = ErrorListHelper.GetExtensionErrorList(serviceProvider); errorList.Clear(); // log any errors if (conversionContext != null) { if (conversionContext.Errors.Count > 0) { ErrorListHelper.LogExtensionErrors(conversionContext.Errors, projectItem); } conversionContext.Dispose(); } if (transformContext != null) { if (transformContext.Errors.Count > 0) { ErrorListHelper.LogExtensionErrors(transformContext.Errors, projectItem); } transformContext.Dispose(); } } }
private static string OnProjectFileGeneration(string name, string content) { var document = XDocument.Parse(content); if (document.Root != null) { var ie = document.Root.Elements("{http://schemas.microsoft.com/developer/msbuild/2003}PropertyGroup").GetEnumerator(); while (ie.MoveNext()) { if (ie.Current == null || ie.Current.FirstAttribute == null) { continue; } if (!ie.Current.FirstAttribute.Value.Contains("Debug|AnyCPU")) { continue; } ie.Current.Add( new XElement( "{http://schemas.microsoft.com/developer/msbuild/2003}CodeAnalysisRuleSet", basePath + ruleSet)); } ie.Dispose(); ie = document.Root.Elements("{http://schemas.microsoft.com/developer/msbuild/2003}ItemGroup").GetEnumerator(); var insertSuccessful = false; while (ie.MoveNext()) { if (ie.Current == null || ie.Current.FirstNode == null) { continue; } var element = ie.Current.FirstNode as XElement; if (element != null && element.Name != "{http://schemas.microsoft.com/developer/msbuild/2003}None") { continue; } ie.Current.Add(GetSettingsConfigElement()); insertSuccessful = true; } ie.Dispose(); if (!insertSuccessful) { document.Root.Add(GetConfigItemGroup()); } document.Root.Add(GetAnalyzerItemGroup()); document.Root.Add(GetDisableAnalysersTarget()); } string project; using (var str = new Utf8StringWriter()) { document.Save(str); project = str.ToString(); } return(project); }
public async Task <HttpResponseMessage> PROPFIND(HttpRequestMessage httpRequestMessage) { string filter = string.Empty; Item entity = null; XElement response = null; XDocument xRequest = null; XDocument xDocument = new XDocument( new XElement(d + "multistatus", new XAttribute(XNamespace.Xmlns + "d", "DAV:") ) ); xDocument.Declaration = new XDeclaration("1.0", "utf-8", "true"); Stream stream = httpRequestMessage.Content.ReadAsStreamAsync().Result; string rowKey = getRowKey(httpRequestMessage.RequestUri); string depth = httpRequestMessage.Headers.Where(h => h.Key.ToLower() == "depth").FirstOrDefault().Value.FirstOrDefault(); string partitionKey = getPartitionKey(httpRequestMessage.RequestUri, false); string rowParent = getPartitionKey(httpRequestMessage.RequestUri, true); if (partitionKey == "wwwdavroot") { filter = "PartitionKey eq 'wwwdavroot'"; if (rowKey != "/") { filter = "PartitionKey eq '" + partitionKey + "' and " + "RowKey eq '" + rowKey + "'"; TableQuery <Item> query = new TableQuery <Item>().Where(filter); IEnumerable <Item> items = itemTable.ExecuteQuery(query); if (items.Count() == 0) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } else { entity = items.First(); response = responseCollection(Host(httpRequestMessage) + httpRequestMessage.RequestUri.LocalPath, entity); } partitionKey = rowKey; } else { response = responseCollection(Host(httpRequestMessage), new Item() { Created = DateTime.Now, RowKey = "", Timestamp = DateTime.Now, Collection = true }); } } else { filter = "PartitionKey eq '" + partitionKey + "' or " + "(RowKey eq '" + rowKey + "' " + "and PartitionKey eq '" + rowParent + "')"; TableQuery <Item> query = new TableQuery <Item>().Where(filter); IEnumerable <Item> items = itemTable.ExecuteQuery(query); if (items.Count() == 0) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } entity = items.First(); response = responseCollection(Host(httpRequestMessage) + httpRequestMessage.RequestUri.LocalPath, entity); } if (stream.Length > 0) { xRequest = XDocument.Load(stream); } if (stream.Length > 0 && xRequest.Descendants(d + "allprop").Count() == 0) { response = new XElement(d + "response", new XElement(d + "href", Host(httpRequestMessage) + httpRequestMessage.RequestUri.LocalPath), new XElement(d + "propstat", new XElement(d + "status", "HTTP/1.1 200 OK"), new XElement(d + "prop") ), new XElement(d + "propstat", new XElement(d + "status", "HTTP/1.1 404 Not Found"), new XElement(d + "prop") ) ); foreach (var xElement in xRequest.Descendants(d + "prop").Descendants()) { filter = "PartitionKey eq '" + entity.BlobName + "' and RowKey eq '" + xElement.Name.NamespaceName + xElement.Name.LocalName + "'"; TableQuery <Prop> query = new TableQuery <Prop>().Where(filter); IEnumerable <Prop> props = propTable.ExecuteQuery(query); if (props.Count() > 0) { response.Descendants(d + "prop").First().Add( new XElement(xElement.Name.NamespaceName + xElement.Name.LocalName, xElement.Value) ); } else { response.Descendants(d + "prop").Last().Add( new XElement(xElement.Name.Namespace + xElement.Name.LocalName) ); } } } xDocument.Element(d + "multistatus").Add(response); if (depth == "1") { filter = "PartitionKey eq '" + partitionKey + "'"; TableQuery <Item> query = new TableQuery <Item>().Where(filter); IEnumerable <Item> items = itemTable.ExecuteQuery(query); if (partitionKey == "wwwdavroot") { partitionKey = ""; } foreach (Item item in items) { if (item.Collection) { response = responseCollection(Host(httpRequestMessage) + item.PartitionKey.Replace("&dir;", "/") + "/" + item.RowKey + "/", item); } else { response = responseCollection(Host(httpRequestMessage) + partitionKey.Replace("&dir;", "/") + "/" + HttpUtility.HtmlEncode(item.RowKey), item); } xDocument.Element(d + "multistatus").Add(response); } } HttpResponseMessage httpResponseMessage = new HttpResponseMessage((HttpStatusCode)207); Utf8StringWriter utf8writer = new Utf8StringWriter(); xDocument.Save(utf8writer); StringBuilder sb = utf8writer.GetStringBuilder(); httpResponseMessage.Content = new StringContent(sb.ToString(), Encoding.UTF8, "application/xml"); return(httpResponseMessage); }
public void Thread1() { Debug.Log("Thread started"); IPAddress send_to_address = IPAddress.Parse(targetAddress); IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 0); UdpClient udpServer = new UdpClient(myPort); udpServer.Client.ReceiveTimeout = 10; // in milliseconds string received_data; byte[] receive_byte_array; Debug.Log("Listening on port " + sending_end_point.Port); int count = 0; // Read reply: while (udpServer.Available == 0 && threadflag) { } string[] stringSeparators = new string[] { "<IPOC>", "</IPOC>" }; string[] stringSeparators1 = new string[] { "<TestOutput>", "</TestOutput>" }; try { receive_byte_array = udpServer.Receive(ref sending_end_point); received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); string[] temp = received_data.Split(stringSeparators, StringSplitOptions.None); timestamp = temp[1]; Debug.Log("received"); } catch (Exception e) { Debug.LogError(e.ToString()); } XmlWriterSettings Settings = new XmlWriterSettings(); Settings.OmitXmlDeclaration = true; Settings.ConformanceLevel = ConformanceLevel.Fragment; Settings.NewLineOnAttributes = true; Settings.Indent = true; Settings.IndentChars = ""; String position = "RKorr X=\"" + 0 + "\" Y=\"" + 0 + "\" Z=\"" + 0 + "\" A=\"" + 0 + "\" B=\"" + 0 + "\" C=\"" + 0 + "\""; string text; using (TextWriter textWriter = new Utf8StringWriter()) { using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, Settings)) { xmlWriter.WriteStartElement("Sen"); xmlWriter.WriteAttributeString(null, "Type", null, "ImFree"); xmlWriter.WriteElementString("EStr", "Message from Unity"); xmlWriter.WriteElementString( "Tech T21=\"1.09\" T22=\"2.08\" T23=\"3.07\" T24=\"4.06\" T25=\"5.05\" T26=\"6.04\" T27=\"7.03\" T28=\"8.02\" T29=\"9.01\" T210=\"10.00\"", ""); xmlWriter.WriteElementString(position, ""); xmlWriter.WriteElementString("TestOutput", testsend); xmlWriter.WriteElementString("IPOC", timestamp); xmlWriter.WriteEndElement(); } text = textWriter.ToString(); } byte[] send_buffer = Encoding.ASCII.GetBytes(text); try { udpServer.Send(send_buffer, send_buffer.Length, sending_end_point); } catch (Exception e) { Debug.LogError(e.ToString()); } do { try { receive_byte_array = udpServer.Receive(ref sending_end_point); received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); count = 0; string[] temp = received_data.Split(stringSeparators, StringSplitOptions.None); timestamp = temp[1]; string[] temp1 = received_data.Split(stringSeparators1, StringSplitOptions.None); testoutput = temp1[1]; XmlDocument doc = new XmlDocument(); doc.LoadXml(received_data); XmlNode newPos = doc.DocumentElement.SelectSingleNode("/Rob/RIst"); FeedBackSimulateOnCube.x = (float)Convert.ToDouble(newPos.Attributes["X"].Value); FeedBackSimulateOnCube.z = (float)Convert.ToDouble(newPos.Attributes["Y"].Value); FeedBackSimulateOnCube.y = (float)Convert.ToDouble(newPos.Attributes["Z"].Value); FeedBackSimulateOnCube.angleA = (float)Convert.ToDouble(newPos.Attributes["A"].Value); FeedBackSimulateOnCube.angleB = (float)Convert.ToDouble(newPos.Attributes["B"].Value); FeedBackSimulateOnCube.angleC = (float)Convert.ToDouble(newPos.Attributes["C"].Value); } catch (Exception) { Debug.LogWarning("Failed to recieve packet!"); count++; continue; } try { //lock (fs.pos_rot_Lock) //{ pos_copy = fs.current_position; pos_copy.y -= 0.89f; pos_copy *= 200; rot_copy = fs.current_rotation.eulerAngles; //} // Limit position and rotation updates Vector3 newPosition; Vector3 newRotation; if (false) { newPosition = pos_copy; newRotation = rot_copy; // TODO: implement this once inverse kinematics is done } else { newPosition = Vector3.MoveTowards(lastPosition, pos_copy, maxVel); //if (!(Mathf.Approximately(newPosition.x, lastPosition.x) && // Mathf.Approximately(newPosition.y, lastPosition.y) && // Mathf.Approximately(newPosition.z, lastPosition.z))) //{ // Debug.LogWarning("Limited position!"); //} // Rotate angles, MoveTowardsAngle should take of rotation of angles around 360 if (Mathf.Abs(rot_copy.x - rot_last.x) > 180) { rot_copy.x -= 360 * Mathf.Sign(rot_copy.x - rot_last.x); } if (Mathf.Abs(rot_copy.y - rot_last.y) > 180) { rot_copy.y -= 360 * Mathf.Sign(rot_copy.y - rot_last.y); } if (Mathf.Abs(rot_copy.z - rot_last.z) > 180) { rot_copy.z -= 360 * Mathf.Sign(rot_copy.z - rot_last.z); } rot_last = rot_copy; newRotation = Vector3.zero; newRotation.x = Mathf.MoveTowardsAngle(lastRotation.x, rot_copy.x, maxVelAngle); newRotation.y = Mathf.MoveTowardsAngle(lastRotation.y, rot_copy.y, maxVelAngle); newRotation.z = Mathf.MoveTowardsAngle(lastRotation.z, rot_copy.z, maxVelAngle); //if (!(Mathf.Approximately(newRotation.x, lastRotation.x) && // Mathf.Approximately(newRotation.y, lastRotation.y) && // Mathf.Approximately(newRotation.z, lastRotation.z))) //{ // Debug.LogWarning("Limited rotation!"); //} lastPosition = newPosition; lastRotation = newRotation; } // Generate string to send String position1 = "RKorr X=\"" + string.Format("{0:0.00}", newPosition.x) + "\" Y=\"" + string.Format("{0:0.00}", newPosition.z) + "\" Z=\"" + string.Format("{0:0.00}", newPosition.y) + "\" A=\"" + string.Format("{0:0.00}", newRotation.x) + "\" B=\"" + string.Format("{0:0.00}", newRotation.y) + "\" C=\"" + string.Format("{0:0.00}", newRotation.z) + "\""; string text1; using (TextWriter textWriter = new Utf8StringWriter()) { using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, Settings)) { xmlWriter.WriteStartElement("Sen"); xmlWriter.WriteAttributeString(null, "Type", null, "ImFree"); xmlWriter.WriteElementString("EStr", "Message from Unity"); xmlWriter.WriteElementString( "Tech T21=\"1.09\" T22=\"2.08\" T23=\"3.07\" T24=\"4.06\" T25=\"5.05\" T26=\"6.04\" T27=\"7.03\" T28=\"8.02\" T29=\"9.01\" T210=\"10.00\"", ""); xmlWriter.WriteElementString(position1, ""); xmlWriter.WriteElementString("TestOutput", testsend); xmlWriter.WriteElementString("IPOC", timestamp); xmlWriter.WriteEndElement(); } text1 = textWriter.ToString(); } Debug.Log("Sending to: " + sending_end_point.ToString()); byte[] send_buffer1 = Encoding.ASCII.GetBytes(text1); udpServer.Send(send_buffer1, send_buffer1.Length, sending_end_point); } catch (Exception e) { Debug.LogError(e.ToString()); count++; } } while (threadflag); udpServer.Close(); }