public async Task <IEnumerable <Payment> > GetByCreator(int id) { IQuery getPaymentsByCreatorQuery = Program.DI.Resolve <GetPaymentsByCreatorQueryFactory>().GetByCreator(id); IServerResponse response = await Program.DI.Resolve <IServerCommunicator>().SendQuery(getPaymentsByCreatorQuery); return(Program.DI.Resolve <IResponseParser>().ParseCollection <Payment>(response)); }
/// <summary> /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void Process(IClientRequest request, IServerResponse response) { string[] clientMessage = Encoding.Default.GetString(request.Read()).TrimEnd('\0').Split(' '); if (clientMessage.Length == 1 && clientMessage[0] != "BYE") { response.Write("-Error Unknown Command"); return; } Debug.WriteLine("Message received by mock server: " + clientMessage[0] + " " + (clientMessage.Length == 2 ? clientMessage[1] : string.Empty)); switch (clientMessage[0]) { case "CONN": response.Write(string.Format("+OK Hello {0}", clientMessage[1])); break; case "MESG": MessageCount++; response.Write("+OK Msg Received"); OnMessageReceived(new MessageReceivedEventArgs(clientMessage[1])); break; case "BYE": response.Write("+OK GoodBye"); response.EndConnection = true; break; } }
public async Task <UserInfo> GetUserById(int id) { IQuery getUserByIdQuery = Program.DI.Resolve <GetUserByIdQueryFactory>().GetUserById(id); IServerResponse response = await Program.DI.Resolve <IServerCommunicator>().SendQuery(getUserByIdQuery); return(Program.DI.Resolve <IResponseParser>().Parse <UserInfo>(response)); }
public async Task <Payment> Add(AddPaymentForm addPaymentForm) { IQuery addPaymentQuery = Program.DI.Resolve <AddPaymentQueryFactory>().Add(addPaymentForm); IServerResponse response = await Program.DI.Resolve <IServerCommunicator>().SendQuery(addPaymentQuery); return(Program.DI.Resolve <IResponseParser>().Parse <Payment>(response)); }
public Task <IConnectionState> Run(Action <ServerSentEvent> donothing, CancellationToken cancelToken) { IWebRequester requester = _webRequesterFactory.Create(); var taskResp = requester.Get(_url, _tokenService, _headers); return(taskResp.ContinueWith <IConnectionState>(tsk => { if (tsk.Status == TaskStatus.RanToCompletion && !cancelToken.IsCancellationRequested) { IServerResponse response = tsk.Result; if (response.StatusCode == HttpStatusCode.OK) { return new ConnectedState(response, _webRequesterFactory, _headers, _tokenService, _logger); } else { _logger.LogInformation("Failed to connect to: " + _url.ToString() + response ?? (" Http statuscode: " + response.StatusCode)); } } else { _logger.LogDebug("Task Status {@Status}: {Reason}", tsk.Status, ExceptionDetails.InnermostMessage(tsk.Exception)); } return new DisconnectedState(_url, _webRequesterFactory, _headers, _tokenService, _logger); })); }
public async Task <Session> SignUp(SignUpForm signUpForm) { IQuery signUpQuery = Program.DI.Resolve <SignUpQueryFactory>().SignUp(signUpForm); IServerResponse response = await Program.DI.Resolve <IServerCommunicator>().SendQuery(signUpQuery); return(Program.DI.Resolve <IResponseParser>().Parse <Session>(response)); }
public async Task <Session> LogIn(LogInForm logInForm) { IQuery logInQuery = Program.DI.Resolve <LogInQueryFactory>().LogIn(logInForm); IServerResponse response = await Program.DI.Resolve <IServerCommunicator>().SendQuery(logInQuery); return(Program.DI.Resolve <IResponseParser>().Parse <Session>(response)); }
/// <summary> /// Serves the given file to the client and closes the request when done. /// </summary> /// <param name="res">The res.</param> /// <param name="path">The path.</param> /// <exception cref="System.ArgumentException">File does not exist</exception> public static void ServeFile(this IServerResponse res, string path) { if (!File.Exists(path)) { throw new ArgumentException("File does not exist"); } if (!res.IsCached) { res.ContentLength64 = new FileInfo(path).Length; } var fileInfo = new FileInfo(path); res.ContentLength64 = fileInfo.Length; var stream = File.Open(path, FileMode.Open, FileAccess.Read); var copier = new AsyncStreamCopier(stream, res.OutputStream); copier.Completed += (s, e) => { e.InputStream.Close(); res.Close(); }; copier.Copy(); }
public static void Run() { { // Old way string myResponse; bool success = Connector.TryConnect(out myResponse); WriteLine(myResponse); } { // New way bool success = Connector.TryConnect(out string myResponse); WriteLine(myResponse); } { // New way bool success1 = Connector.TryConnect(out Server1Response myResponse1); WriteServerResponse(myResponse1); bool success2 = Connector.TryConnect(out Server2Response myResponse2); WriteServerResponse(myResponse2); } // One way of dealing with failed connection attempts { IServerResponse response = null; try { response = Connector.Connect("server1"); if (response.Success) { DoSomething(response); } } catch (Exception) { HandleTheError(response); } } // Using the try pattern { if (Connector.TryConnect(out Server1Response myResponse1)) { DoSomething(myResponse1); } else { HandleTheError(myResponse1); } } }
public ConnectedState(IServerResponse response, IWebRequesterFactory webRequesterFactory, Dictionary <string, string> headers, ITokenService tokenService, ILogger logger) { _response = response; _webRequesterFactory = webRequesterFactory; _headers = headers; _tokenService = tokenService; _logger = logger; }
public static byte[] GetBytes(IServerResponse response) { using (MemoryStream stream = new MemoryStream()) { response.WriteTo(stream); return(stream.ToArray()); } }
public async Task <User> Update(User user) { IQuery updateProfileQuery = await App.DI.Resolve <UpdateProfileQueryFactory>().UpdateProfile(user); IServerResponse response = await App.DI.Resolve <IServerCommunicator>().SendQuery(updateProfileQuery); return(App.DI.Resolve <IResponseParser>().Parse <User>(response)); }
public async Task <User> GetUserById(long id) { IQuery getUserQuery = await App.DI.Resolve <GetProfileQueryFactory>().GetUserById(id); IServerResponse response = await App.DI.Resolve <IServerCommunicator>().SendQuery(getUserQuery); return(App.DI.Resolve <IResponseParser>().Parse <User>(response)); }
/// <summary> /// Processes a client request. /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void Process(IClientRequest request, IServerResponse response) { Argument.Assert.IsNotNull(request, "request"); Argument.Assert.IsNotNull(response, "response"); string[] commandArgs = Encoding.Default.GetString(request.Read()).Split(' '); ProcessCommand(commandArgs, response); }
/// <summary> /// Response with the status code: /// 405 Method Not Allowed /// A request was made of a resource using a request method not supported by that resource; /// for example, using GET on a form which requires data to be presented via POST, /// or using PUT on a read-only resource. /// </summary> /// <param name="res">The response to the client</param> /// <param name="allowedVerbs">The allowed verbs.</param> public static void Response405(this IServerResponse res, params HttpVerb[] allowedVerbs) { res.StatusCode = 405; var data = allowedVerbs.Aggregate("", (str, item) => str += item.ToString() + ","); res.Headers.Add("Allow", data.TrimEnd(',')); res.Close(); }
public async Task <User> LogIn(string login, string password) { IQuery logInQuery = await App.DI.Resolve <LogInQueryFactory>().LogIn(login, password); IServerResponse response = await App.DI.Resolve <IServerCommunicator>().SendQuery(logInQuery); return(App.DI.Resolve <IResponseParser>().Parse <User>(response)); }
public async Task <User> SignUp(string login, string password, string email) { IQuery signUpQuery = await App.DI.Resolve <SignUpQueryFactory>().SignUp(login, password, email); IServerResponse response = await App.DI.Resolve <IServerCommunicator>().SendQuery(signUpQuery); return(App.DI.Resolve <IResponseParser>().Parse <User>(response)); }
public dynamic Parse <E>(IServerResponse modelElementJSON) where E : Exception { E ex = null; try { ex = JsonConvert.DeserializeObject <E>(modelElementJSON.Data); } catch { return(JsonConvert.DeserializeObject(modelElementJSON.Data)); } throw ex; }
public IEnumerable <dynamic> ParseCollection <E>(IServerResponse modelElementJSON) where E : Exception { E ex = null; try { ex = JsonConvert.DeserializeObject <E>(modelElementJSON.Data); } catch { return(JsonConvert.DeserializeObject <List <dynamic> >(modelElementJSON.Data)); } throw ex; }
public async Task <User> ChangeAvatar(User user, Stream avatar) { IQuery changeAvatarQuery = await App.DI.Resolve <ChangeAvatarQueryFactory>().ChangeAvatar(user.id, avatar); IServerResponse response = await App.DI.Resolve <IServerCommunicator>().SendQuery(changeAvatarQuery); user.UpdateAvatarUrl(ServerCommunicator.MULTIPART_SERVER_URL + "/" + App.DI.Resolve <IResponseParser>().Parse <FilePath>(response).path); return(user); }
public T Parse <T>(IServerResponse modelElementJSON) where T : ModelElement { ResponseException ex = null; try { ex = JsonConvert.DeserializeObject <ResponseException>(modelElementJSON.Data); } catch { return(JsonConvert.DeserializeObject <T>(modelElementJSON.Data)); } throw ex; }
public IServerResponse ResetPassword(ResetPasswordInfo resetPasswordInfo) { Assert.IsNotNull(resetPasswordInfo); Assert.IsStringNotNullOrEmpty(resetPasswordInfo.EmailOrMobile); Assert.IsStringNotNullOrEmpty(resetPasswordInfo.NewPassword); IServerResponse response = serverProvider.ResetPassword(resetPasswordInfo); return(response); }
public IServerResponse ChangePassword(ChangePasswordInfo changePasswordInfo) { Assert.IsNotNull(changePasswordInfo); Assert.IsStringNotNullOrEmpty(changePasswordInfo.OldPassword); Assert.IsStringNotNullOrEmpty(changePasswordInfo.NewPassword); Assert.AreEqual(changePasswordInfo.NewPassword, changePasswordInfo.ConfirmPassword); IServerResponse response = serverProvider.ChangePassword(changePasswordInfo); return(response); }
public static void Refresh(IServerResponse msg = null, HttpResponseBase response = null) { if (response == null) { response = new HttpResponseWrapper(HttpContext.Current.Response); } StringBuilder sb = new StringBuilder(); sb.Append("<script type='text/javascript'> "); sb.Append("if(window.postMessage) { if(window.opener != null) { window.opener.postMessage('{\"event\":\"reload\""); if (msg != null) { sb.AppendFormat(", \"msg\": {{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}", (int)msg.Status, msg.Message); } sb.Append("}', '*'); }"); sb.Append("else if(window.parent != null) { window.parent.postMessage('{\"event\":\"reload\""); if (msg != null) { sb.AppendFormat(", \"msg\": {{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}", (int)msg.Status, msg.Message); } sb.Append("}', '*'); }"); sb.Append("else { window.top.postMessage('{\"event\":\"reload\""); if (msg != null) { sb.AppendFormat(", \"msg\": {{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}", (int)msg.Status, msg.Message); } sb.Append("}', '*'); }"); sb.Append("} else { if(window.opener != null) { "); if (msg != null) { sb.AppendFormat("window.localStorage.setItem(\"alert\", '{{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}');", (int)msg.Status, msg.Message); } sb.Append("window.opener.location.reload(); }"); sb.Append("else if(window.parent != null) { "); if (msg != null) { sb.AppendFormat("window.localStorage.setItem(\"alert\", '{{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}');", (int)msg.Status, msg.Message); } sb.Append("window.parent.location.reload(); }"); sb.Append("else { "); if (msg != null) { sb.AppendFormat("window.localStorage.setItem(\"alert\", '{{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}');", (int)msg.Status, msg.Message); } sb.Append("window.top.location.reload(); }"); sb.Append("} </script>"); response.Write(sb.ToString()); response.End(); }
/// <summary> /// Gets a proxy Response according to the Accept-Encoding header /// </summary> /// <param name="req">The req.</param> /// <param name="res">The res.</param> /// <returns>A proxy request that compresses the payload</returns> public static IServerResponse GetCompressedResponse(this HttpListenerRequest req, IServerResponse res) { var enc = req.GetAcceptEncoding(); switch(enc) { case EncodingType.Deflate: return new DeflateResponse(res); case EncodingType.Gzip: return new GzipResponse(res); default: return res; } }
public IServerResponse Register(RegisterInfo registerInfo) { Assert.IsNotNull(registerInfo); Assert.IsStringNotNullOrEmpty(registerInfo.Password); IServerResponse <Session> response = serverProvider.Register(registerInfo); if (response.Status == ResponseStatus.Success && response.Data != null) { SaveSession(response.Data); } return(response); }
/// <summary> /// Writes the specified byte data to the response /// </summary> /// <param name="res">The res.</param> /// <param name="type">The type.</param> /// <param name="data">The data.</param> /// <returns></returns> public static IServerResponse Write(this IServerResponse res, EncodingType type, byte[] data) { switch (type) { case EncodingType.Deflate: { res.Headers.Add("Content-Encoding", "deflate"); if (!res.IsCached) { res = res.GetCachedResponse(); } var stream = new DeflateStream(res.OutputStream, CompressionMode.Compress); stream.Write(data, 0, data.Length); stream.Flush(); } break; case EncodingType.Gzip: { res.Headers.Add("Content-Encoding", "gzip"); if (!res.IsCached) { res = res.GetCachedResponse(); } var stream = new GZipStream(res.OutputStream, CompressionMode.Compress); stream.Write(data, 0, data.Length); stream.Flush(); } break; case EncodingType.Plain: if (!res.IsCached) { res.ContentLength64 = data.Length; } res.OutputStream.Write(data, 0, data.Length); break; } return(res); }
public IServerResponse SignOn(SignOnInfo signOnInfo) { Assert.IsNotNull(signOnInfo); Assert.IsStringNotNullOrEmpty(signOnInfo.AccountOrEmailOrMobile); Assert.IsStringNotNullOrEmpty(signOnInfo.Password); IServerResponse <Session> response = serverProvider.SignOn(signOnInfo); if (response.Status == ResponseStatus.Success && response.Data != null) { SaveSession(response.Data); } return(response); }
public IServerResponse TransferSignOn(TransferSignOnInfo transferSignOnInfo) { Assert.IsNotNull(transferSignOnInfo); Assert.IsStringNotNullOrEmpty(transferSignOnInfo.ClientId); Assert.IsStringNotNullOrEmpty(transferSignOnInfo.SessionId); Assert.IsStringNotNullOrEmpty(transferSignOnInfo.FromClientId); Assert.IsStringNotNullOrEmpty(transferSignOnInfo.FromSessionId); IServerResponse <Session> response = serverProvider.TransferSignOn(transferSignOnInfo); if (response.Status == ResponseStatus.Success && response.Data != null) { SaveSession(response.Data); } return(response); }
/// <summary> /// Appends a "private" to the Cache-Control header to deny caching on shared caches. /// </summary> /// <param name="res">The res.</param> /// <returns></returns> public static IServerResponse CachePrivate(this IServerResponse res) { var header = res.Headers.Get("Cache-Control"); if (!string.IsNullOrEmpty(header)) { header = "private, " + header; } else { header = "private"; } res.Headers["Cache-Control"] = header; return(res); }
/// <summary> /// Sets the max-age part of the Cache-Control header /// </summary> /// <param name="res">The res.</param> /// <param name="seconds">The seconds.</param> /// <returns></returns> public static IServerResponse MaxAge(this IServerResponse res, int seconds) { var header = res.Headers.Get("Cache-Control"); if (!string.IsNullOrEmpty(header)) { header = header + string.Format(", max-age={0}", seconds); } else { header = string.Format("max-age={0}", seconds); } res.Headers["Cache-Control"] = header; return(res); }
public static void Refresh(IServerResponse msg = null, HttpResponseBase response = null) { if (response == null) response = new HttpResponseWrapper(HttpContext.Current.Response); StringBuilder sb = new StringBuilder(); sb.Append("<script type='text/javascript'> "); sb.Append("if(window.postMessage) { if(window.opener != null) { window.opener.postMessage('{\"event\":\"reload\""); if (msg != null) sb.AppendFormat(", \"msg\": {{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}", (int)msg.Status, msg.Message); sb.Append("}', '*'); }"); sb.Append("else if(window.parent != null) { window.parent.postMessage('{\"event\":\"reload\""); if (msg != null) sb.AppendFormat(", \"msg\": {{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}", (int)msg.Status, msg.Message); sb.Append("}', '*'); }"); sb.Append("else { window.top.postMessage('{\"event\":\"reload\""); if (msg != null) sb.AppendFormat(", \"msg\": {{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}", (int)msg.Status, msg.Message); sb.Append("}', '*'); }"); sb.Append("} else { if(window.opener != null) { "); if (msg != null) sb.AppendFormat("window.localStorage.setItem(\"alert\", '{{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}');", (int)msg.Status, msg.Message); sb.Append("window.opener.location.reload(); }"); sb.Append("else if(window.parent != null) { "); if (msg != null) sb.AppendFormat("window.localStorage.setItem(\"alert\", '{{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}');", (int)msg.Status, msg.Message); sb.Append("window.parent.location.reload(); }"); sb.Append("else { "); if (msg != null) sb.AppendFormat("window.localStorage.setItem(\"alert\", '{{ \"Status\": \"{0}\", \"Message\": \"{1}\" }}');", (int)msg.Status, msg.Message); sb.Append("window.top.location.reload(); }"); sb.Append("} </script>"); response.Write(sb.ToString()); response.End(); }
internal CachedResponse(IServerResponse res) : base(res) { this.res = res; cached = true; }
public RefreshResult(IServerResponse result = null) { this.result = result; }
public ConnectedState(IServerResponse response, IWebRequesterFactory webRequesterFactory) { mResponse = response; mWebRequesterFactory = webRequesterFactory; }
/// <summary> /// Initializes a new instance of the <see cref="GzipResponse" /> class. /// </summary> /// <param name="res">The res.</param> public GzipResponse(IServerResponse res) : base(res) { Headers.Add("Content-Encoding", "gzip"); gzipStream = new GZipStream(base.OutputStream, CompressionMode.Compress, true); }
/// <summary> /// Initializes a new instance of the <see cref="ServerResponse" /> class. /// </summary> /// <param name="res">The res.</param> public ServerResponse(IServerResponse res) : this((res as ServerResponse).InnerResponse) { }
/// <summary> /// Initializes a new instance of the <see cref="DeflateResponse" /> class. /// </summary> /// <param name="res">The res.</param> public DeflateResponse(IServerResponse res) : base (res) { Headers.Add("Content-Encoding", "deflate"); deflateStream = new DeflateStream(base.OutputStream, CompressionMode.Compress, true); }