private async Task <string> FetchMedicationAsync(string url) { //Create HTTP request using the URL System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url)); request.ContentType = "application/json"; request.Method = "GET"; //Send the request ot the server and wait for the response //TODO: Add exception handling to web queries and Json parsing using (System.Net.WebResponse response = await request.GetResponseAsync()) { //Get a stream representation of the HTTP web response using (System.IO.Stream stream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { string json = await Task.Run(() => streamReader.ReadToEnd()); //string json = await Task.Run(() => JsonConvert.ToString(streamText)); Console.Out.WriteLine("Result: {0}", json); //Return the JSON document return(json); } } } }
public static async System.Threading.Tasks.Task <Boolean> FetchCompanyHistoryAsync(Models.HistoryU obj) { Uri u = new Uri(url1 + "insertHistoryC?Search=" + obj.Wyszukiwanie + "&Description=" + obj.Description + "&Companyid=" + obj.User + "&Expoid=" + obj.Expo); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(u); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); if (Boolean.Parse(jsonDoc["saved"].ToString()) == true) { return(true); } else { return(false); } } } return(false); }
public static async System.Threading.Tasks.Task <Models.Company> FetchCompanyAsync(string email) { // Create an HTTP web request using the URL: System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url1 + "/company?Email=" + email)); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: try { using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); // Return the JSON document: return(Droid.Modules.Parsers.Company(jsonDoc)); } } } catch (System.Net.WebException ex) { } return(null); }
public static async System.Threading.Tasks.Task <Boolean> FetchUserEditAsync(Models.User obj) { Uri u = new Uri(url1 + "EditProfileUser?Email=" + obj.Email + "&ForName=" + obj.ForName + "&SurName=" + obj.SurName + "&Phone=" + obj.Phone + "&Nationality=" + obj.Nationality); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(u); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); if (Boolean.Parse(jsonDoc["AccountChanged"].ToString()) == true) { return(true); } else if (Boolean.Parse(jsonDoc["Unactual"].ToString()) == true) { LDbConnection.InsertUser(await DbConnection.FetchUserAsync(obj.Email)); return(true); } } } return(false); }
public static async System.Threading.Tasks.Task <Boolean> FetchCompanyJoinExpoAsync(Models.Company us, Models.Expo e) { Uri u = new Uri(url1 + "insertCExpo?Expoid=" + e.Id + "&Companyid=" + us.Id); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(u); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); if (Boolean.Parse(jsonDoc["JoinedC"].ToString()) == true) { return(true); } else { return(false); } } } return(false); }
public static void GetHomePage(Action <ResponseDataJson> callback) { System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(SERVER_URL + "/AppHome/GetJson"); request.ContentType = "text/json"; request.Accept = "text/json"; request.Method = "GET"; request.GetResponseAsync().ContinueWith(t => { var isOk = false; try { var responseStream = t.Result.GetResponseStream(); var jsonStr = new System.IO.StreamReader(responseStream).ReadToEnd(); responseStream.Dispose(); isOk = true; callback.Invoke(new ResponseDataJson(ResponseCode.OK, jsonStr)); } catch (Exception e) { if (!isOk) { callback.Invoke(new ResponseDataJson(ResponseCode.Fail, null, e)); } } }); }
public async Task <bool> QueryHost(Uri InHost) { // Send GET request to host System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(InHost + TestFile); request.Method = "GET"; //Default to "not found" System.Net.HttpStatusCode response = System.Net.HttpStatusCode.NotFound; try { response = ((System.Net.HttpWebResponse) await request.GetResponseAsync()).StatusCode; } catch { Trace.WriteLine(string.Format("<!><!><!>The host: {0} is down.", InHost)); } // Push host to queue if valid if (response == System.Net.HttpStatusCode.OK) { lock (Hosts) Hosts.Enqueue(InHost); Trace.WriteLine("Added: " + InHost); return(true); } return(false); }
public static async System.Threading.Tasks.Task <Boolean> FetchCompanyEditAsync(Models.Company obj) { Uri u = new Uri(url1 + "EditProfileCompany?Email=" + obj.Email + "&CompanyName=" + obj.CompanyName + "&CompanyFullName=" + obj.CompanyFullName + "&CompanyAbout=" + obj.CompanyAbout + "&ProductsAbout=" + obj.ProductsAbout + "&Facebook=" + obj.Facebook + "&Instagram=" + obj.Instagram + "&Snapchat=" + obj.Snapchat + "&Youtube=" + obj.Youtube + "&Phone=" + obj.Phone + "&UserPhone=" + obj.UserPhone + "&ContactEmail=" + obj.ContactEmail + "&www=" + obj.www + "&Adress=" + obj.www + "&NIP=" + obj.NIP + "&Forname_And_Surname=" + obj.ForName_And_SurName); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(u); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); if (Boolean.Parse(jsonDoc["AccountChanged"].ToString()) == true) { return(true); } else if (Boolean.Parse(jsonDoc["Unactual"].ToString()) == true) { LDbConnection.InsertCompany(await DbConnection.FetchCompanyAsync(obj.Email)); return(true); } } } return(false); }
private async void RadioPoll(Object state) { string PollingUrl = "https://hive365.co.uk/streaminfo/info.php"; System.Net.HttpWebRequest WebRequest = System.Net.WebRequest.CreateHttp(PollingUrl); using (var resp = await WebRequest.GetResponseAsync()) { using (var streamreader = new System.IO.StreamReader(resp.GetResponseStream())) { dynamic JsonValue = Newtonsoft.Json.JsonConvert.DeserializeObject(await streamreader.ReadToEndAsync()); try { string SongName = JsonValue.info.artist_song; if (CurrentSong != SongName) { var MessagesToDelete = MessageClient.GetMessagesAsync().Cast <Discord.IMessage>().Where(x => x.Content.Contains("via Hive365 Radio!")); await MessageClient.DeleteMessagesAsync(await MessagesToDelete.ToList()); SendMessage_Raised("Now playing " + SongName + " on Spagbot via Hive365 Radio!", MessageClient); CurrentSong = SongName; } } catch { //RuntimeBinder exception probably :) } } } WebRequest = null; }
public static T GetWebResponse <T>(string url) { System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponseAsync().GetAwaiter().GetResult()) { using (System.IO.StreamReader readStream = new System.IO.StreamReader(response.GetResponseStream(), encode)) { string responseText = readStream.ReadToEnd(); return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseText)); } } }
public static async Task AddImageFromUrl(string url, string imageName) { System.Net.HttpWebRequest request = null; byte[] b = null; name = imageName; request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "GET"; using (var response = (System.Net.HttpWebResponse) await request.GetResponseAsync()) { if (request.HaveResponse) { if (response.StatusCode == System.Net.HttpStatusCode.OK) { System.IO.Stream receiveStream = response.GetResponseStream(); using (System.IO.BinaryReader br = new System.IO.BinaryReader(receiveStream)) { b = br.ReadBytes(500000); if (b != null) { if (!Images.ContainsKey(name)) { // hold image byte[] image = new byte[b.Length]; image = b; Images.Add(imageName, b); // Debug.WriteLine("MAP SIZE: " + getImages.Count); b = null; } } br.Dispose(); } } } } }
async Task <DTOs.Response.BootstrapResponse> scrapeFromUrl(string url) { System.Net.HttpWebRequest r = System.Net.HttpWebRequest.CreateHttp(url); var response = await r.GetResponseAsync(); try { string s = (new System.IO.StreamReader(response.GetResponseStream())).ReadToEnd(); return(Newtonsoft.Json.JsonConvert.DeserializeObject <DTOs.Response.BootstrapResponse>(s)); } catch { return(new DTOs.Response.BootstrapResponse()); } throw new NotImplementedException(); }
/// <summary> /// Helper method to work around annoying exceptions thrown by System.Net.WebRequest /// when the server returns a non-success status code /// </summary> /// <param name="req">The request to get the response from</param> /// <returns>The web response</returns> private static async Task <System.Net.HttpWebResponse> GetResponseWithoutExceptionAsync(System.Net.HttpWebRequest req) { try { return((System.Net.HttpWebResponse) await req.GetResponseAsync()); } catch (System.Net.WebException we) { var resp = we.Response as System.Net.HttpWebResponse; if (resp == null) { throw; } return(resp); } }
public static async System.Threading.Tasks.Task <System.Collections.Generic.List <Models.Expo> > FetchUserExposAsync(Models.User u) { // Create an HTTP web request using the URL: System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url1 + "UserExpos?email=" + u.Email)); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); // Return the JSON document: System.Collections.Generic.List <Models.Expo> lista = new System.Collections.Generic.List <Models.Expo>(); for (int i = 0; i != jsonDoc.Count; i++) { Models.Expo e = new Models.Expo { Name_Expo = jsonDoc[i]["Name_Expo"], Id = Int32.Parse(jsonDoc[i]["Id"].ToString()), Photo = jsonDoc[i]["Photo"], MapPhoto = jsonDoc[i]["MapPhoto"], Adres = jsonDoc[i]["Adres"], Description = jsonDoc[i]["Description"] }; var start = double.Parse(jsonDoc[i]["ExpoStartData"].ToString().Replace('/', ' ').Replace('"', ' ').Replace(')', ' ').Replace("Date(", "").Trim()); TimeSpan time = TimeSpan.FromMilliseconds(start); DateTime startdate = new DateTime(1970, 1, 1) + time; e.DataTargowStart = startdate; var end = double.Parse(jsonDoc[i]["ExpoEndData"].ToString().Replace('/', ' ').Replace('"', ' ').Replace(')', ' ').Replace("Date(", "").Trim()); TimeSpan time1 = TimeSpan.FromMilliseconds(end); DateTime enddate = new DateTime(1970, 1, 1) + time1; e.DataTargowEnd = enddate; lista.Add(e); } return(lista); } } }
public async void StartDownload() { Log.Debug("starting download: " + this); string directory = Path.GetDirectoryName(filePath.Value); Directory.CreateDirectory(directory); fileStream = new FileStream(filePath.Value, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); using (response = (System.Net.HttpWebResponse) await request.GetResponseAsync()) { using (stream = response.GetResponseStream()) { await System.Threading.Tasks.Task.Run(() => { DownloadedSize = 0; FileSize = response.ContentLength; downloadStart = DateTime.Now; // update the download-state. DownloadState = DownloadState.Downloading; StateChanged.Invoke(this, DownloadState.Downloading); while (DownloadState == DownloadState.Downloading && ((bufferBytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)) { fileStream.Write(buffer, 0, bufferBytesRead); DownloadedSize += bufferBytesRead; CurrentSize += bufferBytesRead; DownloadSpeed = CurrentSize / 1024 / (DateTime.Now - downloadStart).TotalSeconds; } }); } } fileStream.Close(); fileStream.Dispose(); if (DownloadedSize == FileSize) { Log.Debug("finished download: " + this); DownloadState = DownloadState.Completed; } DownloadSpeed = 0; StateChanged?.Invoke(this, DownloadState); }
public void MapRoute(IApplicationBuilder app) { string address = "http://localhost:5010"; app.Map("/LoadTest", builder => { builder.Run(async context => { await context.Response.WriteAsync("OK"); }); }); app.Map("/HttpClient", builder => { builder.Run(async context => { HttpClient client = new HttpClient(); var response = client.GetStringAsync("http://www.baidu.com").Result; await context.Response.WriteAsync("OK"); }); }); app.Map("/Trace", builder => { builder.Run(async context => { //System.Threading.Thread.Sleep(new Random().Next(111, 5555)); //HttpClient client = new HttpClient(); //var response = await client.GetStringAsync(address +"/Test1"); //await context.Response.WriteAsync(response); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address + "/Test1"); req.Timeout = 5000000; using (System.Net.WebResponse wr = await req.GetResponseAsync()) { await context.Response.WriteAsync("ok"); } }); }); }
public static void Main(string[] args) { Byte[] bytes = System.IO.File.ReadAllBytes(fileName); String file = Convert.ToBase64String(bytes); JsonData data = new JsonData(); data.model = "cvlizer_3_0"; data.language = "de"; data.filename = fileName; data.data = file; string json = JsonConvert.SerializeObject(data); byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(json); System.Net.HttpWebRequest req = System.Net.WebRequest.Create("https://cvlizer.joinvision.com/cvlizer/rest/v1/extract/xml/") as System.Net.HttpWebRequest; req.Method = "POST"; req.ContentType = "application/json"; req.Headers[System.Net.HttpRequestHeader.ContentLength] = jsonBytes.Length.ToString(); req.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer " + productToken; //req.Headers.Add("Authorization", "Bearer " + < Product - Token >); //req.ContentLength = jsonBytes.Length; using (System.IO.Stream post = req.GetRequestStreamAsync().Result) // todo please don't block the tread { post.Write(jsonBytes, 0, jsonBytes.Length); } string result = null; using (System.Net.HttpWebResponse resp = req.GetResponseAsync().Result as System.Net.HttpWebResponse) { System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } Console.Write(result); File.WriteAllText("cvlizer.xml", result); Console.ReadLine(); }
/// <summary> /// Main download method. /// </summary> private async void download() { dlTimer.Start(); dsTimer.Start(); // Set 'cancelDownload' to false, so that method can stop again. cancelDownload = false; req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); // check if downloaded-length!=0 and !overwrite so the user want to resume. if (dLength > 0 && !overwrite) { req.AddRange(dLength); // add range to the 'req' to change the point of start download. } isDownloading = true; using (res = (System.Net.HttpWebResponse) await req.GetResponseAsync()) { fLength = res.ContentLength + dLength; // get the total-size of the file. eSize.Invoke(null, Unkdevt.StringHelpers.GetLengthString(FileSize)); // update the total-size. eDownloadedSize.Invoke(null, Unkdevt.StringHelpers.GetLengthString(DownloadedLength)); // update the downloaded-length. dt = System.DateTime.Now; // get the current time ( point of start downloading ). using (stream = res.GetResponseStream()) { await System.Threading.Tasks.Task.Run(() => // await task so the winform don't freezing. { // update the download-state. eDownloadState.Invoke(null, "Downloading"); // while not 'cancelDownload' and file doesn't end do: while (!cancelDownload && ((bufferReader = stream.Read(buffer, 0, buffer.Length)) > 0)) { fStream.Write(buffer, 0, bufferReader); // write byte to the file on harddisk. dLength += bufferReader; // update downloaded-length value. cLength += bufferReader; // update current-downloaded-length value. } }); } } dlTimer.Stop(); dsTimer.Stop(); isDownloading = false; // eSpeed.Invoke(null, "0.0 Kb/s"); // update downloading-speed to 0.0 kb/s. eDownloadedSize.Invoke(null, Unkdevt.StringHelpers.GetLengthString(DownloadedLength)); // update downloaded-size. eDownloadState.Invoke(null, DownloadState); // update download-state. fStream.Dispose(); // free file on harddisk by dispose 'fStream'. }
public T ProcessRequest(string token, string logOn, string password, System.Net.Cookie cookie) { Uri uri = ToUrl(token); System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); wr.Credentials = new System.Net.NetworkCredential(logOn, password); wr.CookieContainer = new System.Net.CookieContainer(); if (cookie != null) { var cookiUri = cookie.Domain != null ? new Uri(cookie.Domain) : BaseUrl; wr.CookieContainer.SetCookies(uri, cookie.ToString()); } OnProcessingRequest(wr); #if !PORTABLE using (var response = wr.GetResponse()) #else using (var response = wr.GetResponseAsync().Result) #endif using (var stream = response.GetResponseStream()) { if (stream == null) { throw new InvalidOperationException("Response stream is null"); } var sr = new System.IO.StreamReader(stream); var jsonResult = sr.ReadToEnd(); var result = JsonParser.ParseJsonResult(jsonResult); if (result != null && result.CacheId != 0) { this.CacheId = result.CacheId; } var ret = new T { Result = result }; OnProcessedRequest(ret); return(ret); } }
private async Task <string> FetchMedicationAsync(string url) { //Create HTTP request using the URL System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url)); request.ContentType = "application/json"; request.Method = "GET"; //Send the request to the server and wait for the response //TODO: Add exception handling to web queries and Json parsing try { using (System.Net.WebResponse response = await request.GetResponseAsync()) { //Get a stream representation of the HTTP web response using (System.IO.Stream stream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { string json = await Task.Run(() => streamReader.ReadToEnd()); //Return the JSON string return(json); } //Use this stream to build a JSON document object: //JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream)); //Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); //Return the JSON document //return jsonDoc.ToString(); } } } catch (Exception e) { Console.Out.WriteLine("{0}. Exception caught", e); return(""); } }
public async Task <bool> QueryHost(UpdateServerEntry hostObject) { RxLogger.Logger.Instance.Write($"Attempting to contact host {hostObject.Uri.AbsoluteUri}"); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(hostObject.Uri.AbsoluteUri + TestFile); request.Method = "GET"; //Default to "not found" System.Net.HttpStatusCode response = System.Net.HttpStatusCode.NotFound; try { response = ((System.Net.HttpWebResponse) await request.GetResponseAsync()).StatusCode; } catch { hostObject.HasErrored = true; RxLogger.Logger.Instance.Write($"The host {hostObject.Uri.AbsoluteUri} seems to be offline"); } // Push host to queue if valid if (response == System.Net.HttpStatusCode.OK) { lock (Hosts) { Hosts.Enqueue(hostObject); // Only add the top 4 hosts into this list if (CurrentHostsList.Count < 4) { CurrentHostsList.Add(new UpdateServerSelectorObject(hostObject)); } } RxLogger.Logger.Instance.Write($"Added host {hostObject.Uri.AbsoluteUri} to the hosts queue"); return(true); } return(false); }
public static async System.Threading.Tasks.Task <Models.MobileLogin> FetchLoginAsync(String email, String password) { Uri u = new Uri(url1 + "Login?Email=" + email + "&Password="******"application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); return(Droid.Modules.Parsers.Login(jsonDoc)); } } return(null); }
public async Task <Client> RequestGetAsync() { this .Method("GET") //.Headers() // default headers //.Parameters() // Data/Parameters ; foreach ( KeyValuePair <Uri, ClientRequestImplementation <ImplementationRequest> > kvp in this.RequestImplementationObjects ) { Uri uri = kvp.Key; ImplementationRequest request = kvp.Value.ImplementationObject; RequestSetup(request); #if NETSTANDARD1_0 ImplementationResponse response = (ImplementationResponse)await request.GetResponseAsync(); this.ResponseImplementationObjects.Add(uri, response); #else using (System.Net.Http.HttpClient http_client = new System.Net.Http.HttpClient()) { ImplementationResponse response = await http_client.SendAsync(request); this.ResponseImplementationObjects.Add(uri, response); } #endif } return(this); }
public static async System.Threading.Tasks.Task <System.Collections.Generic.List <Models.HistoryU> > FetchHistory(Models.Company u) { // Create an HTTP web request using the URL: System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url1 + "History?email=" + u.Email)); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); // Return the JSON document: System.Collections.Generic.List <Models.HistoryU> lista = new System.Collections.Generic.List <Models.HistoryU>(); for (int i = 0; i != jsonDoc.Count; i++) { Models.HistoryU h = new Models.HistoryU { ID = Int32.Parse(jsonDoc[i]["ID"].ToString()), Description = jsonDoc[i]["Description"], Wyszukiwanie = jsonDoc[i]["Wyszukiwanie"], User = Int32.Parse(jsonDoc[i]["User"].ToString()), Expo = Int32.Parse(jsonDoc[i]["Expo"].ToString()) }; lista.Add(h); } return(lista); } } }
public void RequestWork(object state) { try { #if NETFX_CORE System.Net.HttpWebRequest req = System.Net.HttpWebRequest.CreateHttp(new Uri(_Url)); #else #if (UNITY_5 || UNITY_5_3_OR_NEWER) System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(new Uri(_Url)) as System.Net.HttpWebRequest; #else System.Net.HttpWebRequest req = new System.Net.HttpWebRequest(new Uri(_Url)); #endif req.KeepAlive = false; #endif try { lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } _InnerReq = req; } #if !NETFX_CORE req.Timeout = int.MaxValue; req.ReadWriteTimeout = int.MaxValue; #if !HTTP_REQ_DONOT_ABORT if (_Timeout > 0) { req.Timeout = _Timeout; req.ReadWriteTimeout = _Timeout; } #endif #endif if (_Headers != null) { foreach (var kvp in _Headers.Data) { var key = kvp.Key; var val = (kvp.Value ?? "").ToString(); if (key.IndexOfAny(new[] { '\r', '\n', ':', }) >= 0) { continue; // it is dangerous, may be attacking. } if (val.IndexOfAny(new[] { '\r', '\n', }) >= 0) { continue; // it is dangerous, may be attacking. } else { req.Headers[key] = val; } } } if (_RangeEnabled) { long filepos = 0; if (_Dest != null) { using (var stream = PlatExt.PlatDependant.OpenRead(_Dest)) { if (stream != null) { try { filepos = stream.Length; } catch (Exception e) { if (GLog.IsLogErrorEnabled) { GLog.LogException(e); } } } } } if (filepos <= 0) { if (_DestStream != null) { try { if (_DestStream.CanSeek) { filepos = _DestStream.Length; } } catch (Exception e) { if (GLog.IsLogErrorEnabled) { GLog.LogException(e); } } } } if (filepos > 0) { if (filepos > int.MaxValue) { _RangeEnabled = false; } else { req.AddRange((int)filepos); } } else { _RangeEnabled = false; } } if (_Data != null && (_Data.Count > 0 || _Data.Encoded != null)) { req.Method = "POST"; var data = _Data.Encoded; if (data == null) { req.ContentType = _Data.ContentType; data = _Data.Encode(); } else { req.ContentType = "application/octet-stream"; } #if NETFX_CORE var tstream = req.GetRequestStreamAsync(); if (_Timeout > 0) { if (!tstream.Wait(_Timeout)) { throw new TimeoutException(); } } else { tstream.Wait(); } var stream = tstream.Result; #else req.ContentLength = data.Length; var stream = req.GetRequestStream(); #endif lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } } if (stream != null) { #if NETFX_CORE if (_Timeout > 0) { stream.WriteTimeout = _Timeout; } else { stream.WriteTimeout = int.MaxValue; } #endif try { stream.Write(data, 0, data.Length); stream.Flush(); } finally { stream.Dispose(); } } } else { } lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } } #if NETFX_CORE var tresp = req.GetResponseAsync(); if (_Timeout > 0) { if (!tresp.Wait(_Timeout)) { throw new TimeoutException(); } } else { tresp.Wait(); } var resp = tresp.Result; #else var resp = req.GetResponse(); #endif lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } } if (resp != null) { try { _Total = (ulong)resp.ContentLength; } catch { } try { _RespHeaders = new HttpRequestData(); foreach (var key in resp.Headers.AllKeys) { _RespHeaders.Add(key, resp.Headers[key]); } if (_RangeEnabled) { bool rangeRespFound = false; foreach (var key in resp.Headers.AllKeys) { if (key.ToLower() == "content-range") { rangeRespFound = true; } } if (!rangeRespFound) { _RangeEnabled = false; } } var stream = resp.GetResponseStream(); lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } } if (stream != null) { #if NETFX_CORE if (_Timeout > 0) { stream.ReadTimeout = _Timeout; } else { stream.ReadTimeout = int.MaxValue; } #endif Stream streamd = null; try { byte[] buffer = new byte[1024 * 1024]; ulong totalcnt = 0; int readcnt = 0; bool mem = false; if (_Dest != null) { if (_RangeEnabled) { streamd = Capstones.PlatExt.PlatDependant.OpenAppend(_Dest); totalcnt = (ulong)streamd.Length; } else { streamd = Capstones.PlatExt.PlatDependant.OpenWrite(_Dest); } #if HTTP_REQ_DONOT_ABORT if (streamd != null) { _CloseList.Add(streamd); } #endif } if (streamd == null) { if (_DestStream != null) { if (_RangeEnabled) { _DestStream.Seek(0, SeekOrigin.End); totalcnt = (ulong)_DestStream.Length; } streamd = _DestStream; } else { mem = true; streamd = new MemoryStream(); #if HTTP_REQ_DONOT_ABORT _CloseList.Add(streamd); #endif } } if (_Total > 0) { _Total += totalcnt; } do { lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } } try { readcnt = 0; readcnt = stream.Read(buffer, 0, 1024 * 1024); if (readcnt <= 0) { stream.ReadByte(); // when it is closed, we need read to raise exception. break; } streamd.Write(buffer, 0, readcnt); streamd.Flush(); } catch (TimeoutException te) { if (GLog.IsLogErrorEnabled) { GLog.LogException(te); } _Error = "timedout"; } catch (System.Net.WebException we) { if (GLog.IsLogErrorEnabled) { GLog.LogException(we); } #if NETFX_CORE if (we.Status.ToString() == "Timeout") #else if (we.Status == System.Net.WebExceptionStatus.Timeout) #endif { _Error = "timedout"; } else { _Error = "Request Error (Exception):\n" + we.ToString(); } } catch (Exception e) { if (GLog.IsLogErrorEnabled) { GLog.LogException(e); } _Error = "Request Error (Exception):\n" + e.ToString(); } lock (_CloseLock) { if (_Closed) { #if !HTTP_REQ_DONOT_ABORT req.Abort(); #endif if (_Status != RequestStatus.Finished) { _Error = "Request Error (Cancelled)"; _Status = RequestStatus.Finished; } return; } } totalcnt += (ulong)readcnt; _Length = totalcnt; //Capstones.PlatExt.PlatDependant.LogInfo(readcnt); } while (readcnt > 0); if (mem) { _Resp = ((MemoryStream)streamd).ToArray(); } } finally { stream.Dispose(); if (streamd != null) { if (streamd != _DestStream) { streamd.Dispose(); } } } } } finally { #if NETFX_CORE resp.Dispose(); #else resp.Close(); #endif } } } catch (TimeoutException te) { if (GLog.IsLogErrorEnabled) { GLog.LogException(te); } _Error = "timedout"; } catch (System.Net.WebException we) { if (GLog.IsLogErrorEnabled) { GLog.LogException(we); } #if NETFX_CORE if (we.Status.ToString() == "Timeout") #else if (we.Status == System.Net.WebExceptionStatus.Timeout) #endif { _Error = "timedout"; } else { if (we.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)we.Response).StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable) { } else { _Error = "Request Error (Exception):\n" + we.ToString(); } } } catch (Exception e) { if (GLog.IsLogErrorEnabled) { GLog.LogException(e); } _Error = "Request Error (Exception):\n" + e.ToString(); } finally { if (_Error == null) { lock (_CloseLock) { _Closed = true; _InnerReq = null; } } else { StopRequest(); } } } catch (TimeoutException te) { if (GLog.IsLogErrorEnabled) { GLog.LogException(te); } _Error = "timedout"; } catch (System.Net.WebException we) { if (GLog.IsLogErrorEnabled) { GLog.LogException(we); } #if NETFX_CORE if (we.Status.ToString() == "Timeout") #else if (we.Status == System.Net.WebExceptionStatus.Timeout) #endif { _Error = "timedout"; } else { _Error = "Request Error (Exception):\n" + we.ToString(); } } catch (Exception e) { if (GLog.IsLogErrorEnabled) { GLog.LogException(e); } _Error = "Request Error (Exception):\n" + e.ToString(); } finally { lock (_CloseLock) { _Status = RequestStatus.Finished; if (_OnDone != null) { var ondone = _OnDone; _OnDone = null; ondone(); } } } }
public async System.Threading.Tasks.Task <System.Text.Json.JsonElement> SendAsync() { if (System.String.IsNullOrWhiteSpace(this.URL)) { throw new System.Exception(SoftmakeAll.SDK.Communication.REST.EmptyURLErrorMessage); } this.HasRequestErrors = false; if (System.String.IsNullOrWhiteSpace(this.Method)) { this.Method = SoftmakeAll.SDK.Communication.REST.DefaultMethod; } System.Text.Json.JsonElement Result = new System.Text.Json.JsonElement(); try { System.Net.HttpWebRequest HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(this.URL); HttpWebRequest.Method = this.Method; if (this.Headers.Count > 0) { foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers) { if (Header.Key != "Content-Type") { HttpWebRequest.Headers.Add(Header.Key, Header.Value); } else { HttpWebRequest.ContentType = Header.Value; } } } this.AddAuthorizationHeader(HttpWebRequest); if (this.Body.ValueKind == System.Text.Json.JsonValueKind.Undefined) { HttpWebRequest.ContentLength = 0; } else { System.Byte[] BodyBytes = new System.Text.UTF8Encoding().GetBytes(Body.ToString()); HttpWebRequest.ContentType = SoftmakeAll.SDK.Communication.REST.DefaultContentType; HttpWebRequest.ContentLength = BodyBytes.Length; await(await HttpWebRequest.GetRequestStreamAsync()).WriteAsync(BodyBytes, 0, BodyBytes.Length); } if (this.Timeout > 0) { HttpWebRequest.Timeout = this.Timeout; } using (System.Net.HttpWebResponse HttpWebResponse = (System.Net.HttpWebResponse) await HttpWebRequest.GetResponseAsync()) { this._StatusCode = HttpWebResponse.StatusCode; Result = await this.ReadResponseStreamAsync(HttpWebResponse); } } catch (System.Net.WebException ex) { this.HasRequestErrors = true; System.Net.HttpWebResponse HttpWebResponse = ex.Response as System.Net.HttpWebResponse; if (HttpWebResponse == null) { this._StatusCode = System.Net.HttpStatusCode.InternalServerError; Result = new { Error = true, Message = ex.Message }.ToJsonElement(); return(Result); } this._StatusCode = HttpWebResponse.StatusCode; Result = await this.ReadResponseStreamAsync(HttpWebResponse); } catch (System.Exception ex) { this.HasRequestErrors = true; this._StatusCode = System.Net.HttpStatusCode.InternalServerError; Result = new { Error = true, Message = ex.Message }.ToJsonElement(); } return(Result); }
public async System.Threading.Tasks.Task <SoftmakeAll.SDK.Communication.REST.File> DownloadFileAsync() { if (System.String.IsNullOrWhiteSpace(this.URL)) { throw new System.Exception(SoftmakeAll.SDK.Communication.REST.EmptyURLErrorMessage); } this.HasRequestErrors = false; this.Method = SoftmakeAll.SDK.Communication.REST.DefaultMethod; SoftmakeAll.SDK.Communication.REST.File Result = null; try { System.Net.HttpWebRequest HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(this.URL); HttpWebRequest.Method = this.Method; if (this.Headers.Count > 0) { foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers) { HttpWebRequest.Headers.Add(Header.Key, Header.Value); } } this.AddAuthorizationHeader(HttpWebRequest); if (this.Body.ValueKind == System.Text.Json.JsonValueKind.Undefined) { HttpWebRequest.ContentLength = 0; } else { System.Byte[] BodyBytes = new System.Text.UTF8Encoding().GetBytes(Body.ToString()); HttpWebRequest.ContentType = SoftmakeAll.SDK.Communication.REST.DefaultContentType; HttpWebRequest.ContentLength = BodyBytes.Length; System.IO.Stream RequestStream = await HttpWebRequest.GetRequestStreamAsync(); await RequestStream.WriteAsync(BodyBytes, 0, BodyBytes.Length); } if (this.Timeout > 0) { HttpWebRequest.Timeout = this.Timeout; } using (System.Net.HttpWebResponse HttpWebResponse = (System.Net.HttpWebResponse) await HttpWebRequest.GetResponseAsync()) { this._StatusCode = HttpWebResponse.StatusCode; System.Net.WebClient WebClient = new System.Net.WebClient(); foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers) { WebClient.Headers.Add(Header.Key, Header.Value); } this.AddAuthorizationHeader(WebClient); System.Byte[] FileContents = WebClient.DownloadData(this.URL); if ((FileContents == null) || (FileContents.Length == 0)) { return(null); } System.String FileName = ""; try { const System.String Key = "filename="; FileName = HttpWebResponse.Headers.Get("Content-Disposition"); FileName = FileName.Substring(FileName.IndexOf(Key) + Key.Length); FileName = FileName.Substring(0, FileName.IndexOf(';')); } catch { FileName = ""; } return(new SoftmakeAll.SDK.Communication.REST.File() { Name = FileName, Contents = FileContents }); } } catch (System.Net.WebException ex) { this.HasRequestErrors = true; System.Net.HttpWebResponse HttpWebResponse = ex.Response as System.Net.HttpWebResponse; if (HttpWebResponse == null) { this._StatusCode = System.Net.HttpStatusCode.InternalServerError; Result = null; return(Result); } this._StatusCode = HttpWebResponse.StatusCode; Result = null; } catch { this.HasRequestErrors = true; this._StatusCode = System.Net.HttpStatusCode.InternalServerError; Result = null; } return(Result); }
//Use the ArcGIS REST API to create a profile line based on the input geometry public async Task <Polyline> GetProfileLine(Geometry geometry) { try { string requestUrlBase = @"http://elevation.arcgis.com/arcgis/rest/services/Tools/Elevation/GPServer/Profile/"; //Create the token to use TokenService elevationServices = new TokenService(); _token = await elevationServices.GenerateTokenAsync(); #region Submit a profile task to be executed asynchronously. A unique job ID will be assigned for the transaction. string oidField = "OID"; string lengthField = "Shape_Length"; string InputLineFeatures = CreateInputLineFeaturesJson(geometry, oidField, lengthField); string additonalParams = "&ProfileIDField=" + oidField + "&DEMResolution=FINEST&MaximumSampleDistance=10&MaximumSampleDistanceUnits=Kilometers&returnZ=true&returnM=true&env%3AoutSR=102100&env%3AprocessSR=102100&f=json"; string profileServiceUrl = string.Format("{0}submitJob?token={1}&InputLineFeatures={2}{3}", requestUrlBase, _token.AccessToken, InputLineFeatures, additonalParams); System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(profileServiceUrl); webRequest.Timeout = 0xea60; System.Net.WebResponse response = await webRequest.GetResponseAsync(); #endregion #region Use the jobId to check the status of the job. Keep checking if the jobStatus is not "Succeeded" DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JobStatus)); _jobStatus = (JobStatus)serializer.ReadObject(response.GetResponseStream() as Stream); while (_jobStatus.Status.Contains("Executing") || _jobStatus.Status.Contains("esriJobWaiting") || _jobStatus.Status.Contains("Submitted")) { string statusUrl = string.Format("{0}jobs/{1}?f=pjson&token={2}", requestUrlBase, _jobStatus.Id, _token.AccessToken); webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(statusUrl); response = await webRequest.GetResponseAsync(); _jobStatus = (JobStatus)serializer.ReadObject(response.GetResponseStream()); } #endregion #region The job has successfully completed. Use the jobId to retrieve the result, then use the result to create a profile line if (_jobStatus.Status.Contains("Succeeded")) { string resultsUrl = string.Format("{0}jobs/{1}/results/OutputProfile?returnZ=true&returnM=true&f=pjson&token={2}", requestUrlBase, _jobStatus.Id, _token.AccessToken); webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(resultsUrl); response = await webRequest.GetResponseAsync(); serializer = new DataContractJsonSerializer(typeof(OutputProfile)); //Parse the result as the output profile line _outputProfileLine = (OutputProfile)serializer.ReadObject(response.GetResponseStream()); _outputProfileLine.FeatureSet.HasM = true; _outputProfileLine.FeatureSet.HasZ = true; //Create a polyline (profile) from the geometry of the output profile line Polyline profile = new Polyline(); foreach (var points in _outputProfileLine.FeatureSet.Features.FirstOrDefault().Geometry.Paths) { PointCollection collection = new PointCollection(); foreach (var point in points) { collection.Add( new MapPoint( Convert.ToDouble(point[0]), //[0] is x Convert.ToDouble(point[1]), //[1] is x Convert.ToDouble(point[2]), //[2] is z Convert.ToDouble(point[3]), //[3] is m new ESRI.ArcGIS.Client.Geometry.SpatialReference(102100))); } profile.Paths.Add(collection); } return(profile); } return(null); #endregion } catch (Exception) { return(null); } }
public void MapRoute(IApplicationBuilder app) { string address = "http://moa.hengyinfs.com"; //string address = "http://localhost:5010"; app.Map("/SqlClient", builder => { builder.Run(async context => { SqlConnection connection = new SqlConnection("Max Pool Size = 512;server=localhost;uid=sa;pwd=123456;database=HttpReports;"); var count = await connection.QueryFirstOrDefaultAsync <dynamic>("select * from requestinfo"); await context.Response.WriteAsync("ok"); }); }); app.Map("/MySql", builder => { builder.Run(async context => { MySqlConnection connection = new MySqlConnection("DataBase=HttpReports;Data Source=localhost;User Id=root;Password=123456;"); var count = await connection.QueryFirstOrDefaultAsync <dynamic>("select * from requestinfo"); await context.Response.WriteAsync("ok"); }); }); app.Map("/HttpClient", builder => { builder.Run(async context => { HttpClient client = new HttpClient(); var response = client.GetStringAsync("http://www.baidu.com").Result; await context.Response.WriteAsync("OK"); }); }); app.Map("/Trace", builder => { builder.Run(async context => { //System.Threading.Thread.Sleep(new Random().Next(111, 5555)); //HttpClient client = new HttpClient(); //var response = await client.GetStringAsync(address +"/Test1"); //await context.Response.WriteAsync(response); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address + "/Test1"); req.Timeout = 5000000; using (System.Net.WebResponse wr = await req.GetResponseAsync()) { await context.Response.WriteAsync("ok"); } }); }); app.Map("/Test1", builder => { builder.Run(async context => { System.Threading.Thread.Sleep(new Random().Next(111, 5555)); HttpClient client = new HttpClient(); var response = await client.GetStringAsync(address + "/Test2"); await context.Response.WriteAsync(response); }); }); app.Map("/Test2", builder => { builder.Run(async context => { System.Threading.Thread.Sleep(new Random().Next(111, 5555)); HttpClient client = new HttpClient(); var response = await client.GetStringAsync(address + "/Test3"); await context.Response.WriteAsync(response); }); }); app.Map("/Test3", builder => { builder.Run(async context => { System.Threading.Thread.Sleep(new Random().Next(111, 5555)); HttpClient client = new HttpClient(); var response = await client.GetStringAsync(address + "/Test4"); await context.Response.WriteAsync(response); }); }); app.Map("/Test4", builder => { builder.Run(async context => { System.Threading.Thread.Sleep(new Random().Next(111, 5555)); HttpClient client = new HttpClient(); var response = await client.GetStringAsync(address + "/Test5"); await context.Response.WriteAsync(response); }); }); app.Map("/Test5", builder => { builder.Run(async context => { System.Threading.Thread.Sleep(new Random().Next(111, 5555)); await context.Response.WriteAsync("ok"); return; }); }); }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); var client = manager.Client; commands.ForEach(cmd => cmd.Init(cgb)); cgb.CreateCommand(".sr").Alias(".setrole") .Description("Sets a role for a given user.\n**Usage**: .sr @User Guest") .Parameter("user_name", ParameterType.Required) .Parameter("role_name", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.ManageRoles) { return; } var usr = e.Server.FindUsers(e.GetArg("user_name")).FirstOrDefault(); if (usr == null) { await e.Send("You failed to supply a valid username"); return; } var role = e.Server.FindRoles(e.GetArg("role_name")).FirstOrDefault(); if (role == null) { await e.Send("You failed to supply a valid role"); return; } try { await usr.AddRoles(new Role[] { role }); await e.Send($"Successfully added role **{role.Name}** to user **{usr.Name}**"); } catch (Exception ex) { await e.Send("Failed to add roles. Most likely reason: Insufficient permissions.\n"); Console.WriteLine(ex.ToString()); } }); cgb.CreateCommand(".rr").Alias(".removerole") .Description("Removes a role from a given user.\n**Usage**: .rr @User Admin") .Parameter("user_name", ParameterType.Required) .Parameter("role_name", ParameterType.Required) .Do(async e => { if (!e.User.ServerPermissions.ManageRoles) { return; } var usr = e.Server.FindUsers(e.GetArg("user_name")).FirstOrDefault(); if (usr == null) { await e.Send("You failed to supply a valid username"); return; } var role = e.Server.FindRoles(e.GetArg("role_name")).FirstOrDefault(); if (role == null) { await e.Send("You failed to supply a valid role"); return; } try { await usr.RemoveRoles(new Role[] { role }); await e.Send($"Successfully removed role **{role.Name}** from user **{usr.Name}**"); } catch (InvalidOperationException) { } catch { await e.Send("Failed to remove roles. Most likely reason: Insufficient permissions."); } }); cgb.CreateCommand(".r").Alias(".role").Alias(".cr") .Description("Creates a role with a given name.**Usage**: .r Awesome Role") .Parameter("role_name", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.ManageRoles) { return; } if (string.IsNullOrWhiteSpace(e.GetArg("role_name"))) { return; } try { var r = await e.Server.CreateRole(e.GetArg("role_name")); await e.Send($"Successfully created role **{r.Name}**."); } catch (Exception ex) { await e.Send(":warning: Unspecified error."); } }); cgb.CreateCommand(".rolecolor").Alias(".rc") .Parameter("Rolename", ParameterType.Required) .Parameter("r", ParameterType.Optional) .Parameter("g", ParameterType.Optional) .Parameter("b", ParameterType.Optional) .Description("Set a role's color to the hex or 0-255 color value provided.\n**Usage**: .color Admin 255 200 100 or .color Admin ffba55") .Do(async e => { if (!e.User.ServerPermissions.ManageRoles) { await e.Channel.SendMessage("You don't have permission to use this!"); return; } var args = e.Args.Where(s => s != String.Empty); if (args.Count() != 2 && args.Count() != 4) { await e.Send("The parameters are invalid."); return; } Role role = e.Server.FindRoles(e.Args[0]).FirstOrDefault(); if (role == null) { await e.Send("That role does not exist."); return; } try { bool rgb = args.Count() == 4; byte red = Convert.ToByte(rgb ? int.Parse(e.Args[1]) : Convert.ToInt32(e.Args[1].Substring(0, 2), 16)); byte green = Convert.ToByte(rgb ? int.Parse(e.Args[2]) : Convert.ToInt32(e.Args[1].Substring(2, 2), 16)); byte blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(e.Args[1].Substring(4, 2), 16)); await role.Edit(color: new Color(red, green, blue)); await e.Channel.SendMessage($"Role {role.Name}'s color has been changed."); } catch (Exception ex) { await e.Send(":warning: Unspecified error, please report this."); Console.WriteLine($".rolecolor error: {ex}"); } }); cgb.CreateCommand(".roles") .Description("List all roles on this server or a single user if specified.") .Parameter("user", ParameterType.Unparsed) .Do(async e => { if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) { var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault(); if (usr != null) { await e.Send($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles).Replace("@everyone", "මeveryone")); return; } } await e.Send("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles).Replace("@everyone", "මeveryone")); }); cgb.CreateCommand(".modules") .Description("List all bot modules") .Do(async e => { await e.Send("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.client.Modules().Modules.Select(m => m.Name))); }); cgb.CreateCommand(".commands") .Description("List all of the bot's commands from a certain module.") .Parameter("module", ParameterType.Unparsed) .Do(async e => { var commands = NadekoBot.client.Services.Get <CommandService>().AllCommands .Where(c => c.Category.ToLower() == e.GetArg("module").Trim().ToLower()); if (commands == null || commands.Count() == 0) { await e.Send("That module does not exist."); return; } await e.Send("`List of commands:` \n• " + string.Join("\n• ", commands.Select(c => c.Text))); }); cgb.CreateCommand(".b").Alias(".ban") .Parameter("everything", ParameterType.Unparsed) .Description("Bans a mentioned user") .Do(async e => { try { if (e.User.ServerPermissions.BanMembers && e.Message.MentionedUsers.Any()) { var usr = e.Message.MentionedUsers.First(); await usr.Server.Ban(usr); await e.Send("Banned user " + usr.Name + " Id: " + usr.Id); } } catch (Exception ex) { } }); cgb.CreateCommand(".ub").Alias(".unban") .Parameter("everything", ParameterType.Unparsed) .Description("Unbans a mentioned user") .Do(async e => { try { if (e.User.ServerPermissions.BanMembers && e.Message.MentionedUsers.Any()) { var usr = e.Message.MentionedUsers.First(); await usr.Server.Unban(usr); await e.Send("Unbanned user " + usr.Name + " Id: " + usr.Id); } } catch { } }); cgb.CreateCommand(".k").Alias(".kick") .Parameter("user") .Description("Kicks a mentioned user.") .Do(async e => { try { if (e.User.ServerPermissions.KickMembers && e.Message.MentionedUsers.Any()) { var usr = e.Message.MentionedUsers.First(); await e.Message.MentionedUsers.First().Kick(); await e.Send("Kicked user " + usr.Name + " Id: " + usr.Id); } } catch { await e.Send("No sufficient permissions."); } }); cgb.CreateCommand(".mute") .Description("Mutes mentioned user or users") .Parameter("throwaway", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.MuteMembers) { await e.Send("You do not have permission to do that."); return; } if (e.Message.MentionedUsers.Count() == 0) { return; } try { foreach (var u in e.Message.MentionedUsers) { await u.Edit(isMuted: true); } await e.Send("Mute successful"); } catch { await e.Send("I do not have permission to do that most likely."); } }); cgb.CreateCommand(".unmute") .Description("Unmutes mentioned user or users") .Parameter("throwaway", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.MuteMembers) { await e.Send("You do not have permission to do that."); return; } if (e.Message.MentionedUsers.Count() == 0) { return; } try { foreach (var u in e.Message.MentionedUsers) { await u.Edit(isMuted: false); } await e.Send("Unmute successful"); } catch { await e.Send("I do not have permission to do that most likely."); } }); cgb.CreateCommand(".deafen") .Alias(".deaf") .Description("Deafens mentioned user or users") .Parameter("throwaway", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.DeafenMembers) { await e.Send("You do not have permission to do that."); return; } if (e.Message.MentionedUsers.Count() == 0) { return; } try { foreach (var u in e.Message.MentionedUsers) { await u.Edit(isDeafened: true); } await e.Send("Deafen successful"); } catch { await e.Send("I do not have permission to do that most likely."); } }); cgb.CreateCommand(".undeafen") .Alias(".undeaf") .Description("Undeafens mentioned user or users") .Parameter("throwaway", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.DeafenMembers) { await e.Send("You do not have permission to do that."); return; } if (e.Message.MentionedUsers.Count() == 0) { return; } try { foreach (var u in e.Message.MentionedUsers) { await u.Edit(isDeafened: false); } await e.Send("Undeafen successful"); } catch { await e.Send("I do not have permission to do that most likely."); } }); cgb.CreateCommand(".rvch") .Description("Removes a voice channel with a given name.") .Parameter("channel_name", ParameterType.Required) .Do(async e => { try { if (e.User.ServerPermissions.ManageChannels) { await e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Voice).FirstOrDefault()?.Delete(); await e.Send($"Removed channel **{e.GetArg("channel_name")}**."); } } catch { await e.Send("No sufficient permissions."); } }); cgb.CreateCommand(".vch").Alias(".cvch") .Description("Creates a new voice channel with a given name.") .Parameter("channel_name", ParameterType.Required) .Do(async e => { try { if (e.User.ServerPermissions.ManageChannels) { await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice); await e.Send($"Created voice channel **{e.GetArg("channel_name")}**."); } } catch { await e.Send("No sufficient permissions."); } }); cgb.CreateCommand(".rch").Alias(".rtch") .Description("Removes a text channel with a given name.") .Parameter("channel_name", ParameterType.Required) .Do(async e => { try { if (e.User.ServerPermissions.ManageChannels) { await e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault()?.Delete(); await e.Send($"Removed text channel **{e.GetArg("channel_name")}**."); } } catch { await e.Send("No sufficient permissions."); } }); cgb.CreateCommand(".ch").Alias(".tch") .Description("Creates a new text channel with a given name.") .Parameter("channel_name", ParameterType.Required) .Do(async e => { try { if (e.User.ServerPermissions.ManageChannels) { await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text); await e.Send($"Added text channel **{e.GetArg("channel_name")}**."); } } catch { await e.Send("No sufficient permissions."); } }); cgb.CreateCommand(".st").Alias(".settopic") .Description("Sets a topic on the current channel.") .Parameter("topic", ParameterType.Unparsed) .Do(async e => { try { if (e.User.ServerPermissions.ManageChannels) { await e.Channel.Edit(topic: e.GetArg("topic")); } } catch { } }); cgb.CreateCommand(".uid").Alias(".userid") .Description("Shows user id") .Parameter("user", ParameterType.Optional) .Do(async e => { var usr = e.User; if (e.GetArg("user") != null) { usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault(); } await e.Send($"Id of the user { usr.Name } is { usr.Id }"); }); cgb.CreateCommand(".cid").Alias(".channelid") .Description("Shows current channel id") .Do(async e => await e.Send("This channel's id is " + e.Channel.Id)); cgb.CreateCommand(".sid").Alias(".serverid") .Description("Shows current server id") .Do(async e => await e.Send("This server's id is " + e.Server.Id)); cgb.CreateCommand(".stats") .Description("Shows some basic stats for nadeko") .Do(async e => { var t = Task.Run(() => { return(NadekoStats.Instance.GetStats() + "`" + Music.GetMusicStats() + "`"); }); await e.Send(await t); }); cgb.CreateCommand(".leaveall") .Description("Nadeko leaves all servers **OWNER ONLY**") .Do(e => { if (e.User.Id == NadekoBot.OwnerID) { NadekoBot.client.Servers.ForEach(async s => { if (s.Name == e.Server.Name) { return; } await s.Leave(); }); } }); cgb.CreateCommand(".prune") .Parameter("num", ParameterType.Required) .Description("Prunes a number of messages from the current channel.\n**Usage**: .prune 5") .Do(async e => { if (!e.User.ServerPermissions.ManageMessages) { return; } int val; if (string.IsNullOrWhiteSpace(e.GetArg("num")) || !int.TryParse(e.GetArg("num"), out val) || val < 0) { return; } foreach (var msg in await e.Channel.DownloadMessages(val)) { await msg.Delete(); await Task.Delay(100); } }); cgb.CreateCommand(".die") .Alias(".graceful") .Description("Works only for the owner. Shuts the bot down and notifies users about the restart.") .Do(async e => { if (e.User.Id == NadekoBot.OwnerID) { Timer t = new Timer(); t.Interval = 2000; t.Elapsed += (s, ev) => { Environment.Exit(0); }; t.Start(); await e.Send("`Shutting down.`"); } }); ConcurrentDictionary <Server, bool> clearDictionary = new ConcurrentDictionary <Server, bool>(); cgb.CreateCommand(".clr") .Description("Clears some of nadeko's messages from the current channel.") .Do(async e => { await Task.Run(async() => { var msgs = (await e.Channel.DownloadMessages(100)).Where(m => m.User.Id == NadekoBot.client.CurrentUser.Id); foreach (var m in msgs) { await m.Delete(); } }); }); cgb.CreateCommand(".newname") .Alias(".setname") .Description("Give the bot a new name.") .Parameter("new_name", ParameterType.Unparsed) .Do(async e => { if (e.User.Id != NadekoBot.OwnerID || e.GetArg("new_name") == null) { return; } await client.CurrentUser.Edit(NadekoBot.password, e.GetArg("new_name")); }); cgb.CreateCommand(".newavatar") .Alias(".setavatar") .Description("Sets a new avatar image for the NadekoBot.") .Parameter("img", ParameterType.Unparsed) .Do(async e => { if (e.User.Id != NadekoBot.OwnerID || string.IsNullOrWhiteSpace(e.GetArg("img"))) { return; } // Gather user provided URL. string avatarAddress = e.GetArg("img"); // Creates an HTTPWebRequest object, which references the URL given by the user. System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Uri.EscapeUriString(avatarAddress)); // Discard the response if image isnt downloaded in 5 s as to not lock Nadeko. Prevents loading from faulty links. webRequest.Timeout = 5000; // Gathers the webRequest response as a Stream object. System.Net.WebResponse webResponse = await webRequest.GetResponseAsync(); // Create image object from the response we got from the webRequest stream. This is because there is no "GetResponseStream". System.Drawing.Image image = System.Drawing.Image.FromStream(webResponse.GetResponseStream()); // Save the image to disk. image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png); await client.CurrentUser.Edit(NadekoBot.password, avatar: image.ToStream()); // Send confirm. await e.Send("New avatar set."); }); cgb.CreateCommand(".setgame") .Description("Sets the bots game.") .Parameter("set_game", ParameterType.Unparsed) .Do(e => { if (e.User.Id != NadekoBot.OwnerID || e.GetArg("set_game") == null) { return; } client.SetGame(e.GetArg("set_game")); }); cgb.CreateCommand(".checkmyperms") .Description("Checks your userspecific permissions on this channel.") .Do(async e => { string output = "```\n"; foreach (var p in e.User.ServerPermissions.GetType().GetProperties().Where(p => p.GetGetMethod().GetParameters().Count() == 0)) { output += p.Name + ": " + p.GetValue(e.User.ServerPermissions, null).ToString() + "\n"; } output += "```"; await e.User.SendMessage(output); }); Server commsServer = null; User commsUser = null; Channel commsChannel = null; cgb.CreateCommand(".commsuser") .Description("Sets a user for through-bot communication. Only works if server is set. Resets commschannel.**Owner only**.") .Parameter("name", ParameterType.Unparsed) .Do(async e => { if (e.User.Id != NadekoBot.OwnerID) { return; } commsUser = commsServer?.FindUsers(e.GetArg("name")).FirstOrDefault(); if (commsUser != null) { commsChannel = null; await e.Send("User for comms set."); } else { await e.Send("No server specified or user."); } }); cgb.CreateCommand(".commsserver") .Description("Sets a server for through-bot communication.**Owner only**.") .Parameter("server", ParameterType.Unparsed) .Do(async e => { if (e.User.Id != NadekoBot.OwnerID) { return; } commsServer = client.FindServers(e.GetArg("server")).FirstOrDefault(); if (commsServer != null) { await e.Send("Server for comms set."); } else { await e.Send("No such server."); } }); cgb.CreateCommand(".commschannel") .Description("Sets a channel for through-bot communication. Only works if server is set. Resets commsuser.**Owner only**.") .Parameter("ch", ParameterType.Unparsed) .Do(async e => { if (e.User.Id != NadekoBot.OwnerID) { return; } commsChannel = commsServer?.FindChannels(e.GetArg("ch"), ChannelType.Text).FirstOrDefault(); if (commsChannel != null) { commsUser = null; await e.Send("Server for comms set."); } else { await e.Send("No server specified or channel is invalid."); } }); cgb.CreateCommand(".send") .Description("Send a message to someone on a different server through the bot.**Owner only.**\n **Usage**: .send Message text multi word!") .Parameter("msg", ParameterType.Unparsed) .Do(async e => { if (e.User.Id != NadekoBot.OwnerID) { return; } if (commsUser != null) { await commsUser.SendMessage(e.GetArg("msg")); } else if (commsChannel != null) { await commsChannel.SendMessage(e.GetArg("msg")); } else { await e.Send("Failed. Make sure you've specified server and [channel or user]"); } }); cgb.CreateCommand(".menrole") .Alias(".mentionrole") .Description("Mentions every person from the provided role or roles (separated by a ',') on this server. Requires you to have mention everyone permission.") .Parameter("roles", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.MentionEveryone) { return; } var arg = e.GetArg("roles").Split(',').Select(r => r.Trim()); string send = $"--{e.User.Mention} has invoked a mention on the following roles--"; foreach (var roleStr in arg) { if (string.IsNullOrWhiteSpace(roleStr)) { continue; } var role = e.Server.FindRoles(roleStr).FirstOrDefault(); if (role == null) { continue; } send += $"\n`{role.Name}`\n"; send += string.Join(", ", role.Members.Select(r => r.Mention)); } while (send.Length > 2000) { var curstr = send.Substring(0, 2000); await e.Channel.Send(curstr.Substring(0, curstr.LastIndexOf(", ") + 1)); send = curstr.Substring(curstr.LastIndexOf(", ") + 1) + send.Substring(2000); } await e.Channel.Send(send); }); cgb.CreateCommand(".parsetosql") .Description("Loads exported parsedata from /data/parsedata/ into sqlite database.") .Do(async e => { if (e.User.Id != NadekoBot.OwnerID) { return; } await Task.Run(() => { SaveParseToDb <Announcement>("data/parsedata/Announcements.json"); SaveParseToDb <Classes._DataModels.Command>("data/parsedata/CommandsRan.json"); SaveParseToDb <Request>("data/parsedata/Requests.json"); SaveParseToDb <Stats>("data/parsedata/Stats.json"); SaveParseToDb <TypingArticle>("data/parsedata/TypingArticles.json"); }); }); cgb.CreateCommand(".unstuck") .Description("Clears the message queue. **OWNER ONLY**") .Do(async e => { if (e.User.Id != NadekoBot.OwnerID) { return; } await Task.Run(() => NadekoBot.client.MessageQueue.Clear()); }); cgb.CreateCommand(".donators") .Description("List of lovely people who donated to keep this project alive.") .Do(async e => { await Task.Run(async() => { var rows = Classes.DBHandler.Instance.GetAllRows <Donator>(); var donatorsOrdered = rows.OrderByDescending(d => d.Amount); string str = $"`Total number of people who donated is {donatorsOrdered.Count()}`\n"; await e.Channel.SendMessage(str + string.Join(", ", donatorsOrdered.Select(d => d.UserName))); }); }); //THIS IS INTENTED TO BE USED ONLY BY THE ORIGINAL BOT OWNER cgb.CreateCommand(".adddon") .Alias(".donadd") .Description("Add a donator to the database.") .Parameter("donator") .Parameter("amount") .Do(e => { try { if (NadekoBot.OwnerID != e.User.Id) { return; } var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault(); var amount = int.Parse(e.GetArg("amount")); Classes.DBHandler.Instance.InsertData(new Donator { Amount = amount, UserName = donator.Name, UserId = (long)e.User.Id }); e.Channel.SendMessage("Successfuly added a new donator. 👑"); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("---------------\nInner error:\n" + ex.InnerException); } }); }); }