Exemplo n.º 1
0
        public void SerializeError_serializes_httperror()
        {
            using (var stream = new MemoryStream())
            {
                var textWriter = new StreamWriter(stream);
                var writer     = new JsonTextWriter(textWriter);

                var mockInnerException = new Mock <Exception>(MockBehavior.Strict);
                mockInnerException.Setup(m => m.Message).Returns("Inner exception message");
                mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace");

                var outerException = new Exception("Outer exception message", mockInnerException.Object);

                var error = new HttpError(outerException, true)
                {
                    StackTrace = "Outer stack trace"
                };
                var jsonSerializer = new JsonSerializer();

                var mockIdProvider = new Mock <IErrorIdProvider>(MockBehavior.Strict);
                mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny <HttpError>())).Returns("OUTER-ID").Returns("INNER-ID");

                var serializer = new ErrorSerializer(mockIdProvider.Object);
                serializer.SerializeError(error, stream, writer, jsonSerializer);

                writer.Flush();

                var expectedJson         = File.ReadAllText("ErrorSerializerTest.json");
                var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
                var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
                output.Should().Be(minifiedExpectedJson);
            }
        }
Exemplo n.º 2
0
        public T GetResponse <T>(String method_name, params DiscuzParam[] parameters)
        {
            //String url = FormatGetUrl(method_name, parameters);
            //byte[] response_bytes = GetResponseBytes(url);

            DiscuzParam[] signed = Sign(method_name, parameters);

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < signed.Length; i++)
            {
                if (i > 0)
                {
                    builder.Append("&");
                }

                builder.Append(signed[i].ToEncodedString());
            }

            byte[] response_bytes = GetResponseBytes(Url, method_name, builder.ToString());


            XmlSerializer response_serializer = GetSerializer(typeof(T));

            try
            {
                T response = (T)response_serializer.Deserialize(new MemoryStream(response_bytes));
                return(response);
            }
            catch
            {
                Error error = (Error)ErrorSerializer.Deserialize(new MemoryStream(response_bytes));
                throw new DiscuzException(error.ErrorCode, error.ErrorMsg);
            }
        }
Exemplo n.º 3
0
        public void CanSerialize_returns_true_for_HttpError()
        {
            var serializer = new ErrorSerializer();
            var result     = serializer.CanSerialize(typeof(HttpError));

            result.Should().BeTrue();
        }
Exemplo n.º 4
0
        public void CanSerialize_returns_false_for_Exception()
        {
            var serializer = new ErrorSerializer();
            var result     = serializer.CanSerialize(typeof(Exception));

            result.Should().BeFalse();
        }
Exemplo n.º 5
0
        public void DoesNotPutNullInALink()
        {
            var exception = new JsonApiException(ErrorType.Server, "Some message");
            var errors    = new ErrorSerializer().Serialize(new ApiError(exception))["errors"][0];

            Assert.Null(errors["links"]);
        }
Exemplo n.º 6
0
        public void SerializesHttpError()
        {
            var innerException = new ApplicationException("Another message");
            var exception      = new InvalidOperationException("Some message", innerException);
            var httpError      = new System.Web.Http.HttpError(exception, true);

            var errors = new ErrorSerializer().Serialize(new ApiError(httpError))["errors"][0];

            Assert.Equal("Some message. Another message.", errors.Value <string>("title"));
            Assert.Equal(httpError.ExceptionType, errors.Value <string>("code"));
            Assert.Equal(httpError.StackTrace, errors.Value <string>("detail"));
        }
Exemplo n.º 7
0
        public void SerializesProperties()
        {
            var exception = new InvalidOperationException("Some message")
            {
                HelpLink = "http://example.com"
            };
            var errors = new ErrorSerializer().Serialize(new ApiError(exception))["errors"][0];

            Assert.Equal(exception.Message, errors.Value <string>("title"));
            Assert.Equal(exception.HelpLink, errors["links"].Value <string>("about"));
            Assert.Equal(exception.GetType().FullName, errors.Value <string>("code"));
            Assert.Equal(exception.ToString(), errors.Value <string>("detail"));
        }
Exemplo n.º 8
0
        public T GetResponse <T>(string method_name, params FacebookParam[] parameters)
        {
            string url = FormatGetUrl(method_name, parameters);

            byte[] response_bytes = GetResponseBytes(url);

            XmlSerializer response_serializer = GetSerializer(typeof(T));

            try {
                T response = (T)response_serializer.Deserialize(new MemoryStream(response_bytes));
                return(response);
            }
            catch {
                Error error = (Error)ErrorSerializer.Deserialize(new MemoryStream(response_bytes));
                throw new FacebookException(error.ErrorCode, error.ErrorMsg);
            }
        }
Exemplo n.º 9
0
        public void SerializesTwoExceptions()
        {
            var exception1 = new InvalidOperationException("Some message 1");
            var exception2 = new ArgumentException("Some message 2");
            var errors     =
                new ErrorSerializer().Serialize(
                    new List <ApiError>()
            {
                new ApiError(exception1), new ApiError(exception2)
            })["errors"];

            Assert.Equal(exception1.Message, errors[0].Value <string>("title"));
            Assert.Equal(exception1.GetType().FullName, errors[0].Value <string>("code"));
            Assert.Equal(exception1.ToString(), errors[0].Value <string>("detail"));

            Assert.Equal(exception2.Message, errors[1].Value <string>("title"));
            Assert.Equal(exception2.GetType().FullName, errors[1].Value <string>("code"));
            Assert.Equal(exception2.ToString(), errors[1].Value <string>("detail"));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Tworzy instancję tego serializatora wykonując walidację wprowadzonych danych
        /// </summary>
        /// <param name="status">Status odpowiedzi</param>
        /// <param name="actionName">Nazwa wykonanej akcji</param>
        /// <param name="data">Dane wynikowe wykonanej akcji</param>
        /// <param name="errors">Błędy wykonanej akcji</param>
        /// <returns></returns>
        public static ActionResponseSerializer CreateInstance(string status, string actionName, JObject data, IEnumerable <ErrorData> errors)
        {
            var result = new ActionResponseSerializer()
            {
                Status         = status,
                ActionName     = actionName,
                Data           = data,
                ResponseErrors = new ErrorSerializer[errors.Count()]
            };

            int index = 0;

            foreach (var error in errors)
            {
                result.ResponseErrors[index] = ErrorSerializer.CreateInstance(error.ErrorCode, error.ErrorMessage);

                index++;
            }

            return(result);
        }
Exemplo n.º 11
0
        public void SerializeError_serializes_httperror()
        {
            using (var stream = new MemoryStream())
            {
                var textWriter = new StreamWriter(stream);
                var writer     = new JsonTextWriter(textWriter);
                var error      = new HttpError(new Exception("This is the exception message!"), true)
                {
                    StackTrace = "Stack trace would go here"
                };
                var jsonSerializer = new JsonSerializer();

                var serializer = new ErrorSerializer(new TestErrorIdProvider());
                serializer.SerializeError(error, stream, writer, jsonSerializer);

                writer.Flush();

                var expectedJson         = File.ReadAllText("ErrorSerializerTest.json");
                var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
                var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
                output.Should().Be(minifiedExpectedJson);
            }
        }
Exemplo n.º 12
0
        public bool GetBoolResponse(string method_name, params FacebookParam[] parameters)
        {
            string url = FormatGetUrl(method_name, parameters);

            byte[] response_bytes = GetResponseBytes(url);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(Encoding.Default.GetString(response_bytes));

            try {
                return(System.Convert.ToBoolean(Int32.Parse(doc.InnerText)));
            }
            catch (FormatException e) {
                Error error;
                try {
                    error = (Error)ErrorSerializer.Deserialize(new MemoryStream(response_bytes));
                } catch {
                    Console.Error.WriteLine("Parse error: Inner text was '{0}'", doc.InnerText);
                    throw e;
                }
                throw new FacebookException(error.ErrorCode, error.ErrorMsg);
            }
        }
Exemplo n.º 13
0
        internal Photo Upload(long aid, string caption, string path, string session_key)
        {
            // check for file
            FileInfo file = new FileInfo(path);

            if (!file.Exists)
            {
                throw new FileNotFoundException("Upload file not found", path);
            }

            // create parameter string
            List <FacebookParam> parameter_list = new List <FacebookParam>();

            parameter_list.Add(FacebookParam.Create("call_id", DateTime.Now.Ticks));
            parameter_list.Add(FacebookParam.Create("session_key", session_key));
            parameter_list.Add(FacebookParam.Create("aid", aid));

            if (caption != null && caption != string.Empty)
            {
                parameter_list.Add(FacebookParam.Create("caption", caption));
            }

            FacebookParam[] param_array  = Sign("facebook.photos.upload", parameter_list.ToArray());
            string          param_string = string.Empty;

            foreach (FacebookParam param in param_array)
            {
                param_string = param_string + "--" + BOUNDARY + LINE;
                param_string = param_string + "Content-Disposition: form-data; name=\"" + param.Name + "\"" + LINE + LINE + param.Value + LINE;
            }

            param_string = param_string + "--" + BOUNDARY + LINE
                           + "Content-Disposition: form-data; name=\"filename\"; filename=\"" + file.Name + "\"" + LINE
                           + "Content-Type: image/jpeg" + LINE + LINE;

            string closing_string = LINE + "--" + BOUNDARY + "--";

            // get bytes
            byte[] param_bytes   = System.Text.Encoding.Default.GetBytes(param_string);
            byte[] closing_bytes = System.Text.Encoding.Default.GetBytes(closing_string);

            byte[] file_bytes = System.IO.File.ReadAllBytes(path);

            // compose
            List <byte> byte_list = new List <byte>(param_bytes.Length + file_bytes.Length + closing_bytes.Length);

            byte_list.AddRange(param_bytes);
            byte_list.AddRange(file_bytes);
            byte_list.AddRange(closing_bytes);

            byte[] final_bytes = new byte[byte_list.Count];
            byte_list.CopyTo(final_bytes);

            // create request
            WebClient wc = new WebClient();

            wc.Headers.Set("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            wc.Headers.Add("MIME-version", "1.0");

            // upload
            byte[] response = wc.UploadData("http://api.facebook.com/restserver.php?", "POST", final_bytes);

            // deserialize
            XmlSerializer photo_serializer = new XmlSerializer(typeof(Photo));

            try {
                return((Photo)photo_serializer.Deserialize(new MemoryStream(response)));
            }
            catch {
                Error error = (Error)ErrorSerializer.Deserialize(new MemoryStream(response));
                throw new FacebookException(error.ErrorCode, error.ErrorMsg);
            }
        }