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));
        }
Example #2
0
        /// <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;
            }
        }
Example #3
0
        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));
        }
Example #5
0
        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));
        }
Example #8
0
        /// <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();
        }
Example #9
0
        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);
                }
            }
        }
Example #10
0
 public ConnectedState(IServerResponse response, IWebRequesterFactory webRequesterFactory, Dictionary <string, string> headers, ITokenService tokenService, ILogger logger)
 {
     _response            = response;
     _webRequesterFactory = webRequesterFactory;
     _headers             = headers;
     _tokenService        = tokenService;
     _logger = logger;
 }
Example #11
0
 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));
        }
Example #13
0
        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));
        }
Example #14
0
        /// <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);
        }
Example #15
0
        /// <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();
        }
Example #16
0
        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));
        }
Example #17
0
        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));
        }
Example #18
0
        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;
        }
Example #19
0
        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;
        }
Example #20
0
        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);
        }
Example #21
0
        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;
        }
Example #22
0
        public IServerResponse ResetPassword(ResetPasswordInfo resetPasswordInfo)
        {
            Assert.IsNotNull(resetPasswordInfo);
            Assert.IsStringNotNullOrEmpty(resetPasswordInfo.EmailOrMobile);
            Assert.IsStringNotNullOrEmpty(resetPasswordInfo.NewPassword);

            IServerResponse response = serverProvider.ResetPassword(resetPasswordInfo);

            return(response);
        }
Example #23
0
        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);
        }
Example #24
0
        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();
        }
Example #25
0
        /// <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;
            }
        }
Example #26
0
        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);
        }
Example #27
0
        /// <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);
        }
Example #28
0
        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);
        }
Example #29
0
        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);
        }
Example #30
0
        /// <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);
        }
Example #31
0
        /// <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);
        }
Example #32
0
        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();
        }
Example #33
0
 internal CachedResponse(IServerResponse res)
     : base(res)
 {
     this.res = res;
     cached = true;
 }
Example #34
0
 public RefreshResult(IServerResponse result = null)
 {
     this.result = result;
 }
 public ConnectedState(IServerResponse response, IWebRequesterFactory webRequesterFactory)
 {
     mResponse = response;
     mWebRequesterFactory = webRequesterFactory;
 }
Example #36
0
 /// <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);
 }
Example #37
0
 /// <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) { }
Example #38
0
 /// <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);
 }