public void SetConfigurationData(string SqlIP, string SqlPort, string SqlUsername, string SqlPassword, int KioskId, string KioskRegion, string AdminPassword, string xmlFileName)
            {
                bool isError = false;
                try
                {
                    Decrypt(xmlFileName);
                }
                catch (Exception)
                {
                    isError = true;
                }

                try
                {

                    var doc = new XDocument(
                        new XElement("Settings",
                            new XElement("SqlIP", SqlIP),
                            new XElement("SqlUsername", SqlUsername),
                            new XElement("SqlPassword", SqlPassword),
                            new XElement("SqlPort", SqlPort),
                            new XElement("AdminPassword", AdminPassword),
                            new XElement("KioskId", KioskId),
                            new XElement("KioskRegion", KioskRegion)));

                    File.WriteAllText(xmlFileName, doc.ToString());
                }
                catch (Exception) { }

                finally
                {
                    if (!isError) Encrypt(xmlFileName);
                }
            }
Example #2
0
        internal static async Task <string> GetClientResponse(
            string endpoint,
            XDocument request,
            XDocument headers,
            HttpClientHandler handler)
        {
            using (var client = handler != null ? new HttpClient(handler, true) : new HttpClient())
            {
                AddHeaders(client, headers);

                var httpContent = new StringContent(request?.ToString(), Encoding.UTF8, "application/xml");

                Console.WriteLine("Response from service:");
                Console.WriteLine("----------------------");

                string response = null;
                try
                {
                    response = await(await client.PostAsync(endpoint, httpContent)).Content.ReadAsStringAsync();
                }
                catch (Exception e)
                {
                    var message = $"Error while trying to get response: {e.Message}";
                    Console.WriteLine(message);
                }

                Console.WriteLine(response);
                Console.WriteLine("----------------------");
                Console.WriteLine("----------------------");

                return(response);
            }
        }
Example #3
0
        internal void WriteAmf3XDocument(XDocument document)
        {
            //if (document == null)
            //    throw new ArgumentNullException("document");

            WriteAmf3Utf(document?.ToString() ?? string.Empty);
        }
        private async Task <string> Serialize(PS_ERIP argReq)
        {
            XDocument reqXml = await SerializationUtil.Serialize(argReq);

            string request = reqXml?.ToString();

            return(request);
        }
Example #5
0
        public static string ReplaceBody(string fullXml, string body)
        {
            XElement  bodyElement = GetBody(fullXml);
            XDocument document    = bodyElement.Document;

            bodyElement.ReplaceWith(GetRoot(body));
            return(document?.ToString());
        }
        private async Task <string> Serialize(MDOM_POS PosArg)
        {
            XDocument reqXml = await SerializationUtil.Serialize(PosArg);

            //string request = $"xml={reqXml?.ToString()}";
            string request = reqXml?.ToString();

            return(request);
        }
Example #7
0
        public ZA3000D DoLoad(ZA3000D FilterData, String Mode)
        {
            ZA3000D SignUpV = new ZA3000D();

            try
            {
                XDocument doc = new XDocument(new XElement("Root",
                                                           new XElement("as_otp", FilterData.Otp),
                                                           new XElement("as_Email", FilterData.Email),
                                                           new XElement("as_Passwd", FilterData.Passwd),
                                                           new XElement("ai_usr_mast_id", FilterData.UsrMastID),
                                                           new XElement("ai_SessionId", FilterData.ZaBase.SessionId),
                                                           new XElement("as_mode", Mode)
                                                           ));

                String     XString = doc.ToString();
                PLABSM.DAL dbObj   = new PLABSM.DAL();
                dbObj.ConnectionMode = PLABSM.ConnectionModes.WebDB;
                DataSet ds = dbObj.SelectSP("ZA3000_sel", XString, PLABSM.DbProvider.MSSql);

                System.Data.DataTable dtComn = PLWM.Utils.GetDataTable(ds, 1);

                if (dtComn.Rows.Count > 0)
                {
                    System.Data.DataRow dr1 = dtComn.Rows[0];


                    SignUpV = new ZA3000D()
                    {
                        UsrMastID = PLWM.Utils.CnvToNullableInt(dr1["usr_mast_id"]),

                        FistNam = PLWM.Utils.CnvToStr(dr1["usr_FistNam"]),
                        LastNam = PLWM.Utils.CnvToStr(dr1["usr_LastNam"]),
                        Email   = PLWM.Utils.CnvToStr(dr1["usr_email"]),
                        Mob     = PLWM.Utils.CnvToStr(dr1["usr_phno"]),
                        ZaBase  = new BaseD()
                        {
                            SessionId = PLWM.Utils.CnvToStr(dr1["SessionId"]),
                            UserName  = PLWM.Utils.CnvToStr(dr1["usr_FistNam"]),
                            ErrorMsg  = "",
                            ZaKey     = Utils.GetKey()
                        }
                    };
                }
            }
            catch (Exception e)
            {
                SignUpV.ZaBase.ErrorMsg = PLWM.Utils.CnvToSentenceCase(e.Message.ToLower().Replace("plerror", "").Replace("plerror", "").Trim());
            }
            return(SignUpV);
        }
Example #8
0
        public object ExecuteCommand(XDocument commandXml)
        {
            string uri = string.Empty;

            switch (this.APIVersion)
            {
            case NexposeAPIVersion.v11:
                uri = "/api/1.1/xml";
                break;

            case NexposeAPIVersion.v12:
                uri = "/api/1.2/xml";
                break;

            default:
                throw new Exception("Unknown API version.");
            }
            byte[]         byteArray = Encoding.ASCII.GetBytes(commandXml.ToString());
            HttpWebRequest request   = WebRequest.Create("https://" + this.Host + ":" + this.Port + uri) as HttpWebRequest;

            request.Proxy         = new WebProxy("127.0.0.1:8080");
            request.Method        = "POST";
            request.ContentType   = "text/xml";
            request.ContentLength = byteArray.Length;

            using (Stream dataStream = request.GetRequestStream())
                dataStream.Write(byteArray, 0, byteArray.Length);

            string xml = string.Empty;

            using (HttpWebResponse r = request.GetResponse() as HttpWebResponse) {
                using (StreamReader reader = new StreamReader(r.GetResponseStream()))
                    xml = reader.ReadToEnd();

                if (r.ContentType.Contains("multipart/mixed"))
                {
                    string[] splitRequest = xml
                                            .Split(new string[] { "--AxB9sl3299asdjvbA" }, StringSplitOptions.None);

                    splitRequest = splitRequest [2]
                                   .Split(new string[] { "\r\n\r\n" }, StringSplitOptions.None);

                    string base64Data = splitRequest [1]
                                        .Substring(0, splitRequest [1].IndexOf("DQo="));

                    return(Convert.FromBase64String(base64Data));
                }
            }

            return(XDocument.Parse(xml));
        }
Example #9
0
        public string[][] UpdateProjFilesCallback(string file)
        {
            List <string> filesToRequest    = new List <string>();
            List <string> newFilesToRequest = new List <string>();
            XDocument     xd   = XDocument.Load(ProjPath + "\\CoProFiles\\timestamps.xml");
            bool          cond = xd.ToString() != file;

            if (cond)
            {
                XmlTextReader xr = new XmlTextReader(new System.IO.StringReader(file));
                Dictionary <string, string[]> serverDictionary = new Dictionary <string, string[]>();
                while (xr.Read())
                {
                    xr.MoveToContent();
                    if (xr.NodeType == System.Xml.XmlNodeType.Element && xr.Name == "File")
                    {
                        serverDictionary[xr.GetAttribute(0)]    = new string[2];
                        serverDictionary[xr.GetAttribute(0)][0] = xr.GetAttribute(1);
                        serverDictionary[xr.GetAttribute(0)][1] = xr.GetAttribute(2);
                    }
                }
                xr.Close();
                xr = new XmlTextReader(ProjPath + "\\CoProFiles\\timestamps.xml");
                Dictionary <string, string[]> myDictionary = new Dictionary <string, string[]>();
                while (xr.Read())
                {
                    xr.MoveToContent();
                    if (xr.NodeType == System.Xml.XmlNodeType.Element && xr.Name == "File")
                    {
                        myDictionary[xr.GetAttribute(0)]    = new string[2];
                        myDictionary[xr.GetAttribute(0)][0] = xr.GetAttribute(1);
                        myDictionary[xr.GetAttribute(0)][1] = xr.GetAttribute(2);
                    }
                }
                xr.Close();
                for (int i = 0; i < serverDictionary.Keys.Count; i++)
                {
                    string tempKey = serverDictionary.Keys.ElementAt(i);
                    if (!myDictionary.ContainsKey(tempKey))
                    {
                        newFilesToRequest.Add(serverDictionary[tempKey][1] + "\\" + tempKey);
                    }
                    else if (myDictionary[tempKey][0] != serverDictionary[tempKey][0])
                    {
                        filesToRequest.Add(serverDictionary[tempKey][1] + "\\" + tempKey);
                    }
                }
            }
            string[][] arrs = { filesToRequest.ToArray(), newFilesToRequest.ToArray() };
            return(arrs);
        }
Example #10
0
        public override MetadataFileResult EpisodeMetadata(Series series, EpisodeFile episodeFile)
        {
            if (!Settings.EpisodeMetadata)
            {
                return(null);
            }

            _logger.Debug("Generating Episode Metadata for: {0}", Path.Combine(series.Path, episodeFile.RelativePath));

            var xmlResult = string.Empty;

            foreach (var episode in episodeFile.Episodes.Value)
            {
                var sb  = new StringBuilder();
                var xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Indent             = false;

                using (var xw = XmlWriter.Create(sb, xws))
                {
                    var doc = new XDocument();

                    var details = new XElement("details");
                    details.Add(new XElement("id", series.Id));
                    details.Add(new XElement("title", string.Format("{0} - {1}x{2:00} - {3}", series.Title, episode.SeasonNumber, episode.EpisodeNumber, episode.Title)));
                    details.Add(new XElement("series_name", series.Title));
                    details.Add(new XElement("episode_name", episode.Title));
                    details.Add(new XElement("season_number", episode.SeasonNumber.ToString("00")));
                    details.Add(new XElement("episode_number", episode.EpisodeNumber.ToString("00")));
                    details.Add(new XElement("firstaired", episode.AirDate));
                    details.Add(new XElement("genre", string.Join(" / ", series.Genres)));
                    details.Add(new XElement("actor", string.Join(" / ", series.Actors.ConvertAll(c => c.Name + " - " + c.Character))));
                    details.Add(new XElement("overview", episode.Overview));


                    //Todo: get guest stars, writer and director
                    //details.Add(new XElement("credits", tvdbEpisode.Writer.FirstOrDefault()));
                    //details.Add(new XElement("director", tvdbEpisode.Directors.FirstOrDefault()));

                    doc.Add(details);
                    doc.Save(xw);

                    xmlResult += doc.ToString();
                    xmlResult += Environment.NewLine;
                }
            }

            var filename = GetEpisodeMetadataFilename(episodeFile.RelativePath);

            return(new MetadataFileResult(filename, xmlResult.Trim(Environment.NewLine.ToCharArray())));
        }
Example #11
0
        private static string CreateXmlWithoutEmptyValues()
        {
            var doc  = new XDocument();
            var root = new XElement("NullableValues");

            root.Add(new XElement("Id", 123),
                     new XElement("StartDate", new DateTime(2010, 2, 21, 9, 35, 00).ToString()),
                     new XElement("UniqueId", new Guid(GuidString))
                     );

            doc.Add(root);

            return(doc.ToString());
        }
Example #12
0
        private static string CreateXmlWithNullValues()
        {
            var doc  = new XDocument();
            var root = new XElement("NullableValues");

            root.Add(new XElement("Id", null),
                     new XElement("StartDate", null),
                     new XElement("UniqueId", null)
                     );

            doc.Add(root);

            return(doc.ToString());
        }
Example #13
0
        public void Can_Deserialize_Lastfm_Xml()
        {
            string       xmlpath  = this.PathFor("Lastfm.xml");
            XDocument    doc      = XDocument.Load(xmlpath);
            RestResponse response = new RestResponse {
                Content = doc.ToString()
            };
            XmlDeserializer d      = new XmlDeserializer();
            Event           output = d.Deserialize <Event>(response);

            //Assert.NotEmpty(output.artists);
            Assert.Equal("http://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008", output.url);
            Assert.Equal("http://www.last.fm/venue/8777860+Barbican+Centre", output.venue.url);
        }
Example #14
0
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var executeFetchRequest = (ExecuteFetchRequest)request;

            if (executeFetchRequest.FetchXml == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "You need to provide FetchXml value");
            }

            var service = ctx.GetFakedOrganizationService();

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(executeFetchRequest.FetchXml)
            };
            var queryResult = (service.Execute(retrieveMultiple) as RetrieveMultipleResponse).EntityCollection;

            XDocument doc = new XDocument(new XElement("resultset",
                                                       new XAttribute("morerecords", Convert.ToInt16(queryResult.MoreRecords))));

            if (queryResult.PagingCookie != null)
            {
                doc.Root.Add(new XAttribute("paging-cookie", queryResult.PagingCookie));
            }

            var allowedAliases = new string[0];

            var fetchXmlDocument = XDocument.Parse(executeFetchRequest.FetchXml).Root;

            if (fetchXmlDocument != null)
            {
                var linkedEntityName = fetchXmlDocument.Descendants("link-entity").Attributes("name").Select(a => a.Value).Distinct();
                allowedAliases = linkedEntityName.Concat(fetchXmlDocument.Descendants("link-entity").Attributes("alias").Select(a => a.Value).Distinct()).ToArray();
            }

            foreach (var row in queryResult.Entities)
            {
                doc.Root.Add(CreateXmlResult(row, ctx, allowedAliases));
            }

            var response = new ExecuteFetchResponse
            {
                Results = new ParameterCollection
                {
                    { "FetchXmlResult", doc.ToString() }
                }
            };

            return(response);
        }
Example #15
0
        public void Can_Deserialize_Google_Weather_Xml()
        {
            string       xmlpath  = this.PathFor("GoogleWeather.xml");
            XDocument    doc      = XDocument.Load(xmlpath);
            RestResponse response = new RestResponse {
                Content = doc.ToString()
            };
            XmlDeserializer d      = new XmlDeserializer();
            xml_api_reply   output = d.Deserialize <xml_api_reply>(response);

            Assert.NotEmpty(output.weather);
            Assert.Equal(4, output.weather.Count);
            Assert.Equal("Sunny", output.weather[0].condition.data);
        }
Example #16
0
        public ProjectFile ReadProjectFile(XDocument projectFileContents, string projectUnderTestNameFilter)
        {
            _logger.LogDebug("Reading the project file {0}", projectFileContents.ToString());

            var rererence       = FindProjectReference(projectFileContents, projectUnderTestNameFilter);
            var targetFramework = FindTargetFrameworkReference(projectFileContents);
            var assemblyName    = FindAssemblyName(projectFileContents);

            return(new ProjectFile()
            {
                ProjectReference = rererence,
                TargetFramework = targetFramework
            });
        }
Example #17
0
        private static string UpdateXml(IDictionary <string, object> tagValues, IEnumerable <Substitution> subs, XDocument baseXml, XmlNamespaceManager nsm,
                                        XDocument subsXml)
        {
            var nss =
                subsXml
                .XPathSelectElements("/s:Root/s:Namespaces/s:Namespace", nsm)
                .Select(ns => new Namespace
            {
                Prefix = ns.Attribute("Prefix").Value,
                Uri    = ns.Value
            });
            var baseNsm = new XmlNamespaceManager(new NameTable());

            foreach (var ns in nss)
            {
                baseNsm.AddNamespace(ns.Prefix, ns.Uri);
            }
            foreach (var sub in subs)
            {
                var activeNode = baseXml.XPathSelectElement(sub.XPath.RenderTemplate(tagValues), baseNsm);

                if (activeNode == null)
                {
                    throw new ApplicationException(String.Format("XPath select of {0} returned null", sub.XPath));
                }

                if (sub.HasReplacementContent)
                {
                    ReplaceChildNodes(tagValues, activeNode, sub);
                }
                if (sub.HasAddChildContent)
                {
                    AddChildContentToActive(tagValues, activeNode, sub);
                }
                if (sub.HasAppendAfter)
                {
                    AppendAfterActive(tagValues, activeNode, sub);
                }
                if (sub.RemoveCurrentAttributes)
                {
                    activeNode.RemoveAttributes();
                }
                foreach (var ca in sub.ChangeAttributes)
                {
                    activeNode.SetAttributeValue(ca.Item1,
                                                 ca.Item2.RenderTemplate(tagValues));
                }
            }
            return(baseXml.ToString());
        }
Example #18
0
        public void AddAttributesZero()
        {
            XDocument xdoc = Composer.SetUpJunitDocument();
            var       xei  = xdoc.Descendants("testsuites").GetEnumerator();

            xei.MoveNext();
            var xelt = xei.Current;

            Composer.addAttributes(xelt);
            string xdocStr = xdoc.ToString();
            string correct = "<testsuites tests=\"0\" failures=\"0\" errors=\"0\" />";

            Assert.True(correct == xdocStr);
        }
Example #19
0
        //#TNWelcomesModi


        public static string FindFollowers()
        {
            string handle   = "narendramodi";
            String response = TwitterFollowers.GetTwitterFollowersi(ConsumerKey, ConsumerKeySecret, AccessToken, AccessTokenSecret, handle);

            Console.WriteLine(response);
            JObject oj = JObject.Parse(response);


            XDocument doc = JsonConvert.DeserializeObject <XDocument>(response);

            Console.WriteLine(doc.ToString());
            return(response);
        }
Example #20
0
        public string ReadXml()
        {
            document = new XDocument();

            LoadXmlDocument();

            BasicOperations();

            GetBookWithComputerGenry();

            var element1 = CreateNewXml();

            return(document.ToString());
        }
Example #21
0
        /// <summary>
        /// 模拟并发请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <param name="requestMessaageDoc"></param>
        /// <returns></returns>
        private string TestAsyncTask(string url, string token, XDocument requestMessaageDoc)
        {
            //修改MsgId,防止被去重
            if (requestMessaageDoc.Root.Element("MsgId") != null)
            {
                requestMessaageDoc.Root.Element("MsgId").Value =
                    DateTimeHelper.GetUnixDateTime(SystemTime.Now.AddSeconds(Thread.CurrentThread.GetHashCode())).ToString();
            }

            var responseMessageXml = MessageAgent.RequestXml(null, url, token, requestMessaageDoc.ToString(), 1000 * 20);

            Thread.Sleep(100); //模拟服务器响应时间
            return(responseMessageXml);
        }
Example #22
0
        private async void updateXMLFile(XDocument xdoc)
        {
            try
            {
                //StorageFile file = await installedLocation.CreateFileAsync("Contacts.xml", CreationCollisionOption.ReplaceExisting);
                StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml"); //This line was the replacement for the one above.

                await FileIO.WriteTextAsync(file, xdoc.ToString());
            }
            catch (Exception ex)
            {
                String s = ex.ToString();
            }
        }
Example #23
0
        public void Can_Deserialize_Goodreads_Xml()
        {
            string       xmlpath  = this.PathFor("Goodreads.xml");
            XDocument    doc      = XDocument.Load(xmlpath);
            RestResponse response = new RestResponse {
                Content = doc.ToString()
            };
            XmlDeserializer           d      = new XmlDeserializer();
            GoodReadsReviewCollection output = d.Deserialize <GoodReadsReviewCollection>(response);

            Assert.Equal(2, output.Reviews.Count);
            Assert.Equal("1208943892", output.Reviews[0].Id); // This fails without fixing the XmlDeserializer
            Assert.Equal("1198344567", output.Reviews[1].Id);
        }
Example #24
0
        public override XDocument Init(XDocument postDataDocument, object postData = null)
        {
            //进行加密判断并处理
            _postModel = postData as PostModel;
            var postDataStr = postDataDocument.ToString();

            XDocument decryptDoc = postDataDocument;

            if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
            {
                //使用了加密
                UsingEcryptMessage    = true;
                EcryptRequestDocument = postDataDocument;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
                string        msgXml   = null;
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExcute = true;
                    return(null);
                }

                if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value))
                {
                    //TODO:使用了兼容模式,进行验证即可
                    UsingCompatibilityModelEcryptMessage = true;
                }

                decryptDoc = XDocument.Parse(msgXml);//完成解密
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc);
            if (UsingEcryptMessage)
            {
                RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value;
            }


            //记录上下文
            if (WeixinContextGlobal.UseWeixinContext)
            {
                WeixinContext.InsertMessage(RequestMessage);
            }

            return(decryptDoc);
        }
Example #25
0
 /// <summary>
 /// Convert an xml document to an object
 /// </summary>
 /// <typeparam name="T">The type of the object to be converted to</typeparam>
 /// <param name="document">The xml document</param>
 /// <returns>The object representation as a result of the deserialization of the xml document</returns>
 public static T XmlDeserialize <T>(XDocument document)
 {
     using (XmlReader reader = document.Root.CreateReader())
     {
         if (reader.CanReadBinaryContent)
         {
             return((T)(new XmlSerializer(typeof(T))).Deserialize(reader));
         }
         else
         {
             return(XmlStringDeserialize <T>(document.ToString()));
         }
     }
 }
Example #26
0
        public void RemoveAnnotation(Guid id)
        {
            XDocument annotation = XDocument.Parse(Value);

            var annotationObjectEntity = _annotationObjects.FirstOrDefault(x => x.Id == id);

            if (annotationObjectEntity != null)
            {
                _annotationObjects.Remove(annotationObjectEntity);
                annotation.Descendants("Object").Where(x => x.Element("Guid").Value == annotationObjectEntity.Id.ToString()).Remove();
            }

            UpdateContainer(annotation.ToString());
        }
Example #27
0
        /// <summary>
        /// Generates SSML.
        /// </summary>
        /// <param name="locale">The locale.</param>
        /// <param name="gender">The gender.</param>
        /// <param name="name">The voice name.</param>
        /// <param name="text">The text input.</param>
        private string GenerateSsml(string locale, string gender, string name, string text)
        {
            var ssmlDoc = new XDocument(
                new XElement("speak",
                             new XAttribute("version", "1.0"),
                             new XAttribute(XNamespace.Xml + "lang", "en-US"),
                             new XElement("voice",
                                          new XAttribute(XNamespace.Xml + "lang", locale),
                                          new XAttribute(XNamespace.Xml + "gender", gender),
                                          new XAttribute("name", name),
                                          text)));

            return(ssmlDoc.ToString());
        }
        void RunTest(string name, string asmPath, string sourcePath)
        {
            var resolver = new DefaultAssemblyResolver();
            var assembly = AssemblyDefinition.ReadAssembly(asmPath, new ReaderParameters {
                AssemblyResolver = resolver, InMemory = true
            });
            Resource res        = assembly.MainModule.Resources.First();
            Stream   bamlStream = LoadBaml(res, name + ".baml");

            Assert.IsNotNull(bamlStream);
            XDocument document = BamlResourceEntryNode.LoadIntoDocument(resolver, assembly, bamlStream, CancellationToken.None);

            XamlIsEqual(File.ReadAllText(sourcePath), document.ToString());
        }
Example #29
0
        public static void Example1()
        {
            var hosts = from ip in File.ReadAllLines("IP.csv")
                        let segments = ip.Split('#')
                                       let hostaddress = segments[0]
                                                         let hostName = segments[1]
                                                                        select new XElement("address", // <address><ip>...</ip><name>...</name></address>
                                                                                            new XElement("ip", hostaddress),
                                                                                            new XElement("name", hostName)
                                                                                            );
            XDocument xDoc = new XDocument(new XComment("Host Table"), new XElement("addresses", hosts));

            Console.WriteLine(xDoc.ToString());
        }
Example #30
0
        public void UninstallDoesNotRemoveCustomTelemetryProcessors()
        {
            string    emptyConfig        = ConfigurationHelpers.GetEmptyConfig();
            XDocument configAfterInstall = ConfigurationHelpers.InstallTransform(emptyConfig);

            // Replace valid type on custom so during uninstall it should stay in the config
            string customConfig = configAfterInstall.ToString().Replace("AdaptiveSamplingTelemetryProcessor", "blah");

            XDocument configAfterUninstall = ConfigurationHelpers.UninstallTransform(customConfig);

            Trace.WriteLine(configAfterUninstall.ToString());

            Assert.AreEqual(2, ConfigurationHelpers.GetTelemetryProcessorsFromDefaultSink(configAfterUninstall).ToList().Count);
        }
        public State Convert(GeneralOptions options)
        {
            var root = new XElement(new XElement(Structure.Root));

            root.Add(new XElement(Structure.Theme, options.Theme));
            root.Add(new XElement(Structure.HighlightTail, options.HighlightTail));
            root.Add(new XElement(Structure.Duration, options.HighlightDuration));
            root.Add(new XElement(Structure.Scale, options.Scale));
            root.Add(new XElement(Structure.Rating, options.Rating));
            var doc   = new XDocument(root);
            var value = doc.ToString();

            return(new State(1, value));
        }
Example #32
0
 public void XDocumentToStringThrowsForXDocumentContainingOnlyWhitespaceNodes()
 {
     // XDocument.ToString() throw exception for the XDocument containing whitespace node only
     XDocument d = new XDocument();
     d.Add(" ");
     string s = d.ToString();
 }
        /// <summary>
        /// Gets the Open Search XML for the current site. You can customize the contents of this XML here. See
        /// http://www.hanselman.com/blog/CommentView.aspx?guid=50cc95b1-c043-451f-9bc2-696dc564766d#commentstart
        /// http://www.opensearch.org
        /// </summary>
        /// <returns>The Open Search XML for the current site.</returns>
        public string GetOpenSearchXml()
        {
            // Short name must be less than or equal to 16 characters.
            string shortName = "Search";
            string description = "Search the ASP.NET MVC Boilerplate Site";
            // The link to the search page with the query string set to 'searchTerms' which gets replaced with a user 
            // defined query.
            string searchUrl = this.urlHelper.AbsoluteRouteUrl(
                HomeControllerRoute.GetSearch, 
                new { query = "{searchTerms}" });
            // The link to the page with the search form on it. The home page has the search form on it.
            string searchFormUrl = this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex);
            // The link to the favicon.ico file for the site.
            string favicon16Url = this.urlHelper.AbsoluteContent("~/content/icons/favicon.ico");
            // The link to the favicon.png file for the site.
            string favicon32Url = this.urlHelper.AbsoluteContent("~/content/icons/favicon-32x32.png");
            // The link to the favicon.png file for the site.
            string favicon96Url = this.urlHelper.AbsoluteContent("~/content/icons/favicon-96x96.png");

            XNamespace ns = "http://a9.com/-/spec/opensearch/1.1";
            XDocument document = new XDocument(
                new XElement(
                    ns + "OpenSearchDescription",
                    new XElement(ns + "ShortName", shortName),
                    new XElement(ns + "Description", description),
                    new XElement(ns + "Url",
                        new XAttribute("type", "text/html"),
                        new XAttribute("method", "get"),
                        new XAttribute("template", searchUrl)),
                    // Search results can also be returned as RSS. Here, our start index is zero for the first result.
                    // new XElement(ns + "Url",
                    //     new XAttribute("type", "application/rss+xml"),
                    //     new XAttribute("indexOffset", "0"),
                    //     new XAttribute("rel", "results"),
                    //     new XAttribute("template", "http://example.com/?q={searchTerms}&amp;start={startIndex?}&amp;format=rss")),
                    // Search suggestions can also be returned as JSON.
                    // new XElement(ns + "Url",
                    //     new XAttribute("type", "application/json"),
                    //     new XAttribute("indexOffset", "0"),
                    //     new XAttribute("rel", "suggestions"),
                    //     new XAttribute("template", "http://example.com/suggest?q={searchTerms}")),
                    new XElement(
                        ns + "Image", 
                        favicon16Url,
                        new XAttribute("height", "16"),
                        new XAttribute("width", "16"),
                        new XAttribute("type", "image/x-icon")),
                    new XElement(
                        ns + "Image", 
                        favicon32Url,
                        new XAttribute("height", "32"),
                        new XAttribute("width", "32"),
                        new XAttribute("type", "image/png")),
                    new XElement(
                        ns + "Image", 
                        favicon96Url,
                        new XAttribute("height", "96"),
                        new XAttribute("width", "96"),
                        new XAttribute("type", "image/png")),
                    new XElement(ns + "InputEncoding", "UTF-8"),
                    new XElement(ns + "SearchForm", searchFormUrl)));

            return document.ToString(Encoding.UTF8);
        }