public static string Serialize(ReleaseChangeSet changeSet)
 {
     return(TypeSerializer.SerializeToString(changeSet));
 }
示例#2
0
        public static string ToString(INameValueCollection nvc)
        {
            var map = ToDictionary(nvc);

            return(TypeSerializer.SerializeToString(map));
        }
示例#3
0
        public static GetMemberDelegate CreateTypeConverter(Type fromType, Type toType)
        {
            if (fromType == toType)
            {
                return(null);
            }

            var converter = AutoMappingUtils.GetConverter(fromType, toType);

            if (converter != null)
            {
                return(converter);
            }

            if (fromType == typeof(string))
            {
                return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType));
            }

            if (toType == typeof(string))
            {
                return(o => TypeSerializer.SerializeToString(o).StripQuotes());
            }

            var underlyingToType   = Nullable.GetUnderlyingType(toType) ?? toType;
            var underlyingFromType = Nullable.GetUnderlyingType(fromType) ?? fromType;

            if (underlyingToType.IsEnum)
            {
                if (underlyingFromType.IsEnum || fromType == typeof(string))
                {
                    return(fromValue => Enum.Parse(underlyingToType, fromValue.ToString(), ignoreCase: true));
                }

                if (underlyingFromType.IsIntegerType())
                {
                    return(fromValue => Enum.ToObject(underlyingToType, fromValue));
                }
            }
            else if (underlyingFromType.IsEnum)
            {
                if (underlyingToType.IsIntegerType())
                {
                    return(fromValue => Convert.ChangeType(fromValue, underlyingToType, null));
                }
            }
            else if (typeof(IEnumerable).IsAssignableFrom(fromType))
            {
                return(fromValue =>
                {
                    var listResult = TranslateListWithElements.TryTranslateCollections(
                        fromType, underlyingToType, fromValue);

                    return listResult ?? fromValue;
                });
            }
            else if (underlyingToType.IsValueType)
            {
                return(fromValue => AutoMappingUtils.ChangeValueType(fromValue, underlyingToType));
            }
            else
            {
                return(fromValue =>
                {
                    if (fromValue == null)
                    {
                        return fromValue;
                    }

                    var toValue = toType.CreateInstance();
                    toValue.PopulateWith(fromValue);
                    return toValue;
                });
            }

            return(null);
        }
示例#4
0
        public void DateTimeKind_Does_Not_Change_With_SkipDateTimeConversion_true()
        {
            JsConfig.DateHandler            = DateHandler.ISO8601;
            JsConfig.SkipDateTimeConversion = true;
            string     serilizedResult;
            TestObject deserilizedResult;

            var testObject = new TestObject
            {
                Date = new DateTime(2013, 1, 1, 0, 0, 1, DateTimeKind.Utc)
            };

            serilizedResult   = TypeSerializer.SerializeToString <TestObject>(testObject);
            deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult);
            Assert.AreEqual(deserilizedResult.Date, testObject.Date);
            Assert.AreEqual(DateTimeKind.Utc, deserilizedResult.Date.Kind);

            using (JsConfig.With(skipDateTimeConversion: false))
            {
                Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }

            testObject = new TestObject
            {
                Date = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            };
            serilizedResult   = TypeSerializer.SerializeToString <TestObject>(testObject);
            deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult);
            Assert.AreEqual(deserilizedResult.Date, testObject.Date);
            Assert.AreEqual(DateTimeKind.Utc, deserilizedResult.Date.Kind);

            using (JsConfig.With(skipDateTimeConversion: false))
            {
                Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }
            using (JsConfig.With(alwaysUseUtc: true, skipDateTimeConversion: false)) //It will work now
            {
                Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }

            //make sure it still keeps local local
            testObject = new TestObject
            {
                Date = new DateTime(2013, 1, 2, 0, 2, 0, DateTimeKind.Local)
            };
            serilizedResult   = TypeSerializer.SerializeToString <TestObject>(testObject);
            deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult);
            Assert.AreEqual(deserilizedResult.Date, testObject.Date);
            Assert.AreEqual(DateTimeKind.Local, deserilizedResult.Date.Kind);

            using (JsConfig.With(alwaysUseUtc: true))
            {
                Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }
            using (JsConfig.With(alwaysUseUtc: true, skipDateTimeConversion: false))
            {
                Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }


            testObject = new TestObject
            {
                Date = new DateTime(2013, 1, 2, 0, 2, 0, DateTimeKind.Unspecified)
            };
            serilizedResult   = TypeSerializer.SerializeToString <TestObject>(testObject);
            deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult);
            Assert.AreEqual(deserilizedResult.Date, testObject.Date);
            Assert.AreEqual(DateTimeKind.Unspecified, deserilizedResult.Date.Kind);

            using (JsConfig.With(alwaysUseUtc: true))
            {
                Assert.AreEqual(DateTimeKind.Unspecified, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }
            using (JsConfig.With(alwaysUseUtc: true, skipDateTimeConversion: false))
            {
                Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }

            using (JsConfig.With(skipDateTimeConversion: false))
            {
                serilizedResult   = TypeSerializer.SerializeToString <TestObject>(testObject);
                deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult);
                Assert.AreEqual(DateTimeKind.Local, deserilizedResult.Date.Kind);
            }
        }
示例#5
0
        public void Populate(object to, object from,
                             Func <PropertyInfo, bool> propertyInfoPredicate,
                             Func <object, Type, bool> valuePredicate)
        {
            foreach (var assignmentEntry in AssignmentMemberMap)
            {
                var assignmentMember = assignmentEntry.Value;
                var fromMember       = assignmentEntry.Value.From;
                var toMember         = assignmentEntry.Value.To;

                if (fromMember.PropertyInfo != null && propertyInfoPredicate != null)
                {
                    if (!propertyInfoPredicate(fromMember.PropertyInfo))
                    {
                        continue;
                    }
                }

                try
                {
                    var fromValue = assignmentMember.GetValueFn(from);

                    if (valuePredicate != null)
                    {
                        if (!valuePredicate(fromValue, fromMember.PropertyInfo.PropertyType))
                        {
                            continue;
                        }
                    }

                    if (fromMember.Type != toMember.Type)
                    {
                        if (fromMember.Type == typeof(string))
                        {
                            fromValue = TypeSerializer.DeserializeFromString((string)fromValue, toMember.Type);
                        }
                        else if (toMember.Type == typeof(string))
                        {
                            fromValue = TypeSerializer.SerializeToString(fromValue);
                        }
                        else if (toMember.Type.IsGeneric() &&
                                 toMember.Type.GenericTypeDefinition() == typeof(Nullable <>))
                        {
                            Type genericArg = toMember.Type.GenericTypeArguments()[0];
                            if (genericArg.IsEnum())
                            {
                                fromValue = Enum.ToObject(genericArg, fromValue);
                            }
                        }
                        else
                        {
                            var listResult = TranslateListWithElements.TryTranslateToGenericICollection(
                                fromMember.Type, toMember.Type, fromValue);

                            if (listResult != null)
                            {
                                fromValue = listResult;
                            }
                        }
                    }

                    var setterFn = assignmentMember.SetValueFn;
                    setterFn(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set properties {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromMember.Type.Name,
                                           ToType.FullName, toMember.Type.Name), ex);
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            var httpReq = new HttpRequestWrapper("NotFoundHttpHandler", request);

            if (!request.IsLocal)
            {
                ProcessRequest(httpReq, new HttpResponseWrapper(response), null);
                return;
            }

            Log.ErrorFormat("{0} Request not found: {1}", request.UserHostAddress, request.RawUrl);

            var sb = new StringBuilder();

            sb.AppendLine("Handler for Request not found: \n\n");

            sb.AppendLine("Request.ApplicationPath: " + request.ApplicationPath);
            sb.AppendLine("Request.CurrentExecutionFilePath: " + request.CurrentExecutionFilePath);
            sb.AppendLine("Request.FilePath: " + request.FilePath);
            sb.AppendLine("Request.HttpMethod: " + request.HttpMethod);
            sb.AppendLine("Request.MapPath('~'): " + request.MapPath("~"));
            sb.AppendLine("Request.Path: " + request.Path);
            sb.AppendLine("Request.PathInfo: " + request.PathInfo);
            sb.AppendLine("Request.ResolvedPathInfo: " + httpReq.PathInfo);
            sb.AppendLine("Request.PhysicalPath: " + request.PhysicalPath);
            sb.AppendLine("Request.PhysicalApplicationPath: " + request.PhysicalApplicationPath);
            sb.AppendLine("Request.QueryString: " + request.QueryString);
            sb.AppendLine("Request.RawUrl: " + request.RawUrl);
            try
            {
                sb.AppendLine("Request.Url.AbsoluteUri: " + request.Url.AbsoluteUri);
                sb.AppendLine("Request.Url.AbsolutePath: " + request.Url.AbsolutePath);
                sb.AppendLine("Request.Url.Fragment: " + request.Url.Fragment);
                sb.AppendLine("Request.Url.Host: " + request.Url.Host);
                sb.AppendLine("Request.Url.LocalPath: " + request.Url.LocalPath);
                sb.AppendLine("Request.Url.Port: " + request.Url.Port);
                sb.AppendLine("Request.Url.Query: " + request.Url.Query);
                sb.AppendLine("Request.Url.Scheme: " + request.Url.Scheme);
                sb.AppendLine("Request.Url.Segments: " + request.Url.Segments);
            }
            catch (Exception ex)
            {
                sb.AppendLine("Request.Url ERROR: " + ex.Message);
            }
            if (IsIntegratedPipeline.HasValue)
            {
                sb.AppendLine("App.IsIntegratedPipeline: " + IsIntegratedPipeline);
            }
            if (!WebHostPhysicalPath.IsNullOrEmpty())
            {
                sb.AppendLine("App.WebHostPhysicalPath: " + WebHostPhysicalPath);
            }
            if (!WebHostRootFileNames.IsEmpty())
            {
                sb.AppendLine("App.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
            }
            if (!ApplicationBaseUrl.IsNullOrEmpty())
            {
                sb.AppendLine("App.ApplicationBaseUrl: " + ApplicationBaseUrl);
            }
            if (!DefaultRootFileName.IsNullOrEmpty())
            {
                sb.AppendLine("App.DefaultRootFileName: " + DefaultRootFileName);
            }
            if (!DefaultHandler.IsNullOrEmpty())
            {
                sb.AppendLine("App.DefaultHandler: " + DefaultHandler);
            }
            if (!ServiceStackHttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
            {
                sb.AppendLine("App.DebugLastHandlerArgs: " + ServiceStackHttpHandlerFactory.DebugLastHandlerArgs);
            }

            response.ContentType = "text/plain";
            response.StatusCode  = 404;
            response.Write(sb.ToString());

            //Apache+mod_mono doesn't like this
            //response.OutputStream.Flush();
            //response.Close();
        }
        public void DeleteRelatedEntity <TChild>(object parentId, object childId)
        {
            var childRefKey = GetChildReferenceSetKey <TChild>(parentId);

            client.RemoveItemFromSet(childRefKey, TypeSerializer.SerializeToString(childId));
        }
示例#8
0
        public static void LogRequest(this IHttpResponse response, IHttpRequest request, int?statusCode = null)
        {
            try
            {
                if (!EndpointHost.Config.MetadataMap[request.ServicePath].LogCommonRequestInfo)
                {
                    return;
                }

                Dictionary <string, string> additionalInfo = new Dictionary <string, string>()
                {
                    { "ClientIP", request.RemoteIp },
                    { "AbsolutePath", request.GetAbsolutePath() },
                    { "HostAddress", request.GetUrlHostName() },
                    { "ResponseStatus", (statusCode ?? (response.StatusCode <= 0 ? 200 : response.StatusCode)).ToString() }
                };

                string requestType = EndpointHost.Config.MetadataMap[request.ServicePath].FullServiceName;
                if (!string.IsNullOrWhiteSpace(request.OperationName))
                {
                    requestType += "." + request.OperationName;
                }
                additionalInfo["RequestType"] = requestType;

                string appId = request.Headers[ServiceUtils.AppIdHttpHeaderKey];
                if (!string.IsNullOrWhiteSpace(appId))
                {
                    additionalInfo["ClientAppId"] = appId;
                }

                if (request.RequestObject != null && request.RequestObject is IHasMobileRequestHead)
                {
                    IHasMobileRequestHead h5Request = request.RequestObject as IHasMobileRequestHead;
                    if (h5Request.head != null)
                    {
                        Dictionary <string, string> extension = null;
                        if (EndpointHost.Config.MetadataMap[request.ServicePath].LogH5HeadExtensionData)
                        {
                            extension = new Dictionary <string, string>();
                            foreach (ExtensionFieldType item in h5Request.head.extension)
                            {
                                if (!string.IsNullOrWhiteSpace(item.name) &&
                                    item.name != ServiceUtils.MobileUserIdExtensionKey && item.name != ServiceUtils.MobileAuthTokenExtensionKey)
                                {
                                    extension[item.name] = item.value;
                                }
                            }

                            if (extension.Count == 0)
                            {
                                extension = null;
                            }
                        }
                        additionalInfo["H5Head"] = TypeSerializer.SerializeToString(
                            new
                        {
                            ClientID      = h5Request.head.cid,
                            ClientToken   = h5Request.head.ctok,
                            ClientVersion = h5Request.head.cver,
                            SystemCode    = h5Request.head.syscode,
                            SourceID      = h5Request.head.sid,
                            Language      = h5Request.head.lang,
                            Extension     = extension
                        });
                    }
                }
            }
            catch { }
        }
 /// <summary>Runs this object.</summary>
 public override void Run()
 {
     TypeSerializer.SerializeToString(customer);
 }
示例#10
0
        internal static void LogError(string title, IHttpRequest httpRequest, Exception ex, string errorCode, LogLevel logLevel)
        {
            if (httpRequest == null)
            {
                return;
            }

            ServiceMetadata             metadata = EndpointHost.Config.MetadataMap[httpRequest.ServicePath];
            Dictionary <string, string> additionalExceptionInfo = new Dictionary <string, string>()
            {
                { "Operation", metadata.FullServiceName + "." + httpRequest.OperationName }
            };

            string clientAppId = httpRequest.GetClientAppId();

            if (!string.IsNullOrWhiteSpace(clientAppId))
            {
                additionalExceptionInfo.Add("ClientAppId", clientAppId);
            }

            if (!string.IsNullOrWhiteSpace(errorCode))
            {
                additionalExceptionInfo.Add("ErrorCode", errorCode);
            }

            if (metadata.LogErrorWithRequestInfo)
            {
                try
                {
                    try
                    {
                        var requestInfo = RequestInfoHandler.GetRequestInfo(httpRequest);
                        additionalExceptionInfo["RequestInfo"] = TypeSerializer.SerializeToString(requestInfo);
                    }
                    catch
                    {
                        Dictionary <string, string> requestInfo = new Dictionary <string, string>()
                        {
                            { "Url", httpRequest.RawUrl },
                            { "PathInfo", httpRequest.PathInfo },
                            { "QueryString", TypeSerializer.SerializeToString(httpRequest.QueryString) },
                            { "Headers", TypeSerializer.SerializeToString(httpRequest.Headers) },
                            { "FormData", TypeSerializer.SerializeToString(httpRequest.FormData) }
                        };
                        additionalExceptionInfo["RequestInfo"] = TypeSerializer.SerializeToString(requestInfo);
                    }
                }
                catch
                {
                }

                if (httpRequest.RequestObject != null && !(httpRequest.RequestObject is RequestInfoResponse))
                {
                    additionalExceptionInfo["RequestObject"] = TypeSerializer.SerializeToString(httpRequest.RequestObject);
                }
            }

            switch (logLevel)
            {
            case LogLevel.DEBUG:
                if (ex != null)
                {
                    Log.Error(title, ex, additionalExceptionInfo);
                }
                else
                {
                    Log.Error(title, string.Empty, additionalExceptionInfo);
                }
                break;

            case LogLevel.INFO:
                if (ex != null)
                {
                    Log.Info(title, ex, additionalExceptionInfo);
                }
                else
                {
                    Log.Info(title, string.Empty, additionalExceptionInfo);
                }
                break;

            case LogLevel.WARN:
                if (ex != null)
                {
                    Log.Warn(title, ex, additionalExceptionInfo);
                }
                else
                {
                    Log.Warn(title, string.Empty, additionalExceptionInfo);
                }
                break;

            case LogLevel.ERROR:
                if (ex != null)
                {
                    Log.Error(title, ex, additionalExceptionInfo);
                }
                else
                {
                    Log.Error(title, string.Empty, additionalExceptionInfo);
                }
                break;

            case LogLevel.FATAL:
                if (ex != null)
                {
                    Log.Fatal(title, ex, additionalExceptionInfo);
                }
                else
                {
                    Log.Fatal(title, string.Empty, additionalExceptionInfo);
                }
                break;
            }
        }
示例#11
0
        internal static void LogError(string title, IHttpRequest httpRequest, ResponseStatusType responseStatus, string errorCode, LogLevel logLevel)
        {
            if (httpRequest == null)
            {
                return;
            }

            ServiceMetadata             metadata = EndpointHost.Config.MetadataMap[httpRequest.ServicePath];
            Dictionary <string, string> additionalExceptionInfo = new Dictionary <string, string>()
            {
                { "Version", ServiceUtils.SOA2VersionCatName },
                { "Operation", metadata.FullServiceName + "." + httpRequest.OperationName }
            };

            string clientAppId = httpRequest.GetClientAppId();

            if (!string.IsNullOrWhiteSpace(clientAppId))
            {
                additionalExceptionInfo.Add("ClientAppId", clientAppId);
            }

            if (!string.IsNullOrWhiteSpace(errorCode))
            {
                additionalExceptionInfo.Add("ErrorCode", errorCode);
            }

            if (metadata.LogErrorWithRequestInfo)
            {
                try
                {
                    try
                    {
                        var requestInfo = RequestInfoHandler.GetRequestInfo(httpRequest);
                        additionalExceptionInfo["RequestInfo"] = TypeSerializer.SerializeToString(requestInfo);
                    }
                    catch
                    {
                        Dictionary <string, string> requestInfo = new Dictionary <string, string>()
                        {
                            { "Url", httpRequest.RawUrl },
                            { "PathInfo", httpRequest.PathInfo },
                            { "QueryString", TypeSerializer.SerializeToString(httpRequest.QueryString) },
                            { "Headers", TypeSerializer.SerializeToString(httpRequest.Headers) },
                            { "FormData", TypeSerializer.SerializeToString(httpRequest.FormData) }
                        };
                        additionalExceptionInfo["RequestInfo"] = TypeSerializer.SerializeToString(requestInfo);
                    }
                }
                catch
                {
                }

                if (httpRequest.RequestObject != null && !(httpRequest.RequestObject is RequestInfoResponse))
                {
                    additionalExceptionInfo["RequestObject"] = TypeSerializer.SerializeToString(httpRequest.RequestObject);
                }
            }

            string message = string.Empty;

            if (responseStatus != null)
            {
                additionalExceptionInfo["ResponseStatus"] = TypeSerializer.SerializeToString(responseStatus);
                if (responseStatus.Errors != null && responseStatus.Errors.Count > 0 && responseStatus.Errors[0] != null)
                {
                    message = string.Format("ErrorCode: {0}, Message: {1}", responseStatus.Errors[0].ErrorCode, responseStatus.Errors[0].Message);
                }
            }

            switch (logLevel)
            {
            case LogLevel.DEBUG:
                Log.Debug(title, message, additionalExceptionInfo);
                break;

            case LogLevel.INFO:
                Log.Info(title, message, additionalExceptionInfo);
                break;

            case LogLevel.WARN:
                Log.Warn(title, message, additionalExceptionInfo);
                break;

            case LogLevel.ERROR:
                Log.Error(title, message, additionalExceptionInfo);
                break;

            case LogLevel.FATAL:
                Log.Fatal(title, message, additionalExceptionInfo);
                break;
            }
        }
示例#12
0
        public void Populate(object to, object from,
                             Func <PropertyInfo, bool> propertyInfoPredicate,
                             Func <object, bool> valuePredicate)
        {
            foreach (var propertyEntry in PropertyInfoMap)
            {
                var fromPropertyInfo = propertyEntry.Key;
                var toPropertyInfo   = propertyEntry.Value;

                if (propertyInfoPredicate != null)
                {
                    if (!propertyInfoPredicate(fromPropertyInfo))
                    {
                        continue;
                    }
                }

                try
                {
                    var fromValue = fromPropertyInfo.GetValue(from, new object[] { });

                    if (valuePredicate != null)
                    {
                        if (!valuePredicate(fromValue))
                        {
                            continue;
                        }
                    }

                    if (fromPropertyInfo.PropertyType != toPropertyInfo.PropertyType)
                    {
                        if (fromPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.DeserializeFromString((string)fromValue,
                                                                             toPropertyInfo.PropertyType);
                        }
                        else if (toPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.SerializeToString(fromValue);
                        }
                        else
                        {
                            var listResult = TranslateListWithElements.TryTranslateToGenericICollection(
                                fromPropertyInfo.PropertyType, toPropertyInfo.PropertyType, fromValue);

                            if (listResult != null)
                            {
                                fromValue = listResult;
                            }
                        }
                    }

                    var toSetMetodInfo = toPropertyInfo.GetSetMethod();
                    toSetMetodInfo.Invoke(to, new[] { fromValue });
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("Error trying to set properties {0}.{1} > {2}.{3}",
                                            FromType.FullName, fromPropertyInfo.Name,
                                            ToType.FullName, toPropertyInfo.Name), ex);
                }
            }

            foreach (var fieldEntry in FieldInfoMap)
            {
                var fromFieldInfo = fieldEntry.Key;
                var toFieldInfo   = fieldEntry.Value;

                try
                {
                    var fromValue = fromFieldInfo.GetValue(from);
                    toFieldInfo.SetValue(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("Error trying to set fields {0}.{1} > {2}.{3}",
                                            FromType.FullName, fromFieldInfo.Name,
                                            ToType.FullName, toFieldInfo.Name), ex);
                }
            }
        }
示例#13
0
 public static string GenerateHash(this object obj)
 {
     using var md5Hash = MD5.Create();
     return(GetMd5Hash(md5Hash, TypeSerializer.SerializeToString(obj)));
 }
示例#14
0
 public static bool VerifyMd5Hash(this object obj, string hash)
 {
     using var md5Hash = MD5.Create();
     return(0 == StringComparer.OrdinalIgnoreCase.Compare(GetMd5Hash(md5Hash, TypeSerializer.SerializeToString(obj)), hash));
 }
示例#15
0
        public static ResponseStatus CreateResponseStatus(Exception ex, object request = null, bool debugMode = false)
        {
            var e = ex.UnwrapIfSingleException();

            var responseStatus = (e is IResponseStatusConvertible customStatus
                ? customStatus.ToResponseStatus()
                : null) ?? ResponseStatusUtils.CreateResponseStatus(e.GetType().Name, e.Message);

            if (responseStatus == null)
            {
                return(null);
            }

            if (debugMode)
            {
#if !NETSTANDARD2_0
                if (ex is System.Web.HttpCompileException compileEx && compileEx.Results.Errors.HasErrors)
                {
                    responseStatus.Errors ??= new List <ResponseError>();
                    foreach (var err in compileEx.Results.Errors)
                    {
                        responseStatus.Errors.Add(new ResponseError {
                            Message = err.ToString()
                        });
                    }
                }
#endif
                // View stack trace in tests and on the client
                var sb = StringBuilderCache.Allocate();

                if (request != null)
                {
                    try
                    {
                        var str = $"[{request.GetType().GetOperationName()}: {DateTime.UtcNow}]:\n[REQUEST: {TypeSerializer.SerializeToString(request)}]";
                        sb.AppendLine(str);
                    }
                    catch (Exception requestEx)
                    {
                        sb.AppendLine($"[{request.GetType().GetOperationName()}: {DateTime.UtcNow}]:\n[REQUEST: {requestEx.Message}]");
                    }
                }

                sb.AppendLine(e.ToString());

                var innerMessages = new List <string>();
                var innerEx       = e.InnerException;
                while (innerEx != null)
                {
                    sb.AppendLine("");
                    sb.AppendLine(innerEx.ToString());
                    innerMessages.Add(innerEx.Message);
                    innerEx = innerEx.InnerException;
                }

                responseStatus.StackTrace = StringBuilderCache.ReturnAndFree(sb);
                if (innerMessages.Count > 0)
                {
                    responseStatus.Meta ??= new Dictionary <string, string>();
                    responseStatus.Meta["InnerMessages"] = innerMessages.Join("\n");
                }
            }

            return(responseStatus);
        }
示例#16
0
        protected void SerializeDto <T>(T dto)
        {
            TestResults = new List <SerializersBenchmarkEntry>();
            FixtureTestResults.Add(TestResults);
            this.ModelName = typeof(T).IsGenericType &&
                             typeof(T).GetGenericTypeDefinition() == typeof(List <>)
                                ? typeof(T).GetGenericArguments()[0].Name
                                : typeof(T).Name;

            if (!OnlyRunServiceStackSerializers)
            {
                var dtoMsXml = DataContractSerializer.Instance.Parse(dto);
                RecordRunResults("Microsoft DataContractSerializer", dtoMsXml,
                                 () => DataContractSerializer.Instance.Parse(dto),
                                 () => DataContractDeserializer.Instance.Parse <T>(dtoMsXml)
                                 );

                var dtoMsJson = JsonDataContractSerializer.Instance.Parse(dto);
                RecordRunResults("Microsoft JsonDataContractSerializer", dtoMsJson,
                                 () => JsonDataContractSerializer.Instance.Parse(dto),
                                 () => JsonDataContractDeserializer.Instance.Parse <T>(dtoMsJson)
                                 );

                if (this.MultipleIterations.Sum() <= 10)
                {
                    //To slow to include, up to 280x slower than ProtoBuf
                    var js    = new JavaScriptSerializer();
                    var dtoJs = js.Serialize(dto);
                    RecordRunResults("Microsoft JavaScriptSerializer", dtoJs,
                                     () => js.Serialize(dto),
                                     () => js.Deserialize <T>(dtoJs)
                                     );

                    //Can't import complex types, e.g. Lists, etc
                    //var jayRockString = Jayrock.Json.Conversion.JsonConvert.ExportToString(dto);
                    //RecordRunResults("JayRock JsonConvert", jayRockString,
                    //    () => Jayrock.Json.Conversion.JsonConvert.ExportToString(dto),
                    //    () => Jayrock.Json.Conversion.JsonConvert.Import(typeof(T), jayRockString)
                    //);
                }

                var msBytes = BinaryFormatterSerializer.Instance.Serialize(dto);
                RecordRunResults("Microsoft BinaryFormatter", msBytes,
                                 () => BinaryFormatterSerializer.Instance.Serialize(dto),
                                 () => BinaryFormatterDeserializer.Instance.Deserialize <T>(msBytes)
                                 );

                var dtoJsonNet = JsonConvert.SerializeObject(dto);
                RecordRunResults("NewtonSoft.Json", dtoJsonNet,
                                 () => JsonConvert.SerializeObject(dto),
                                 () => JsonConvert.DeserializeObject <T>(dtoJsonNet)
                                 );

                //var dtoLitJson = JsonMapper.ToJson(dto);
                //RecordRunResults("LitJson", dtoJsonNet,
                //    () => JsonMapper.ToJson(dto),
                //    () => JsonMapper.ToObject<T>(dtoLitJson)
                //);

                var dtoProtoBuf = ProtoBufToBytes(dto);
                RecordRunResults("ProtoBuf.net", dtoProtoBuf,
                                 () => ProtoBufToBytes(dto),
                                 () => ProtoBufFromBytes <T>(dtoProtoBuf)
                                 );
            }

            var dtoJsv = TypeSerializer.SerializeToString(dto);

            RecordRunResults("ServiceStack TypeSerializer", dtoJsv,
                             () => TypeSerializer.SerializeToString(dto),
                             () => TypeSerializer.DeserializeFromString <T>(dtoJsv)
                             );

            var dtoJson = ServiceStack.Text.JsonSerializer.SerializeToString(dto);

            RecordRunResults("ServiceStack JsonSerializer", dtoJson,
                             () => ServiceStack.Text.JsonSerializer.SerializeToString(dto),
                             () => ServiceStack.Text.JsonSerializer.DeserializeFromString <T>(dtoJson)
                             );

            //Propietary library, not freely available.
            //var dtoPlatformText = TextSerializer.SerializeToString(dto);
            //RecordRunResults("Platform TextSerializer", dtoPlatformText,
            //    () => TextSerializer.SerializeToString(dto),
            //    () => TextSerializer.DeserializeFromString<T>(dtoPlatformText)
            //);

            CalculateBestTimes(TestResults);
        }
示例#17
0
 public string SerializeToString <TFrom>(TFrom @from)
 {
     return(TypeSerializer.SerializeToString(@from));
 }
        public void Populate(object to, object from,
                             Func <PropertyInfo, bool> propertyInfoPredicate,
                             Func <object, bool> valuePredicate)
        {
            foreach (var propertyEntry in PropertyInfoMap)
            {
                var fromPropertyInfo = propertyEntry.Key;
                var toPropertyInfo   = propertyEntry.Value;

                if (propertyInfoPredicate != null)
                {
                    if (!propertyInfoPredicate(fromPropertyInfo))
                    {
                        continue;
                    }
                }

                try
                {
                    var getterFn = PropertyGetters.GetOrAdd(fromPropertyInfo.Name,
                                                            fromPropertyInfo.GetPropertyGetterFn());
                    var fromValue = getterFn(from);

                    if (valuePredicate != null)
                    {
                        if (!valuePredicate(fromValue))
                        {
                            continue;
                        }
                    }

                    if (fromPropertyInfo.PropertyType != toPropertyInfo.PropertyType)
                    {
                        if (fromPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.DeserializeFromString((string)fromValue,
                                                                             toPropertyInfo.PropertyType);
                        }
                        else if (toPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.SerializeToString(fromValue);
                        }
                        else if (toPropertyInfo.PropertyType.IsGenericType &&
                                 toPropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                        {
                            Type genericArg = toPropertyInfo.PropertyType.GetGenericArguments()[0];
                            if (genericArg.IsEnum)
                            {
                                fromValue = Enum.ToObject(genericArg, fromValue);
                            }
                        }
                        else
                        {
                            var listResult = TranslateListWithElements.TryTranslateToGenericICollection(
                                fromPropertyInfo.PropertyType, toPropertyInfo.PropertyType, fromValue);

                            if (listResult != null)
                            {
                                fromValue = listResult;
                            }
                        }
                    }

                    var setterFn = PropertySetters.GetOrAdd(toPropertyInfo.Name,
                                                            toPropertyInfo.GetPropertySetterFn());

                    setterFn(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set properties {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromPropertyInfo.Name,
                                           ToType.FullName, toPropertyInfo.Name), ex);
                }
            }

            foreach (var fieldEntry in FieldInfoMap)
            {
                var fromFieldInfo = fieldEntry.Key;
                var toFieldInfo   = fieldEntry.Value;

                try
                {
                    var fromValue = fromFieldInfo.GetValue(from);
                    toFieldInfo.SetValue(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set fields {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromFieldInfo.Name,
                                           ToType.FullName, toFieldInfo.Name), ex);
                }
            }
        }
示例#19
0
        public override void ProcessRequest(HttpContextBase context)
        {
            var request  = context.Request;
            var response = context.Response;

            var httpReq = context.ToRequest(GetType().GetOperationName());

            if (!request.IsLocal)
            {
                ProcessRequestAsync(httpReq, httpReq.Response, null);
                return;
            }

            Log.ErrorFormat("{0} Request not found: {1}", request.UserHostAddress, request.RawUrl);

            var sb = new StringBuilder();

            sb.AppendLine("Handler for Request not found: \n\n");

            sb.AppendLine("Request.ApplicationPath: " + request.ApplicationPath);
            sb.AppendLine("Request.CurrentExecutionFilePath: " + request.CurrentExecutionFilePath);
            sb.AppendLine("Request.FilePath: " + request.FilePath);
            sb.AppendLine("Request.HttpMethod: " + request.HttpMethod);
            sb.AppendLine("Request.MapPath('~'): " + request.MapPath("~"));
            sb.AppendLine("Request.Path: " + request.Path);
            sb.AppendLine("Request.PathInfo: " + request.PathInfo);
            sb.AppendLine("Request.ResolvedPathInfo: " + httpReq.PathInfo);
            sb.AppendLine("Request.PhysicalPath: " + request.PhysicalPath);
            sb.AppendLine("Request.PhysicalApplicationPath: " + request.PhysicalApplicationPath);
            sb.AppendLine("Request.QueryString: " + request.QueryString);
            sb.AppendLine("Request.RawUrl: " + request.RawUrl);
            try
            {
                sb.AppendLine("Request.Url.AbsoluteUri: " + request.Url.AbsoluteUri);
                sb.AppendLine("Request.Url.AbsolutePath: " + request.Url.AbsolutePath);
                sb.AppendLine("Request.Url.Fragment: " + request.Url.Fragment);
                sb.AppendLine("Request.Url.Host: " + request.Url.Host);
                sb.AppendLine("Request.Url.LocalPath: " + request.Url.LocalPath);
                sb.AppendLine("Request.Url.Port: " + request.Url.Port);
                sb.AppendLine("Request.Url.Query: " + request.Url.Query);
                sb.AppendLine("Request.Url.Scheme: " + request.Url.Scheme);
                sb.AppendLine("Request.Url.Segments: " + request.Url.Segments);
            }
            catch (Exception ex)
            {
                sb.AppendLine("Request.Url ERROR: " + ex.Message);
            }
            if (IsIntegratedPipeline.HasValue)
            {
                sb.AppendLine("App.IsIntegratedPipeline: " + IsIntegratedPipeline);
            }
            if (!WebHostPhysicalPath.IsNullOrEmpty())
            {
                sb.AppendLine("App.WebHostPhysicalPath: " + WebHostPhysicalPath);
            }
            if (!WebHostRootFileNames.IsEmpty())
            {
                sb.AppendLine("App.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
            }
            if (!WebHostUrl.IsNullOrEmpty())
            {
                sb.AppendLine("App.ApplicationBaseUrl: " + WebHostUrl);
            }
            if (!DefaultRootFileName.IsNullOrEmpty())
            {
                sb.AppendLine("App.DefaultRootFileName: " + DefaultRootFileName);
            }
            if (!DefaultHandler.IsNullOrEmpty())
            {
                sb.AppendLine("App.DefaultHandler: " + DefaultHandler);
            }
            if (!HttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
            {
                sb.AppendLine("App.DebugLastHandlerArgs: " + HttpHandlerFactory.DebugLastHandlerArgs);
            }

            response.ContentType = "text/plain";
            response.StatusCode  = 404;
            response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r => r.Write(sb.ToString()));
        }
示例#20
0
        public string SerializeToString(IRequest req, object response)
        {
            var contentType = req.ResponseContentType;

            StreamSerializerDelegate responseStreamWriter;

            if (this.ContentTypeSerializers.TryGetValue(contentType, out responseStreamWriter) ||
                this.ContentTypeSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseStreamWriter))
            {
                using (var ms = new MemoryStream())
                {
                    responseStreamWriter(req, response, ms);

                    ms.Position = 0;
                    var result = new StreamReader(ms, UTF8EncodingWithoutBom).ReadToEnd();
                    return(result);
                }
            }

            ResponseSerializerDelegate responseWriter;

            if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) ||
                this.ContentTypeResponseSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseWriter))
            {
                using (var ms = new MemoryStream())
                {
                    var httpRes = new HttpResponseStreamWrapper(ms)
                    {
                        KeepOpen = true, //Don't let view engines close the OutputStream
                    };
                    responseWriter(req, response, httpRes);

                    var bytes  = ms.ToArray();
                    var result = bytes.FromUtf8Bytes();

                    httpRes.ForceClose(); //Manually close the OutputStream

                    return(result);
                }
            }

            var contentTypeAttr = ContentFormat.GetEndpointAttributes(contentType);

            switch (contentTypeAttr)
            {
            case RequestAttributes.Xml:
                return(XmlSerializer.SerializeToString(response));

            case RequestAttributes.Json:
                return(JsonDataContractSerializer.Instance.SerializeToString(response));

            case RequestAttributes.Jsv:
                return(TypeSerializer.SerializeToString(response));

            case RequestAttributes.Soap11:
                return(SoapHandler.SerializeSoap11ToBytes(req, response).FromUtf8Bytes());

            case RequestAttributes.Soap12:
                return(SoapHandler.SerializeSoap12ToBytes(req, response).FromUtf8Bytes());
            }

            throw new NotSupportedException("ContentType not supported: " + contentType);
        }
示例#21
0
 public static string ToJsv <T>(this T obj)
 {
     return(TypeSerializer.SerializeToString(obj));
 }
 public void JsvSerializerHonorsIgnoreMemberAttribute()
 {
     DoIgnoreMemberTest(r => TypeSerializer.SerializeToString(r),
                        s => TypeSerializer.DeserializeFromString <RequestWithIgnoredMembers>(s));
 }
示例#23
0
        public void DateTime_Is_Serialized_As_Utc_and_Deserialized_as_local()
        {
            var testObject = new TestObject
            {
                Date = new DateTime(2013, 1, 1, 0, 0, 1, DateTimeKind.Utc)
            };

            Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);

            //Can change default behavior with config
            using (JsConfig.With(alwaysUseUtc: true))
            {
                Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }

            testObject = new TestObject
            {
                Date = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            };

            Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);

            //Can change default behavior with config
            using (JsConfig.With(alwaysUseUtc: true))
            {
                Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind);
            }
        }
 public static string CoerceString(object o)
 {
     return TypeSerializer.SerializeToString(o);
 }
示例#25
0
        public void onBeforeTestFixture()
        {
            var results = 100.Times(x => ModelWithFieldsOfDifferentTypes.Create(x));

            testData = TypeSerializer.SerializeToString(results);
        }
示例#26
0
 public string BuildSerialisedString()
 {
     return(TypeSerializer.SerializeToString(this));
 }
        public void onBeforeTestFixture()
        {
            NorthwindData.LoadData(false);

            testData = TypeSerializer.SerializeToString(NorthwindData.Customers);
        }
        private TResponse Invoke <TResponse>(ClientExecutionContext context)
        {
            Stopwatch stopwatch           = null;
            Stopwatch remoteCallStopwatch = null;

            try
            {
                stopwatch = new Stopwatch();

                stopwatch.Start();

                ApplyRequestFilters(ServiceName, ServiceNamespace, context.Operation, context.Request);

                HttpWebRequest webRequest = PrepareWebRequest(context);

                remoteCallStopwatch = new Stopwatch();
                remoteCallStopwatch.Start();
                TResponse response;
                using (WebResponse webResponse = Invoke(context, webRequest))
                {
                    remoteCallStopwatch.Stop();
                    context.Metrics.ResponseSize = webResponse.ContentLength < 0 ? 0 : webResponse.ContentLength;


                    response = HandleResponse <TResponse>(context, webResponse);
                }

                ApplyResponseFilters(ServiceName, ServiceNamespace, context.Operation, context.Response);


                context.IsSuccess = true;
                return(response);
            }
            catch (CServiceException cex)
            {
                Dictionary <string, string> additionalInfo = GetClientInfo(context);
                additionalInfo["ErrorCode"] = "FXD301004";
                if (LogErrorWithRequestInfo)
                {
                    additionalInfo["RequestObject"] = TypeSerializer.SerializeToString(context.Request);
                }
                LogCServiceException(GetLogTitle(InternalServiceUtils.ServiceErrorTitle), cex, additionalInfo);


                throw;
            }
            catch (WebException ex)
            {
                WebException subClassedException = HandleWebException(context, (WebException)ex);

                LogGeneralException(context, subClassedException);

                if (ex == subClassedException)
                {
                    throw;
                }

                throw subClassedException;
            }
            catch (Exception ex)
            {
                LogGeneralException(context, ex);

                throw;
            }
            finally
            {
                if (remoteCallStopwatch != null)
                {
                    if (remoteCallStopwatch.IsRunning)
                    {
                        remoteCallStopwatch.Stop();
                    }
                    context.Metrics.ExecutionTime = remoteCallStopwatch.ElapsedMilliseconds;
                }

                stopwatch.Stop();
                context.Metrics.TotalTime = stopwatch.ElapsedMilliseconds;

                ResetCurrentRequestTimeoutSetting();
            }
        }