Esempio n. 1
0
        private IList <RSSPost> _GetBlogFeeds()
        {
            //Load feed via a feedUrl.
            if (_reader == null)
            {
                _reader = System.Xml.XmlReader.Create(_urlfeed, null);
            }
            var doc = System.Xml.Linq.XDocument.Load(_urlfeed);

            System.Xml.Linq.XNamespace autorns = System.Xml.Linq.XNamespace.Get("http://purl.org/dc/elements/1.1/");
            //Get all the "items" in the feed.
            var feeds = doc.Descendants("item").Select(x =>
                                                       new RSSPost
            {
                //Get title, pubished date, and link elements.
                Title          = x.Element("title").Value,                        //3
                Date           = DateTime.Parse(x.Element("pubDate").Value),
                Url            = x.Element("link").Value,
                Content        = x.Element("description").Value,
                ContentEncoded = x.Element(_namespace + "encoded").Value,
                User           = x.Element(autorns + "creator").Value
            }           //  Put them into an object (FeedViewModel)
                                                       )
                        // Order them by the pubDate (FeedViewModel.PublishedDate).
                        .OrderByDescending(x => x.Date);

            //Only get the amount specified, the top (1, 2, 3, etc.) via feedCount.


            //Convert the feeds to a List and return them.
            return(feeds.ToList());
        }
Esempio n. 2
0
        public RSSFeed(Uri urlfeed)
        {
            _urlfeed   = urlfeed.ToString();
            _reader    = System.Xml.XmlReader.Create(urlfeed.ToString(), null);
            _namespace = System.Xml.Linq.XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
            _rss_feed  = System.ServiceModel.Syndication.SyndicationFeed.Load(_reader);

            _rss_posts = _GetBlogFeeds().ToArray <RSSPost>();
        }
Esempio n. 3
0
        public RSSFeed(Uri urlfeed)
        {
            _urlfeed = urlfeed.ToString();
            _reader = System.Xml.XmlReader.Create(urlfeed.ToString(), null);
            _namespace = System.Xml.Linq.XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
            _rss_feed = System.ServiceModel.Syndication.SyndicationFeed.Load(_reader);

            _rss_posts = _GetBlogFeeds().ToArray<RSSPost>();
        }
Esempio n. 4
0
        void XmppClient_OnMessage(object sender, Matrix.Xmpp.Client.MessageEventArgs e)
        {
            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
            if (e.Message.Body != null && e.Message.Body.Length > 0 && e.Message.Type != MessageType.Error)
            {
                string messageBody            = "";
                System.Xml.Linq.XNamespace ns = "urn:xmpp:openpgp:0";
                string pgpData = (string)
                                 (
                    from el in e.Message.Descendants(ns + "openpgp")
                    select el
                                 ).FirstOrDefault();
                if (pgpData != null)
                {
                    messageBody = this.openPGP.Decrypt(pgpData);
                    Log.Info("encrypted message " + e.Message.From + " " + messageBody);
                }
                else
                {
                    messageBody = e.Message.Body;
                    Log.Info("unencrypted message " + e.Message.From + " " + messageBody);
                }

                if (e.Message.XMucUser != null && this.OnInvit != null)
                {
                    this.OnInvit(this, new MessageEventArgs(e.Message.From, e.Message.XMucUser.FirstElement.FirstAttribute.Value));
                }
                else if (this.OnMessage != null && e.Message.Body != null)
                {
                    var from = e.Message.From.ToString().Split('/');
                    if (from[1] != null && from[1].Equals(_username))
                    {
                        return;
                    }
                    else
                    {
                        this.OnMessage(this, new MessageEventArgs(e.Message.From.ToString().Split('@')[0], e.Message.Body));
                    }
                }
            }
            else if (e.Message.Type == MessageType.GroupChat && e.Message.Subject != null && this.OnSubjectGroup != null)
            {
                this.OnSubjectGroup(this, new MessageEventArgs(e.Message.From, e.Message.Subject));
            }
            else if (e.Message.Type == MessageType.Error)
            {
                Log.Error("OnMessage error " + e.Message.From + " " + e.Message.Body);
                Log.Error(e.Message.ToString());
            }

            //}, null);
        }
Esempio n. 5
0
        private Task DriveLEDPanel(LEDPanel panel)
        {
            TimeSpan updateInterval = TimeSpan.FromMinutes(5);
            DateTime lastUpdate     = DateTime.MinValue;

            return(Task.Run(async() =>
            {
                panel.Clear();

                System.Xml.Linq.XNamespace ns = "http://www.w3.org/2005/Atom";
                try
                {
                    IEnumerable <string> entries = null;
                    while (this.KeepRunning)
                    {
                        if (DateTime.Now > lastUpdate + updateInterval)
                        {
                            var request = System.Net.HttpWebRequest.CreateHttp("http://www.theverge.com/rss/index.xml");
                            var response = await request.GetResponseAsync();

                            var document = System.Xml.Linq.XDocument.Load(response.GetResponseStream());
                            entries = document
                                      .Descendants(ns + "title")
                                      .Select(x => x.Value);

                            lastUpdate = DateTime.Now;
                        }

                        if (entries != null)
                        {
                            foreach (var entry in entries)
                            {
                                var buffer = panel.Render("     " + entry + "     -     ");
                                panel.Display(buffer);
                            }
                        }
                        else
                        {
                            await Task.Delay(TimeSpan.FromSeconds(5));
                        }
                    }
                }
                catch (Exception ex)
                {
                    var buffer = panel.Render(ex.ToString());
                    panel.Display(buffer);
                }
            }));
        }
Esempio n. 6
0
        private Dictionary <string, object> SerializeAllValuesFromString(string text)
        {
            if (_storageFormat == StorageFormat.JSON)
            {
                object obj = Procurios.Public.JSON.JsonDecode(text);
                if (obj is Dictionary <string, object> )
                {
                    return(obj as Dictionary <string, object>);
                }
                else
                {
                    return(null);
                }
            }
            else if (_storageFormat == StorageFormat.XML)
            {
                var settings = new Dictionary <string, object>();
                using (var txtrdr = new System.IO.StringReader(text))
                {
                    var doc = System.Xml.Linq.XDocument.Load(txtrdr);
                    var m   = doc.Root;
                    foreach (var elem in m.Elements())
                    {
                        System.Xml.Linq.XNamespace x = elem.Name.Namespace; // "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
                        string key   = elem.Element(x + "Key").Value;
                        string value = elem.Element(x + "Value").Value;
                        // Handle objects encoded in value?
                        settings[key] = value;
                    }
                    return(settings);
                }

                /*
                 * Easy method but no handling for nested objects
                 * var data = System.Xml.Linq.XElement.Parse(text)
                 *  .Elements("setting")
                 *  .ToDictionary(
                 *      el => (string)el.Attribute("key"),
                 *      el => (object)el.Value
                 *  );
                 * return data;
                 * */
            }
            else
            {
                return(null);
            }
        }
Esempio n. 7
0
        //*********************************************************************
        ///
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        ///
        //*********************************************************************

        public AzureAdminClientLib.HttpResponse ListDisksInSubscription()
        {
            var resp = new AzureAdminClientLib.HttpResponse();

            try
            {
                var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(
                    string.Format("https://management.core.windows.net/{0}/services/disks",
                                  _Connection.SubcriptionID));

                req.Headers["x-ms-version"] = "2014-05-01";
                req.ClientCertificates.Add(_Connection.Certificate);

                System.Xml.Linq.XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";

                req.Method = "GET";
                var response   = (System.Net.HttpWebResponse)req.GetResponse();
                var respStream = response.GetResponseStream();

                if (null == respStream)
                {
                    throw new Exception("Unable to create Stream from HttpWebResponse");
                }

                var reader    = new System.IO.StreamReader(respStream);
                var sResponse = reader.ReadToEnd();

                resp.HadError = false;
                resp.Body     = sResponse;
            }
            catch (Exception ex)
            {
                resp.Body = ex.Message;

                if (ex.Message.Contains("409"))
                {
                    resp.HadError = false;
                }
                else
                {
                    resp.HadError = true;
                }
            }

            return(resp);
        }
Esempio n. 8
0
        public static AssemblyBindingConfig LoadFrom(string path)
        {
            var config = new AssemblyBindingConfig();

            var funcConfig = System.Xml.Linq.XElement.Load(path);
            var runtime    = funcConfig.Element("runtime");

            System.Xml.Linq.XNamespace ns = "urn:schemas-microsoft-com:asm.v1";
            var assemblyBinding           = runtime.Element(ns + "assemblyBinding");
            var assemblyIdentityName      = ns + "assemblyIdentity";
            var bindingRedirectName       = ns + "bindingRedirect";

            foreach (var dependentAssembly in assemblyBinding.Elements(ns + "dependentAssembly"))
            {
                var assemblyIdentity = dependentAssembly.Element(assemblyIdentityName);

                var fullName = (string)assemblyIdentity.Attribute("name");

                if ((string)assemblyIdentity.Attribute("culture") != null)
                {
                    fullName += ", Culture=" + (string)assemblyIdentity.Attribute("culture");
                }

                if ((string)assemblyIdentity.Attribute("publicKeyToken") != null)
                {
                    fullName += ", PublicKeyToken=" + (string)assemblyIdentity.Attribute("publicKeyToken");
                }

                var assemblyName = new AssemblyName(fullName);

                var bindingRedirect = dependentAssembly.Element(bindingRedirectName);

                var oldVersion = ((string)bindingRedirect.Attribute("oldVersion")).Split('-');
                var newVerison = (string)bindingRedirect.Attribute("newVersion");

                var binding = new AssemblyBindingRedirect {
                    OldMinVersion = new Version(oldVersion[0]),
                    OldMaxVersion = new Version(oldVersion[1]),
                    NewVersion    = new Version(newVerison),
                };

                config.Add(assemblyName.Name, binding);
            }

            return(config);
        }
Esempio n. 9
0
        //http://msdn.microsoft.com/en-us/library/dn189154.aspx
        public static void UpdatePlayReadyConfigurationXMLFile(Guid keyId, string contentKeyB64)
        {
            System.Xml.Linq.XNamespace xmlns = "http://schemas.microsoft.com/iis/media/v4/TM/TaskDefinition#";
            string keyDeliveryServiceUriStr  = "http://playready.directtaps.net/pr/svc/rightsmanager.asmx";
            Uri    keyDeliveryServiceUri     = new Uri(keyDeliveryServiceUriStr);

            string xmlFileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\..\..", @"MediaEncryptor_PlayReadyProtection.xml");

            // Prepare the encryption task template
            System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(xmlFileName);

            var licenseAcquisitionUrlEl = doc
                                          .Descendants(xmlns + "property")
                                          .Where(p => p.Attribute("name").Value == "licenseAcquisitionUrl")
                                          .FirstOrDefault();
            var contentKeyEl = doc
                               .Descendants(xmlns + "property")
                               .Where(p => p.Attribute("name").Value == "contentKey")
                               .FirstOrDefault();
            var keyIdEl = doc
                          .Descendants(xmlns + "property")
                          .Where(p => p.Attribute("name").Value == "keyId")
                          .FirstOrDefault();

            // Update the "value" property for each element.
            if (licenseAcquisitionUrlEl != null)
            {
                licenseAcquisitionUrlEl.Attribute("value").SetValue(keyDeliveryServiceUri);
            }

            if (contentKeyEl != null)
            {
                contentKeyEl.Attribute("value").SetValue(contentKeyB64);
            }

            if (keyIdEl != null)
            {
                keyIdEl.Attribute("value").SetValue(keyId);
            }

            doc.Save(xmlFileName);
        }
Esempio n. 10
0
        public (string asin, int price) GetAmazonUsingAPI(string toyName)
        {
            try
            {
                var keyword = toyName.Replace(" ", " ");
                var helper  = new Helper.SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION, ASSOCIATE_TAG);

                IDictionary <string, string> request = new Dictionary <string, String>
                {
                    ["Service"]       = "AWSECommerceService",
                    ["Operation"]     = "ItemSearch",
                    ["SearchIndex"]   = "All",
                    ["ResponseGroup"] = "Medium",
                    ["Keywords"]      = keyword
                };
                var requestUrl = helper.Sign(request);
                System.Xml.Linq.XDocument xml = System.Xml.Linq.XDocument.Load(requestUrl);

                System.Xml.Linq.XNamespace ns = xml.Root.Name.Namespace;
                var errorMessageNodes         = xml.Descendants(ns + "Message").ToList();
                if (errorMessageNodes.Any())
                {
                    var message = errorMessageNodes[0].Value;
                    return(null, 0);
                }
                var item         = xml.Descendants(ns + "Item").FirstOrDefault();
                var asin         = item?.Descendants(ns + "ASIN").FirstOrDefault()?.Value;
                var offerSummary = item?.Descendants(ns + "OfferSummary").FirstOrDefault();
                var price        = offerSummary?.Descendants(ns + "LowestNewPrice").FirstOrDefault()?.Descendants(ns + "Amount").FirstOrDefault()?.Value;

                return(asin, price != null ? Convert.ToInt32(price) : 0);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Task.Delay(Delay).Wait();
            }
        }
Esempio n. 11
0
        private void PubsubManager_OnEvent(object sender, Matrix.Xmpp.Client.MessageEventArgs e)
        {
            Log.Info("pep_onevent " + e.Message.From + " " + e.Message.Value);

            if (e.Message.Value != "")
            {
                string jid = e.Message.From;
                System.Xml.Linq.XNamespace ns = "urn:xmpp:openpgp:0";
                try
                {
                    string pubkey = (string)
                                    (
                        from el in e.Message.Descendants(ns + "pubkey")
                        select el
                                    ).First();
                    this.openPGP.AddPublicKey(jid, pubkey);
                }
                catch (Exception ex)
                {
                    Log.Error(e.Message.Value + " resulted in " + ex.Message);
                }
            }
        }
 public CorrelationKey(IDictionary <string, string> keyData, System.Xml.Linq.XName scopeName, System.Xml.Linq.XNamespace provider) : base(default(Guid))
 {
 }
Esempio n. 13
0
 public string GetPrefixOfNamespace(System.Xml.Linq.XNamespace ns)
 {
     throw null;
 }
Esempio n. 14
0
 public string GetPrefixOfNamespace(System.Xml.Linq.XNamespace ns)
 {
     return(default(string));
 }
Esempio n. 15
0
        /// <summary>
        /// DetectLanguage method
        /// Detect Language from input text.
        /// </summary>
        /// <param name="Text">
        /// Input Text
        /// <return>return language(string)
        /// </return>
        public async System.Threading.Tasks.Task <string> DetectLanguage(string Text)
        {
            string r    = string.Empty;
            int    loop = 1;

            while (loop-- > 0)
            {
                try
                {
                    string uriString = null;
                    uriString = string.Format(DetectUri, Uri.EscapeDataString(Text));
                    System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient();
                    System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
                    hc.DefaultRequestHeaders.Add("Authorization", Token);
                    System.Net.Http.HttpResponseMessage hrm = null;
                    System.Diagnostics.Debug.WriteLine("REST API Get");

                    hrm = await hc.GetAsync(new Uri(BaseUrl + uriString));

                    if (hrm != null)
                    {
                        switch (hrm.StatusCode)
                        {
                        case System.Net.HttpStatusCode.OK:
                            var b = await hrm.Content.ReadAsByteArrayAsync();

                            string result = System.Text.UTF8Encoding.UTF8.GetString(b);
                            if (!string.IsNullOrEmpty(result))
                            {
                                System.Xml.Linq.XNamespace ns = ArrayNamespace;
                                var doc = System.Xml.Linq.XDocument.Parse(result);
                                r = doc.Root.Value;
                            }
                            break;

                        case System.Net.HttpStatusCode.Forbidden:
                            string token = await RenewToken();

                            if (string.IsNullOrEmpty(token))
                            {
                                loop++;
                            }
                            break;

                        default:
                            int    code      = (int)hrm.StatusCode;
                            string HttpError = "Http Response Error: " + code.ToString() + " reason: " + hrm.ReasonPhrase.ToString();
                            System.Diagnostics.Debug.WriteLine(HttpError);
                            break;
                        }
                    }
                }
                catch (System.Threading.Tasks.TaskCanceledException)
                {
                    System.Diagnostics.Debug.WriteLine("http POST canceled");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("http POST exception: " + ex.Message);
                }
                finally
                {
                    System.Diagnostics.Debug.WriteLine("http POST done");
                }
            }
            return(r);
        }
Esempio n. 16
0
        /// <summary>
        /// GetLanguages method
        /// Return the list of supported languages.
        /// </summary>
        /// <return>list of supported languages
        /// </return>
        public async System.Threading.Tasks.Task <System.Collections.Generic.Dictionary <string, string> > GetLanguages()
        {
            System.Collections.Generic.Dictionary <string, string> r = new System.Collections.Generic.Dictionary <string, string>();
            int loop = 1;

            while (loop-- > 0)
            {
                try
                {
                    string languageUrl            = BaseUrl + LanguagesUri;
                    System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient();
                    System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
                    hc.DefaultRequestHeaders.Add("Authorization", Token);
                    System.Net.Http.HttpResponseMessage hrm = null;
                    System.Diagnostics.Debug.WriteLine("REST API Get");
                    hrm = await hc.GetAsync(new Uri(languageUrl));

                    if (hrm != null)
                    {
                        switch (hrm.StatusCode)
                        {
                        case System.Net.HttpStatusCode.OK:
                            var b = await hrm.Content.ReadAsByteArrayAsync();

                            string result = System.Text.UTF8Encoding.UTF8.GetString(b);
                            if (!string.IsNullOrEmpty(result))
                            {
                                System.Xml.Linq.XNamespace ns = ArrayNamespace;
                                var doc = System.Xml.Linq.XDocument.Parse(result);

                                doc.Root.Elements(ns + "string").Select(s => s.Value).ToList().ForEach(lang =>
                                {
                                    try
                                    {
                                        var culture = new System.Globalization.CultureInfo(lang);
                                        if (!culture.EnglishName.StartsWith("Unknown"))
                                        {
                                            r.Add(lang, culture.EnglishName);
                                        }
                                    }
                                    catch
                                    {
                                    }
                                });
                            }
                            break;

                        case System.Net.HttpStatusCode.Forbidden:
                            string token = await RenewToken();

                            if (string.IsNullOrEmpty(token))
                            {
                                loop++;
                            }
                            break;

                        default:
                            int    code      = (int)hrm.StatusCode;
                            string HttpError = "Http Response Error: " + code.ToString() + " reason: " + hrm.ReasonPhrase.ToString();
                            System.Diagnostics.Debug.WriteLine(HttpError);
                            break;
                        }
                    }
                }
                catch (System.Threading.Tasks.TaskCanceledException)
                {
                    System.Diagnostics.Debug.WriteLine("http POST canceled");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("http POST exception: " + ex.Message);
                }
                finally
                {
                    System.Diagnostics.Debug.WriteLine("http POST done");
                }
            }
            return(r);
        }
Esempio n. 17
0
        /// <summary> Reads the earthquakes from an xml file and adds a pin element for each to the map. </summary>
        private void ParseAtomUsingLinq()
        {
            System.Xml.Linq.XDocument  feedXML  = System.Xml.Linq.XDocument.Load("http://earthquake.usgs.gov/earthquakes/catalogs/7day-M2.5.xml");
            System.Xml.Linq.XNamespace xmlns    = "http://www.w3.org/2005/Atom";  //Atom namespace
            System.Xml.Linq.XNamespace georssns = "http://www.georss.org/georss"; //GeoRSS Namespace

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

            int i = 0;

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

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

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

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

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

                    // set position and add to canvas (invert y-ordinate)
                    // set lower right (pin-tip) as position
                    SetLeft(pin, mapPoint.X - pin.Width);
                    SetTop(pin, -(mapPoint.Y + pin.Height));
                    Children.Add(pin);
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Translate method
        /// Translate input text from one language to another language.
        /// </summary>
        /// <param name="Text">
        /// Input Text
        /// <param name="FromLang">
        /// Input Language
        /// <param name="ToLang">
        /// Output Language
        /// </param>
        /// <return>return output text (translated)
        /// </return>
        public async System.Threading.Tasks.Task <string> Translate(string Text, string FromLang, string ToLang)
        {
            string r    = string.Empty;
            int    loop = 1;

            while (loop-- > 0)
            {
                try
                {
                    string uriString = null;
                    if (string.IsNullOrWhiteSpace(FromLang))
                    {
                        uriString = string.Format(TranslateUri, Uri.EscapeDataString(Text), ToLang);
                    }
                    else
                    {
                        uriString = string.Format(TranslateWithFromUri, Uri.EscapeDataString(Text), FromLang, ToLang);
                    }
                    Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient();
                    System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
                    hc.DefaultRequestHeaders.TryAppendWithoutValidation("Authorization", Token);
                    Windows.Web.Http.HttpResponseMessage hrm = null;
                    System.Diagnostics.Debug.WriteLine("REST API Get");
                    IProgress <Windows.Web.Http.HttpProgress> progress = new Progress <Windows.Web.Http.HttpProgress>(ProgressHandler);

                    hrm = await hc.GetAsync(new Uri(BaseUrl + uriString)).AsTask(cts.Token, progress);

                    if (hrm != null)
                    {
                        switch (hrm.StatusCode)
                        {
                        case Windows.Web.Http.HttpStatusCode.Ok:
                            var b = await hrm.Content.ReadAsBufferAsync();

                            string result = System.Text.UTF8Encoding.UTF8.GetString(b.ToArray());
                            if (!string.IsNullOrEmpty(result))
                            {
                                System.Xml.Linq.XNamespace ns = ArrayNamespace;
                                var doc = System.Xml.Linq.XDocument.Parse(result);
                                r = doc.Root.Value;
                            }
                            break;

                        case Windows.Web.Http.HttpStatusCode.Forbidden:
                            string token = await RenewToken();

                            if (string.IsNullOrEmpty(token))
                            {
                                loop++;
                            }
                            break;

                        default:
                            int    code      = (int)hrm.StatusCode;
                            string HttpError = "Http Response Error: " + code.ToString() + " reason: " + hrm.ReasonPhrase.ToString();
                            System.Diagnostics.Debug.WriteLine(HttpError);
                            break;
                        }
                    }
                }
                catch (System.Threading.Tasks.TaskCanceledException)
                {
                    System.Diagnostics.Debug.WriteLine("http POST canceled");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("http POST exception: " + ex.Message);
                }
                finally
                {
                    System.Diagnostics.Debug.WriteLine("http POST done");
                }
            }
            return(r);
        }
Esempio n. 19
0
        //*********************************************************************
        ///
        /// <summary>
        ///
        /// </summary>
        /// <param name="diskInfo"></param>
        /// <returns></returns>
        ///
        //*********************************************************************

        public HttpResponse AddDiskToSubscription(DiskInfo diskInfo)
        {
            var resp = new HttpResponse();

            try
            {
                var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(string.Format("https://management.core.windows.net/{0}/services/disks", _Connection.SubcriptionID));
                req.Headers["x-ms-version"] = "2014-05-01";
                req.ClientCertificates.Add(_Connection.Certificate);

                System.Xml.Linq.XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";

                string xml = null;

                //diskInfo.Name += "yyy";

                switch (diskInfo.Os)
                {
                case DiskInfo.OsEnum.None:
                    xml = string.Format(MAKEDATADISK_TEMPLATE, diskInfo.Label, diskInfo.MediaLink, diskInfo.Name);

                    //****************************
                    //return new HttpResponse {HadError = false};
                    //****************************

                    break;

                default:

                    //*******************
                    //diskInfo.Label = "aaatest1";
                    //diskInfo.Name = diskInfo.Label;
                    //**************************

                    xml = string.Format(MAKEOSDISK_TEMPLATE, diskInfo.Os.ToString(), diskInfo.Label, diskInfo.MediaLink, diskInfo.Name);
                    break;
                }

                var encoding = new System.Text.UTF8Encoding();
                var arr      = encoding.GetBytes(xml);
                req.ContentLength = arr.Length;
                req.Method        = "POST";
                req.ContentType   = "application/xml";
                var dataStream = req.GetRequestStream();
                dataStream.Write(arr, 0, arr.Length);
                dataStream.Close();
                var response   = (System.Net.HttpWebResponse)req.GetResponse();
                var respStream = response.GetResponseStream();

                if (null == respStream)
                {
                    throw new Exception("Unable to create Stream from HttpWebResponse");
                }

                var reader    = new System.IO.StreamReader(respStream);
                var sResponse = reader.ReadToEnd();

                resp.HadError = false;
                resp.Body     = sResponse;
            }
            catch (Exception ex)
            {
                resp.Body = ex.Message;

                if (ex.Message.Contains("409"))
                {
                    resp.HadError = false;
                }
                else
                {
                    resp.HadError = true;
                }
            }

            return(resp);
        }
Esempio n. 20
0
        private static void AddValueToHtForSingleNode(System.Xml.Linq.XDocument xDoc, System.Xml.Linq.XNamespace msbuild, string element)
        {
            var des = xDoc.Descendants(msbuild + element).FirstOrDefault();

            if (des != null)
            {
                htCheck.Add(element, string.IsNullOrEmpty(des.Value) ? null : des.Value);
            }
        }
        //internal static void GetCellStringValues(this WorkbookPart workbookPart,
        //    IEnumerable<Cell> cells, Action<string> values)
        //{
        //    foreach (var cell in cells)
        //    {
        //        values(TryGetStringFromCell(workbookPart, cell));
        //    }
        //}

        //internal static void GetCellStringValues(this WorkbookPart workbookPart,
        //    IEnumerable<Cell> cells, Action<string, Cell> values)
        //{
        //    foreach (var cell in cells)
        //    {
        //        values(TryGetStringFromCell(workbookPart, cell), cell);
        //    }
        //}

        // based on http://ericwhite.com/blog/handling-invalid-hyperlinks-openxmlpackageexception-in-the-open-xml-sdk/
        public static void FixInvalidUri(System.IO.Stream fs, Func <string, Uri> invalidUriHandler)
        {
            System.Xml.Linq.XNamespace relNs = "http://schemas.openxmlformats.org/package/2006/relationships";
            using (var za = new System.IO.Compression.ZipArchive(fs, System.IO.Compression.ZipArchiveMode.Update))
            {
                foreach (var entry in za.Entries.ToList())
                {
                    if (!entry.Name.EndsWith(".rels"))
                    {
                        continue;
                    }
                    bool replaceEntry = false;
                    System.Xml.Linq.XDocument entryXDoc = null;
                    using (var entryStream = entry.Open())
                    {
                        try
                        {
                            entryXDoc = System.Xml.Linq.XDocument.Load(entryStream);
                            if (entryXDoc.Root != null && entryXDoc.Root.Name.Namespace == relNs)
                            {
                                var urisToCheck = entryXDoc
                                                  .Descendants(relNs + "Relationship")
                                                  .Where(r => r.Attribute("TargetMode") != null && (string)r.Attribute("TargetMode") == "External");
                                foreach (var rel in urisToCheck)
                                {
                                    var target = (string)rel.Attribute("Target");
                                    if (target != null)
                                    {
                                        try
                                        {
                                            Uri uri = new Uri(target);
                                        }
                                        catch (UriFormatException)
                                        {
                                            Uri newUri = invalidUriHandler(target);
                                            rel.Attribute("Target").Value = newUri.ToString();
                                            replaceEntry = true;
                                        }
                                    }
                                }
                            }
                        }
                        catch (System.Xml.XmlException)
                        {
                            continue;
                        }
                    }
                    if (replaceEntry)
                    {
                        var fullName = entry.FullName;
                        entry.Delete();
                        var newEntry = za.CreateEntry(fullName);
                        using (var writer = new System.IO.StreamWriter(newEntry.Open()))
                            using (var xmlWriter = System.Xml.XmlWriter.Create(writer))
                            {
                                entryXDoc.WriteTo(xmlWriter);
                            }
                    }
                }
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            var xDocument = System.Xml.Linq.XDocument.Load("stackfiles.xls");

            // XML elements are in the "ss" namespace.
            System.Xml.Linq.XNamespace ss = "urn:schemas-microsoft-com:office:spreadsheet";
            var rows = xDocument.Root.Element(ss + "Worksheet")
                       .Element(ss + "Table").Elements(ss + "Row");
            var files = from c in rows
                        select c.Elements(ss + "Cell").ElementAt(1).Element(ss + "Data").Value;

            var yfiles = new List <System.IO.FileInfo>();

            foreach (var dir in new System.IO.DirectoryInfo(Environment.CurrentDirectory).Root.GetDirectories())
            {
                try
                {
                    yfiles.AddRange(dir.GetFiles("*", System.IO.SearchOption.AllDirectories));
                }
                catch {
                    continue;
                }
            }
            var notfound = new List <string>();
            int i        = 1;

            for (var j = 5; j < files.Count(); j++)
            {
                var file = files.ElementAt(j);
                Console.WriteLine("{0}/{1} {2}", i++, files.Count() - 5, file);
                var xfiles = new List <System.IO.FileInfo>();
                if (file.Length > 0)
                {
                    try
                    {
                        var xfiles2 = yfiles.FindAll((obj) => { return(obj.Name == new System.IO.FileInfo(file).Name); });
                        xfiles.AddRange(xfiles2);
                    }
                    catch { continue; }
                }
                if (xfiles.Count > 0)
                {
                    CreateHardLink(Environment.CurrentDirectory + "\\" + file, xfiles[0].FullName, IntPtr.Zero);
                }
                else
                {
                    notfound.Add(file);
                }
            }
            if (notfound.Count > 0)
            {
                var txt = System.IO.File.CreateText("notfound.txt");
                var sb  = new StringBuilder();
                foreach (var file in notfound)
                {
                    sb.AppendFormat("'{0}',", file);
                }
                sb.Remove(sb.Length - 1, 1);
                js = js.Replace("<FILES>", sb.ToString());
                txt.WriteLine(js);
                txt.Close();
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Get information from project file
        /// </summary>
        public static void GetInfoFromCsporj(string fpFolder)
        {
            string projectFilePath = null;

            try
            {
                #region Get some information from project file
                projectFilePath = Directory.GetFiles(fpFolder).Where(a => Path.GetExtension(Path.GetFileName(a)).ToLower() == ".csproj").FirstOrDefault();
                if (File.Exists(projectFilePath))
                {
                    System.Xml.Linq.XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
                    var projDefinition = System.Xml.Linq.XDocument.Load(projectFilePath);
                    var reference      = projDefinition.Descendants(msbuild + "Reference");
                    List <KeyValuePair <string, string> > libDLLs = new List <KeyValuePair <string, string> >();
                    foreach (System.Xml.Linq.XElement item in reference.Where(a => a.HasElements))
                    {
                        System.Xml.Linq.XElement eHiniPath = item.Element(msbuild + "HintPath");
                        System.Xml.Linq.XElement ePrivate  = item.Element(msbuild + "Private");
                        if (eHiniPath != null)
                        {
                            libDLLs.Add(new KeyValuePair <string, string>(eHiniPath.Value, ePrivate != null ? ePrivate.Value : null));
                        }
                    }
                    htCheck.Add("LibaryDLLFromCsproj", libDLLs);

                    var element = projDefinition.Descendants(msbuild + "Reference");

                    AddValueToHtForSingleNode(projDefinition, msbuild, "OutputType");
                    AddValueToHtForSingleNode(projDefinition, msbuild, "Platform");
                    AddValueToHtForSingleNode(projDefinition, msbuild, "TargetFrameworkProfile");
                    AddValueToHtForSingleNode(projDefinition, msbuild, "TargetFrameworkVersion");

                    if (htCheck["TargetFrameworkProfile"] != null)
                    {
                        htCheck["TargetFrameworkProfile"] = ",Profile=" + htCheck["TargetFrameworkProfile"];
                    }
                    if (htCheck["TargetFrameworkVersion"] != null)
                    {
                        htCheck["TargetFrameworkVersion"] = ",Version=" + htCheck["TargetFrameworkVersion"];
                    }
                    htCheck["FrameworkVersion"] = ".NETFramework" + htCheck["TargetFrameworkVersion"] + htCheck["TargetFrameworkProfile"];

                    var desEmbeddedResource = projDefinition.Descendants(msbuild + "EmbeddedResource");
                    foreach (var item in desEmbeddedResource)
                    {
                        if (item.Attribute("Include") != null && item.Attribute("Include").Value.ToLower().Contains("licenses.licx"))
                        {
                            if (item.Element(msbuild + "CopyToOutputDirectory") != null)
                            {
                                htCheck.Add("LicenseCopyValue", item.Element(msbuild + "CopyToOutputDirectory").Value);
                                break;
                            }
                        }
                    }

                    var desContent = projDefinition.Descendants(msbuild + "Content");
                    foreach (var item in desContent)
                    {
                        if (item.Attribute("Include") != null && item.Attribute("Include").Value.ToLower().Contains("settings.xml"))
                        {
                            if (item.Element(msbuild + "CopyToOutputDirectory") != null)
                            {
                                htCheck.Add("LogSettingsCopyValue", item.Element(msbuild + "CopyToOutputDirectory").Value);
                                break;
                            }
                        }
                    }

                    var    desPropertyGroup = projDefinition.Descendants(msbuild + "PropertyGroup");
                    string platForm         = htCheck["Platform"] != null && htCheck["Platform"].ToString() != "" ? htCheck["Platform"].ToString() : "AnyCPU";
                    foreach (var item in desPropertyGroup)
                    {
                        if (item.Attribute("Condition") != null && item.Attribute("Condition").Value.Contains("Debug|" + platForm + ""))
                        {
                            if (item.Element(msbuild + "RegisterForComInterop") != null)
                            {
                                htCheck.Add("RegisterForComInterop_Debug", item.Element(msbuild + "RegisterForComInterop").Value);
                            }
                        }
                        else if (item.Attribute("Condition") != null && item.Attribute("Condition").Value.Contains("Release|" + platForm + ""))
                        {
                            if (item.Element(msbuild + "RegisterForComInterop") != null)
                            {
                                htCheck.Add("RegisterForComInterop_Release", item.Element(msbuild + "RegisterForComInterop").Value);
                            }
                            else if (item.Element(msbuild + "PlatformTarget") != null)
                            {
                                htCheck.Add("BuildPlatformTarget", item.Element(msbuild + "PlatformTarget").Value);
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("Can not find the .csproj file in FP folder.");
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }