示例#1
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new ModernHttpClient1.App());

            CancellationTokenSource _cts;

            _cts = new CancellationTokenSource();

            Task.Run(async() => {
                try
                {
                    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(new NativeMessageHandler());
                    var stream = await client.GetStreamAsync(MainActivity.WisdomUrl);
                    int i      = 1;
                }
                catch (Exception ex)
                {
                    int i = 1;
                }
            }, _cts.Token);
        }
示例#2
0
        /// <summary>
        /// Load the given reference
        /// </summary>
        /// <returns>The load.</returns>
        /// <param name="context">The context.</param>
        /// <param name="reference">The load reference.</param>
        public void Load(IScriptAnalyzerContext context, LoadReference reference)
        {
            var urlsPath = GetUrlsPath(context.Root.GetDirectory());

            var actualUrl = reference.Address;

            var referenceHash = HashMd5(actualUrl.ToString());

            var urlFile = urlsPath.CombineWithFilePath(referenceHash + ".cake").MakeAbsolute(_environment);

            if (!System.IO.File.Exists(urlFile.FullPath))
            {
                var urlFileDir = urlFile.GetDirectory().FullPath;

                // Make sure the directory exists we want to save to
                if (!System.IO.Directory.Exists(urlFileDir))
                {
                    System.IO.Directory.CreateDirectory(urlFileDir);
                }

                var http = new System.Net.Http.HttpClient();

                using (var httpStream = http.GetStreamAsync(actualUrl).Result)
                    using (var cacheStream = System.IO.File.Create(urlFile.MakeAbsolute(_environment).FullPath))
                    {
                        httpStream.CopyTo(cacheStream);
                    }
            }

            context.Analyze(urlFile);
        }
示例#3
0
        public static async System.Threading.Tasks.Task <Comment[]> ParseXmlHttp(string uri)
        {
            var client = new System.Net.Http.HttpClient();
            var stream = await client.GetStreamAsync(uri);

            return(ParseXml(stream));
        }
示例#4
0
        public async Task MusicBox()
        {
            var user   = Context.User as SocketGuildUser;
            var RoleID = user.Guild.GetRole(Room1.Kids_Bedroom.Id);

            if (!user.Roles.Contains(RoleID))
            {
                return;
            }

            if (States.KidRoomState == States.StatesListKids[3])
            {
                EmbedBuilder embed = new EmbedBuilder();
                embed.WithDescription("I inspect the music box");
                if (States.BedInventory.Contains("Key"))
                {
                    embed.WithImageUrl("https://media.discordapp.net/attachments/575130189281886218/586742273836843041/image0.png?width=1015&height=677");
                    embed.AddField("I turn the key on the music box", "It starts to play a classical tune, sounds familliar");
                    using (var client = new System.Net.Http.HttpClient())
                        using (var testStream = await client.GetStreamAsync("https://cdn.discordapp.com/attachments/572605573821104128/584952213869166646/music-box.mp3"))
                            await Context.Channel.SendFileAsync(testStream, "music-box.mp3");
                }
                else
                {
                    embed.AddField("Looks like there's a key lock on the music box", "Maybe I should come back here if I find one");
                    embed.WithImageUrl("https://media.discordapp.net/attachments/575130189281886218/586742225719918613/image0.png?width=1015&height=677");
                }
                await Room1.BedroomChannel.SendMessageAsync("", false, embed.Build());
            }
        }
示例#5
0
        public async void Verify()
        {
            if (System.Threading.Interlocked.CompareExchange(ref mVerifyStatus, 1, 0) == 0)
            {
                try
                {
                    var value = await client.GetStreamAsync(Uri);

                    OnSocketError(false);
                }
                catch (Exception e_)
                {
                    if (e_ is SocketException || e_.InnerException is SocketException)
                    {
                        OnSocketError(true);
                    }
                    else
                    {
                        OnSocketError(false);
                    }
                    if (Gateway.HttpServer.EnableLog(LogType.Debug))
                    {
                        Gateway.HttpServer.Log(LogType.Debug, $"Gateway verify {Uri} server error {e_.Message}  available[{Available}]");
                    }
                }
                finally
                {
                    System.Threading.Interlocked.Exchange(ref mVerifyStatus, 0);
                }
            }
        }
		public async Task<bool> Refresh()
		{
			if (!RevistaController.Instance.RefreshLista(
				await LibHelper.GetHttpPageAsyncHelper(RevistaController.RevistaUrl)))
				return false;

			var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(PATHIMAGENS, CreationCollisionOption.OpenIfExists);
			if (folder == null)
				return false;
			using (var http = new System.Net.Http.HttpClient())
			{
				var ll = await folder.GetFilesAsync();
				foreach (var item in Lista.Where(x => ll.FirstOrDefault(y => y.Name.Equals(Path.GetFileName(x.ImgUrl.AbsolutePath))) == null))
				{
					var file = await folder.CreateFileAsync(Path.GetFileName(item.ImgUrl.AbsolutePath), CreationCollisionOption.ReplaceExisting);

					using (var str = await http.GetStreamAsync(item.ImgUrl))
					{
						str.CopyTo(await file.OpenStreamForWriteAsync());
					}
					item.ImgUrl = new Uri(file.Path);
				}
			}
			return true;
		}
示例#7
0
        public static List <Station> LeerEstaciones()
        {
            List <Station> estaciones = new List <Station>();

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var xmlStream = client.GetStreamAsync("http://radioudg.okhosting.com/virtuales.xml").Result;

            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlStream);

            //extraer episodios del xml
            while (reader.ReadToFollowing("estacion"))
            {
                Station estacion = new Station();

                reader.ReadToFollowing("imagen");
                estacion.WebSiteUri = new Uri(reader.ReadElementContentAsString());

                reader.ReadToFollowing("streaming");
                estacion.StramingUri = new Uri(reader.ReadElementContentAsString());

                reader.ReadToFollowing("nombre");
                estacion.Name = reader.ReadElementContentAsString();

                reader.ReadToFollowing("descripcion");
                estacion.Description = reader.ReadElementContentAsString();

                estaciones.Add(estacion);
            }

            reader.Dispose();
            xmlStream.Dispose();
            client.Dispose();

            return(estaciones);
        }
示例#8
0
        public async Task GetTotalNumberOfImportItemsFromService()
        {
            string serviceUrl      = System.Web.Configuration.WebConfigurationManager.AppSettings["Activities.Url"];
            string serviceUsername = (System.Web.Configuration.WebConfigurationManager.AppSettings["Activities.Import.User"] ?? string.Empty).DecryptString();
            string servicePassword = (System.Web.Configuration.WebConfigurationManager.AppSettings["Activities.Import.Password"] ?? string.Empty).DecryptString();

            List <DTO.TaskOrderImportDTO> taskOrders = null;

            using (var web = new System.Net.Http.HttpClient())
            {
                web.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(serviceUsername + ":" + servicePassword)));

                using (var stream = await web.GetStreamAsync(serviceUrl))
                    using (var jReader = new Newtonsoft.Json.JsonTextReader(new System.IO.StreamReader(stream)))
                    {
                        var serializer = Newtonsoft.Json.JsonSerializer.CreateDefault();
                        taskOrders = serializer.Deserialize <List <DTO.TaskOrderImportDTO> >(jReader);
                    }
            }

            //var total = taskOrders.Count() + taskOrders.SelectMany(a => a.Activities.SelectMany(aa => aa.Activities).Select(x => 1)).Sum(x => x) +
            Console.WriteLine("Total task orders: " + taskOrders.Count());
            Console.WriteLine("Total activities: " + taskOrders.SelectMany(a => a.Activities.Select(x => 1)).Sum());
            Console.WriteLine("Total activity projects: " + taskOrders.SelectMany(a => a.Activities.SelectMany(aa => aa.Activities.Select(x => 1))).Sum());
        }
示例#9
0
        public static async void TrovaUltimoSolMarte()
        {
            int  ultimoconosciuto = Int32.Parse(LocalStorageUtility.RitornaStringa("ultimoconosciuto"));
            bool ripeti           = true;

            while (ripeti)
            {
                using (var httpClient = new System.Net.Http.HttpClient())
                {
                    ultimoconosciuto++;
                    string url = $"https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?api_key={APIKEY}&sol={ultimoconosciuto}";

                    var stream = await httpClient.GetStreamAsync(url);

                    StreamReader reader     = new StreamReader(stream);
                    string       jsonString = reader.ReadToEnd();

                    JMars1 jm = JMars1.FromJson(jsonString);
                    if (ripeti = jm.Photos.Count > 1)
                    {
                        LocalStorageUtility.SetStringa(ultimoconosciuto.ToString(), "ultimoconosciuto");
                    }
                }
            }
        }
        public async Task <IActionResult> File(string l = "https://www.vvvamersfoort.nl/uploads/cache/extra_small/uploads/media/59fc1b3e41b99/amersfoort31.jpg")
        {
            var    httpClient = new System.Net.Http.HttpClient();
            string location   = httpClient.GetType().Assembly.CodeBase;
            var    data       = await httpClient.GetStreamAsync(l);

            return(new FileStreamResult(data, "image/jpg"));
        }
示例#11
0
        /// <summary>
        /// attempts to get a texture for the image
        /// - first it will check the href for a png file name. If it finds one it will load it with the ContentManager passed in
        /// - next it will see if the href is a url and if so it will load it
        /// - next it checks for an embedded, base64 image. It will load that if it finds one
        /// </summary>
        /// <returns>The texture.</returns>
        /// <param name="content">Content.</param>
        public Texture2D GetTexture(NezContentManager content)
        {
            if (_didAttemptTextureLoad || _texture != null)
            {
                return(_texture);
            }

            // check for a url
            if (Href.StartsWith("http"))
            {
#if USE_HTTPCLIENT
                using (var client = new System.Net.Http.HttpClient())
                {
                    var stream = client.GetStreamAsync(Href).Result;
                    _texture = Texture2D.FromStream(Core.GraphicsDevice, stream);
                }
#else
                throw new Exception("Found a texture in an SVG file but the USE_HTTPCLIENT build define is not set and/or HTTP Client is not referenced");
#endif
            }

            // see if we have a path to a png files in the href
            else if (Href.EndsWith("png"))
            {
                // check for existance before attempting to load! We are a PCL so we cant so we'll catch the Exception instead
                try
                {
                    if (content != null)
                    {
                        _texture = content.Load <Texture2D>(Href);
                    }
                }
                catch (ContentLoadException)
                {
                    Debug.Error("Could not load SvgImage from href: {0}", Href);
                }
            }

            // attempt to parse the base64 string if it is embedded in the href
            else if (Href.StartsWith("data:"))
            {
                var startIndex    = Href.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;
                var imageContents = Href.Substring(startIndex);
                var bytes         = Convert.FromBase64String(imageContents);

                using (var m = new MemoryStream())
                {
                    m.Write(bytes, 0, bytes.Length);
                    m.Seek(0, SeekOrigin.Begin);

                    _texture = Texture2D.FromStream(Core.GraphicsDevice, m);
                }
            }

            _didAttemptTextureLoad = true;
            return(_texture);
        }
示例#12
0
        public async Task <SourceRepository> FetchAllFiles(BuildConfig config)
        {
            var result = new SourceRepository();



            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) {
                using (var stream = await client.GetStreamAsync(config.SourceUrl)) {
                    using (var fs = File.OpenWrite(zipFile)) {
                        await stream.CopyToAsync(fs);
                    }
                }
            }

            List <ISourceItem> files = result.Files;

            result.LatestVersion = HashService.Instance.ComputeHash(zipFile);

            using (ZipFile zip = new ZipFile(zipFile)) {
                foreach (ZipEntry entry in zip)
                {
                    if (entry.IsDirectory)
                    {
                        continue;
                    }
                    using (var s = zip.GetInputStream(entry)) {
                        string   filePath = zipFolder + "\\" + entry.Name;
                        FileInfo fi       = new FileInfo(filePath);
                        if (!fi.Directory.Exists)
                        {
                            fi.Directory.Create();
                        }
                        using (FileStream fs = fi.OpenWrite()) {
                            await fs.CopyToAsync(s);
                        }

                        string fileName = System.IO.Path.GetFileName(filePath);

                        ZipSourceItem file = new ZipSourceItem {
                            Url         = filePath,
                            Name        = System.IO.Path.GetFileName(filePath),
                            Folder      = entry.Name.Substring(0, entry.Name.Length - fileName.Length),
                            IsDirectory = false
                        };
                        files.Add(file);
                    }
                }
            }


            Parallel.ForEach(files, file => {
                ((ZipSourceItem)file).Version = HashService.Instance.ComputeHash(file.Url);
            });

            return(result);
        }
示例#13
0
        public override async Task <Stream> ExecuteAsync()
        {
            Busy();

            var client = new System.Net.Http.HttpClient();
            var stream = await client.GetStreamAsync(secure? "https://www.xamarin.com" : WisdomUrl);

            Done();
            return(stream);
        }
        private async Task LoadContentStream(System.Net.Http.HttpClient httpClient)
        {
            if (String.IsNullOrEmpty(ObjectURL) == false)
            {
                ContentStream = await httpClient.GetStreamAsync(ObjectURL);

                var track = new ATL.Track(ContentStream, AudioCodec.MimeType);
                Duration = new TimeSpan(0, 0, track.Duration);
                ContentStreamLoaded?.Invoke(this, EventArgs.Empty);
            }
        }
示例#15
0
 public async static Task <string> GetHtmlSource(string url)
 {
     System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
     using (Stream stream = await httpClient.GetStreamAsync(url))
     {
         using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
         {
             return(await sr.ReadToEndAsync());
         }
     }
 }
示例#16
0
        public async Task<IActionResult> File(string l = "https://www.vvvamersfoort.nl/uploads/cache/medium/uploads/media/5d5d31417914d/dsc-3471.jpg")
        {
            var httpClient = new System.Net.Http.HttpClient();
            string location = httpClient.GetType().Assembly.CodeBase; 

            System.Console.ForegroundColor = ConsoleColor.Red;
            System.Console.WriteLine($"System.Net.Http.HttpClient: {location}");
            System.Console.ResetColor();

            var data = await httpClient.GetStreamAsync(l);
            return new FileStreamResult(data, "image/jpg");
        }
示例#17
0
 public async Task <SKBitmap> GetAsync(string url)
 {
     using (var response = await client.GetStreamAsync(url))
     {
         var bitmap = SKBitmap.Decode(response);
         if (bitmap == null)
         {
             throw new Exception("Failed to decode image");
         }
         return(bitmap);
     }
 }
示例#18
0
        public static async System.Threading.Tasks.Task <String> GetIPsasString(Uri url)
        {
            String _result;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            using (var stream = await client.GetStreamAsync(url))
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                _result = reader.ReadToEnd();
            }
            return(_result);
        }
示例#19
0
        public static async Task <Bitmap> GetBitmapDrawable(string url)
        {
            try {
                var stream = await ImageHttpClient.GetStreamAsync(url);

                return(BitmapFactory.DecodeStream(stream));
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
示例#20
0
        private IEnumerable <PackageIdentity> CreatePackageIdentityFromNupkgPath()
        {
            PackageIdentity identity = null;

            try
            {
                // Example: install-package https://az320820.vo.msecnd.net/packages/microsoft.aspnet.mvc.4.0.20505.nupkg
                if (_isHttp)
                {
                    identity = ParsePackageIdentityFromNupkgPath(Id, @"/");
                    if (identity != null)
                    {
                        Directory.CreateDirectory(Source);
                        var downloadPath = Path.Combine(Source, identity + PackagingCoreConstants.NupkgExtension);

                        using (var client = new System.Net.Http.HttpClient())
                        {
                            NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
                            {
                                using (var downloadStream = await client.GetStreamAsync(Id))
                                {
                                    using (var targetPackageStream = new FileStream(downloadPath, FileMode.Create, FileAccess.Write))
                                    {
                                        await downloadStream.CopyToAsync(targetPackageStream);
                                    }
                                }
                            });
                        }
                    }
                }
                else
                {
                    // Example: install-package c:\temp\packages\jQuery.1.10.2.nupkg
                    identity = ParsePackageIdentityFromNupkgPath(Id, @"\");
                }

                // Set _allowPrerelease to true if identity parsed is prerelease version.
                if (identity != null &&
                    identity.Version != null &&
                    identity.Version.IsPrerelease)
                {
                    _allowPrerelease = true;
                }
            }
            catch (Exception ex)
            {
                Log(MessageLevel.Error, Resources.Cmdlet_FailToParsePackages, Id, ex.Message);
            }

            return(new List <PackageIdentity> {
                identity
            });
        }
        private async void GetTramsAsync()
        {
            Collection <TramInfo> unsortedTrams = new Collection <TramInfo>();

            Trams.Clear();
            var httpClient = new System.Net.Http.HttpClient();
            var stream     = await httpClient.GetStreamAsync(String.Format("http://tramtracker.com/Controllers/GetNextPredictionsForStop.ashx?stopNo={0}&routeNo=0&isLowFloor=false", tramStopNo.ToString()));

            var    reader     = new StreamReader(stream);
            String jsonString = reader.ReadToEnd();

            var rootObject = JsonObject.Parse(jsonString);
            var trams      = rootObject.GetNamedArray("responseObject");

            foreach (JsonValue jsonTram in trams)
            {
                JsonObject jsonTramObject = jsonTram.GetObject();
                String     routeNumber    = jsonTramObject.GetNamedString("RouteNo");
                String     destination    = jsonTramObject.GetNamedString("Destination");

                String dateTimeString = jsonTramObject.GetNamedString("PredictedArrivalDateTime");

                Regex regex      = new Regex(@"^/Date\(([\d]+).*\)/$");
                Match regexMatch = regex.Match(dateTimeString);

                DateTime tramArrivalTime = new DateTime(1970, 1, 1, 0, 0, 0);

                if (regexMatch.Success)
                {
                    if (regexMatch.Groups.Count > 1)
                    {
                        long epochSeconds = Convert.ToInt64(regexMatch.Groups[1].Value);
                        tramArrivalTime = tramArrivalTime.AddMilliseconds(epochSeconds).ToLocalTime();
                    }
                }

                TramInfo tramInfo = new TramInfo(routeNumber, destination, tramArrivalTime);

                if (tramInfo.ArrivalTime.Subtract(DateTime.Now).TotalMinutes <= 120)
                {
                    unsortedTrams.Add(tramInfo);
                }
            }

            var tramlist = from tram in unsortedTrams
                           orderby tram.ArrivalTime
                           select tram;

            Trams = new ObservableCollection <TramInfo>(tramlist);

            tramsListView.ItemsSource = Trams;
            //tramsCollectionViewSource.Source = Trams;
        }
示例#22
0
        public static async System.Threading.Tasks.Task <System.Xml.XmlDocument> GetIPsasXmlDocument(Uri url)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            XmlDocument doc = new XmlDocument();

            using (var stream = await client.GetStreamAsync(url))
            {
                doc.Load(stream);
            }
            return(doc);
        }
示例#23
0
        public async System.Threading.Tasks.Task <System.Xml.XmlDocument> GetIPs(Uri url)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            //,downloadData={base_0:{url:"https://download.microsoft.com/download/0/1/8/018E208D-54F8-44CD-AA26-CD7BC9524A8C/PublicIPs_20160418.xml",id:41653,oldid:"9d8be98c-9d86-4068-8a88-51bb2e0d1ca6"}}
            XmlDocument doc = new XmlDocument();

            using (var stream = await client.GetStreamAsync(url))
            {
                doc.Load(stream);
            }
            return(doc);
        }
示例#24
0
        public async void OpenRemote()
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var stream = await client.GetStreamAsync("http://www.adobe.com/content/dam/Adobe/en/accessibility/products/acrobat/pdfs/acrobat-x-accessible-pdf-from-word.pdf");

            var memStream = new MemoryStream();
            await stream.CopyToAsync(memStream);

            memStream.Position = 0;
            PdfDocument pdfDoc = await PdfDocument.LoadFromStreamAsync(memStream.AsRandomAccessStream());

            Load(pdfDoc);
        }
示例#25
0
        private async Task <string> FetchAsync(string url)
        {
            string jsonString;

            using (var httpClient = new System.Net.Http.HttpClient()) {
                var stream = await httpClient.GetStreamAsync(url);

                StreamReader reader = new StreamReader(stream);
                jsonString = reader.ReadToEnd();
            }

            return(jsonString);
        }
示例#26
0
        public async Task<List<ISourceItem>> FetchAllFiles(BuildConfig config)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) {
                using (var stream = await client.GetStreamAsync(config.SourceUrl)) {
                    using (var fs = File.OpenWrite(zipFile)) {
                        await stream.CopyToAsync(fs);
                    }
                }
            }

            List<ISourceItem> files = new List<ISourceItem>();

            using (ZipFile zip = new ZipFile(zipFile)) {
                foreach (ZipEntry entry in zip)
                {
                    if (entry.IsDirectory)
                        continue;
                    using (var s = zip.GetInputStream(entry)) {
                        string filePath = zipFolder + "\\" + entry.Name;
                        FileInfo fi = new FileInfo(filePath);
                        if (!fi.Directory.Exists)
                        {
                            fi.Directory.Create();
                        }
                        using (FileStream fs = fi.OpenWrite()) {
                            await fs.CopyToAsync(s);
                        }

                        string fileName = System.IO.Path.GetFileName(filePath);

                        ZipSourceItem file = new ZipSourceItem { 
                            Url = filePath,
                            Name = System.IO.Path.GetFileName(filePath),
                            Folder = entry.Name.Substring(0,entry.Name.Length-fileName.Length),
                            IsDirectory = false
                        };
                        files.Add(file);
                    }                    
                }
            }

            var md5 = System.Security.Cryptography.MD5.Create();

            Parallel.ForEach(files, file => {
                ((ZipSourceItem)file).Version = Convert.ToBase64String(md5.ComputeHash(File.ReadAllBytes(file.Url)));
            });

            return files;
        }
示例#27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Button button = FindViewById <Button> (Resource.Id.button1);

            button.Click += async delegate {
                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(new NativeMessageHandler());
                var stream = await client.GetStreamAsync(MainActivity.WisdomUrl);

                await new NetHttp(this).HttpSample(new NativeMessageHandler());
            };
        }
示例#28
0
        public static Stream OpenStream(Uri uri)
        {
#if CORECLR
            using (var client = new System.Net.Http.HttpClient())
            {
                var task = client.GetStreamAsync(uri);
                return(task.Result);
            }
#else
            HttpWebRequest  request    = WebRequest.Create(uri) as HttpWebRequest;
            var             asynResult = request.BeginGetResponse(null, null);
            HttpWebResponse response   = request.EndGetResponse(asynResult) as HttpWebResponse;
            return(response.GetResponseStream());
#endif
        }
示例#29
0
        // In.Net Core 1.0 and.Net Standard 1.3 SelectSingleNode is an extenstion method
        // To make it available again: PackageReference Include = "System.Xml.XPath.XmlDocument"
        //public static System.Xml.XmlNode SelectSingleNode(this XmlDocument doc, string xpath, XmlNamespaceManager ns)
        //{
        //    return null;
        //}

        public static void Load(this XmlDocument doc, string url)
        {
            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                httpClient.DefaultRequestHeaders.UserAgent.Add(
                    new System.Net.Http.Headers.ProductInfoHeaderValue("MyClient", "1.0")
                    );

                System.IO.Stream res = System.Threading.Tasks.Task.Run(
                    () => httpClient.GetStreamAsync(url)
                    ).Result;

                doc.Load(res);
            } // End Using
        }     // End Sub Load
        private async Task <List <Interaction> > PostUserResponse(string userResponse, int tempInteractionCounter)
        {
            //FAKE SENDING RESPONSE TO API
            ///.....
            ///END

            ///Handle the received interaction
            await ChatWindow.ScrollToAsync(0, ChatBox.Height, true);

            List <Interaction> interactions = new List <Interaction>();

            switch (tempInteractionCounter)
            {
            case 0:
                interactions.Add(new Interaction()
                {
                    SpokenWord = "Mine too!"
                });
                interactions.Add(new Interaction()
                {
                    SpokenWord = "Do you like pizza?"
                });
                break;

            case 1:
                await Task.Run(async() =>
                {
                    System.Net.Http.HttpClient client   = new System.Net.Http.HttpClient();
                    client.MaxResponseContentBufferSize = 256000;
                    Stream stream  = await client.GetStreamAsync("https://homepages.cae.wisc.edu/~ece533/images/boat.png");
                    byte[] testImg = GetImageStreamAsBytes(stream);
                    interactions.Add(new Interaction()
                    {
                        image = testImg, showMessage = true
                    });
                });

                break;

            default:
                interactions.Add(new Interaction()
                {
                    SpokenWord = "Pyxus says something intelligent", showMessage = true
                });
                break;
            }
            return(interactions);
        }
示例#31
0
        public async Task <Stream> OpenZipStream(string mainUrl)
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                var matches    = Regex.Match(mainUrl, "https://github\\.com/([\\w-]*)/([\\w-]*)");
                var username   = matches.Groups[1].Value;
                var repository = matches.Groups[2].Value;
                var branch     = "master";

                var url = $"https://github.com/{username}/{repository}/archive/{branch}.zip";

                var openZipStream = await client.GetStreamAsync(url);

                return(openZipStream);
            }
        }
示例#32
0
        async Task <System.IO.Stream> GetExportAsync(System.Net.Http.HttpClient web, Guid requestID, string authToken, string format)
        {
            web.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);

            var stream = await web.GetStreamAsync(WebConfigurationManager.AppSettings["ServiceUrl"] + "response/GetEnhancedEventLog?requestID=" + requestID.ToString("D") + "&format=" + format + "&download=true");

            var contentDisposition = new System.Net.Mime.ContentDisposition
            {
                FileName = "eventlog." + format,
                Inline   = false
            };

            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

            return(stream);
        }
示例#33
0
文件: SvgImage.cs 项目: prime31/Nez
		/// <summary>
		/// attempts to get a texture for the image
		/// - first it will check the href for a png file name. If it finds one it will load it with the ContentManager passed in
		/// - next it will see if the href is a url and if so it will load it
		/// - next it checks for an embedded, base64 image. It will load that if it finds one
		/// </summary>
		/// <returns>The texture.</returns>
		/// <param name="content">Content.</param>
		public Texture2D getTexture( NezContentManager content )
		{
			if( _didAttemptTextureLoad || _texture != null )
				return _texture;

			// check for a url
			if( href.StartsWith( "http" ) )
			{
				using( var client = new System.Net.Http.HttpClient() )
				{
					var stream = client.GetStreamAsync( href ).Result;
					_texture = Texture2D.FromStream( Core.graphicsDevice, stream );
				}
			}
			// see if we have a path to a png files in the href
			else if( href.EndsWith( "png" ) )
			{
				// check for existance before attempting to load! We are a PCL so we cant so we'll catch the Exception instead
				try
				{
					if( content != null )
						_texture = content.Load<Texture2D>( href );
				}
				catch( ContentLoadException )
				{
					Debug.error( "Could not load SvgImage from href: {0}", href );
				}
			}
			// attempt to parse the base64 string if it is embedded in the href
			else if( href.StartsWith( "data:" ) )
			{
				var startIndex = href.IndexOf( "base64,", StringComparison.OrdinalIgnoreCase ) + 7;
				var imageContents = href.Substring( startIndex );
				var bytes = Convert.FromBase64String( imageContents );

				using( var m = new MemoryStream() )
				{
					m.Write( bytes, 0, bytes.Length );
					m.Seek( 0, SeekOrigin.Begin );

					_texture = Texture2D.FromStream( Core.graphicsDevice, m );
				}
			}

			_didAttemptTextureLoad = true;
			return _texture;
		}
示例#34
0
        /// <summary>
        /// Look for the INupkg instance in the cache first. If it's in the cache, return it.
        /// Otherwise, download the package from the storage service and store it into the cache.
        /// </summary>
        public static async Task<INupkg> GetPackageFromCacheOrDownloadIt(
            Package package,
            IPackageCacheService cacheService,
            IPackageFileService packageFileService)
        {
            Debug.Assert(package != null);
            Debug.Assert(cacheService != null);
            Debug.Assert(packageFileService != null);

            string cacheKey = CreateCacheKey(package.PackageRegistration.Id, package.Version);
            byte[] buffer = cacheService.GetBytes(cacheKey);
            if (buffer == null)
            {
                // In the past, some very old packages can specify an external package binary not hosted at nuget.org.
                // We no longer allow that today.
                if (!String.IsNullOrEmpty(package.ExternalPackageUrl))
                {
                    var httpClient = new HttpClient();
                    using (var responseStream = await httpClient.GetStreamAsync(package.ExternalPackageUrl))
                    {
                        buffer = responseStream.ReadAllBytes();
                    }
                }
                else
                {
                    using (Stream stream = await packageFileService.DownloadPackageFileAsync(package))
                    {
                        if (stream == null)
                        {
                            throw new InvalidOperationException("Couldn't download the package from the storage.");
                        }

                        buffer = stream.ReadAllBytes();
                    }
                }

                cacheService.SetBytes(cacheKey, buffer);
            }

            return new Nupkg(new MemoryStream(buffer), leaveOpen: false);
        }
示例#35
0
        /// <summary>
        /// Sets the attachment.
        /// </summary>
        /// <remarks>
        /// Sets the attachment with the given name.  The <see cref="Couchbase.Lite.Attachment"/> data will be 
        /// written to the <see cref="Couchbase.Lite.Database"/> when the <see cref="Couchbase.Lite.Revision"/> is saved.
        /// </remarks>
        /// <param name="name">Name.</param>
        /// <param name="contentType">Content type.</param>
        /// <param name="contentUrl">Content URL.</param>
        public void SetAttachment(String name, String contentType, Uri contentUrl) {
            try
            {
                var http = new System.Net.Http.HttpClient();
				using (var inputStream = http.GetStreamAsync(contentUrl).Result) {	                
	                var length = inputStream.Length;
	                var inputBytes = inputStream.ReadAllBytes();
					#if !PORTABLE
	                inputStream.Close();
					#endif

					SetAttachment(name, contentType, inputBytes);
				}
            }
            catch (IOException e)
            {
                Log.E(Database.Tag, "Error opening stream for url: " + contentUrl);
                throw new RuntimeException(e);
            }
        }
		public async Task InitiateHttp ()
		{
			var client = new System.Net.Http.HttpClient (new NativeMessageHandler ());
			RenderStream (await client.GetStreamAsync (WisdomUrl));
		}
		public override void Start()
		{
			base.Start();


			IRelativePanel panel = Platform.Current.Create<IRelativePanel>();
			panel.BackgroundColor = new Color (255, 255, 255, 255);

			IGrid grdMenu = Constantes.CrearMenuVacio();
			panel.Add(grdMenu, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.TopWith);

			IImageButton imgHome = Platform.Current.Create<IImageButton>();
			imgHome.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images/app-15.png"));
			imgHome.Click += cmdHome_Click;
			grdMenu.SetContent(1, 0, imgHome);

			IImageButton imgRegionales = Platform.Current.Create<IImageButton>();
			imgRegionales.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images-old/icon-11.png"));
			imgRegionales.Click += cmdEstaciones_Click;
			grdMenu.SetContent(1, 1, imgRegionales);

			IImageButton cmdProgramas = Platform.Current.Create<IImageButton>();
			cmdProgramas.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images-old/icon-08.png"));
			//cmdProgramas.Click += (object sender, EventArgs e) => new ProgramasController().Start();
			grdMenu.SetContent(1, 2, cmdProgramas);

			IImageButton imgVirtuales = Platform.Current.Create<IImageButton>();
			imgVirtuales.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images-old/icon-09.png"));
			imgVirtuales.Click += cmdVirtuales_Click;
			grdMenu.SetContent(1, 3, imgVirtuales);

			ILabel lblTitulo = Constantes.CrearTitulo("Archivo de programa", new Color(255, 255, 143, 0));
			panel.Add(lblTitulo, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, grdMenu);

			if (Platform.Current.Page.Width > 250)
			{
				IImage imgLogo = Platform.Current.Create<IImage> ();
				imgLogo.LoadFromUrl (new Uri ("http://radioudg.okhosting.com/images-old/icon2--14.png"));
				imgLogo.Width = Platform.Current.Page.Width / 6;
				imgLogo.Height = lblTitulo.Height;
				imgLogo.Margin = new Thickness (0, 0, 10, 0);
				panel.Add(imgLogo, RelativePanelHorizontalContraint.RightWith, RelativePanelVerticalContraint.TopWith, lblTitulo);
			}

			System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
			var xmlStream = client.GetStreamAsync(Show.PodcastUri).Result;

			System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlStream);

			IList<Episode> episodios = new List<Episode>();

			//extraer episodios del xml
			while (reader.ReadToFollowing ("item")) 
			{
				reader.ReadToFollowing ("title");
				Episode episodio = new Episode ();
				episodio.Name = reader.ReadElementContentAsString ();
				reader.ReadToFollowing ("link");
				string mp3string = reader.ReadElementContentAsString();
				episodio.EpisodeUri = new Uri (mp3string);
				episodio.ImagenUri = Show.LogoUri;
				episodio.Description = Show.Name;

				episodios.Add (episodio);
			}

			reader.Dispose();
			xmlStream.Dispose();
			client.Dispose();

			IControl referencia = lblTitulo;

			foreach (Episode episodio in episodios)
			{
				IImageButton imgLogo = Platform.Current.Create<IImageButton>();
				imgLogo.LoadFromUrl(Show.LogoUri);
				imgLogo.Click += Episode_Click;
				imgLogo.Tag = episodio;
				imgLogo.Width = Constantes.AnchoIconos;
				imgLogo.Height = Constantes.AnchoIconos;
				
				//set margin for first iteration
				if (referencia == lblTitulo)
				{
					imgLogo.Margin = new Thickness(10, 10, 10, 10);
				}
				else
				{
					imgLogo.Margin = new Thickness(0, 10, 10, 10);
				}

				panel.Add(imgLogo, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, referencia);

				referencia = imgLogo;
				
				ILabelButton lblNombre = Platform.Current.Create<ILabelButton> ();
				lblNombre.Click += Episode_Click;
				lblNombre.Text = episodio.Name;
				lblNombre.Tag = episodio;
				lblNombre.Bold = true;
				lblNombre.FontSize = Constantes.FontSize2;
				lblNombre.FontColor = Constantes.FontColor2;
				lblNombre.Width = Platform.Current.Page.Width - (Constantes.AnchoIconos * 3) + 10;
				panel.Add (lblNombre, RelativePanelHorizontalContraint.RightOf, RelativePanelVerticalContraint.TopWith, imgLogo);

				IImageButton imgPlay = Platform.Current.Create<IImageButton>();
				imgPlay.LoadFromUrl(new Uri ("http://radioudg.okhosting.com/images-old/icon-20.png"));
				imgPlay.Click += Episode_Click;
				imgPlay.Tag = episodio;
				imgPlay.Width = Constantes.AnchoIconos;
				imgPlay.Height = Constantes.AnchoIconos;

				panel.Add(imgPlay, RelativePanelHorizontalContraint.RightOf, RelativePanelVerticalContraint.TopWith, lblNombre);
			}

			Platform.Current.Page.Title = "Selecciona un episodio";
			Platform.Current.Page.Content = panel;
		}
        public static List<Station> LeerEstaciones()
        {
            List<Station> estaciones = new List<Station>();
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var xmlStream = client.GetStreamAsync("http://radioudg.okhosting.com/virtuales.xml").Result;
            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlStream);

            //extraer episodios del xml
            while (reader.ReadToFollowing("estacion"))
            {
                Station estacion = new Station();

                reader.ReadToFollowing("imagen");
                estacion.WebSiteUri = new Uri(reader.ReadElementContentAsString());

                reader.ReadToFollowing("streaming");
                estacion.StramingUri = new Uri(reader.ReadElementContentAsString());
                
                reader.ReadToFollowing("nombre");
                estacion.Name = reader.ReadElementContentAsString();

                reader.ReadToFollowing("descripcion");
                estacion.Description = reader.ReadElementContentAsString();

                estaciones.Add(estacion);
            }

			reader.Dispose();
			xmlStream.Dispose();
			client.Dispose();

			return estaciones;
        }