Example #1
0
 public void SignedByteSerialization()
 {
     Assert.AreEqual("1", SimpleJson.SerializeObject((sbyte)1));
 }
 public void CanSerializeUnknownPropertyUsingNamingConvention()
 {
     var instance = new ObjProp { PropTypeKnown = "str", PropTypeUnknown = new { unknown = "property" } };
     var json = SimpleJson.SerializeObject(instance, new MyJsonSerializerStrategy());
     Assert.AreEqual("{\"prop_type_known\":\"str\",\"prop_type_unknown\":{\"unknown\":\"property\"}}", json);
 }
Example #3
0
        private void Send(RaygunMessage raygunMessage, int timeout)
        {
            if (!ValidateApiKey())
            {
                RaygunLogger.Error("Failed to send due to invalid API key");
                return;
            }

            bool canSend = OnSendingMessage(raygunMessage);

            if (!canSend)
            {
                RaygunLogger.Debug("Sending message cancelled");
                return;
            }

            // No internet then we store the report.
            if (!HasInternetConnection)
            {
                var path = _fileManager.SaveCrashReport(raygunMessage, MaxReportsStoredOnDevice);

                if (!string.IsNullOrEmpty(path))
                {
                    RaygunLogger.Debug("Saved crash report to: " + path);
                }

                return;
            }

            try
            {
                // Create the json data.
                var jsonData = SimpleJson.SerializeObject(raygunMessage);

                var statusCode = SendMessage(jsonData, timeout);

                RaygunLogger.LogResponseStatusCode(statusCode);

                // Save the message if the application is currently being rate limited or there was a timeout.
                if (statusCode == (int)RaygunResponseStatusCode.RateLimited ||
                    statusCode == (int)RaygunResponseStatusCode.RequestTimeout ||
                    statusCode == (int)RaygunResponseStatusCode.GatewayTimeout)
                {
                    var path = _fileManager.SaveCrashReport(raygunMessage, MaxReportsStoredOnDevice);

                    if (!string.IsNullOrEmpty(path))
                    {
                        RaygunLogger.Debug("Saved crash report to: " + path);
                    }
                }
            }
            catch (Exception e)
            {
                RaygunLogger.Error(string.Format("Failed to send message due to error {0}: {1}", e.GetType().Name, e.Message));

                var path = _fileManager.SaveCrashReport(raygunMessage, MaxReportsStoredOnDevice);

                if (!string.IsNullOrEmpty(path))
                {
                    RaygunLogger.Debug("Saved crash report to: " + path);
                }
            }
        }
Example #4
0
 public string GetEventTypes()
 {
     return(SimpleJson.SerializeObject(_data.GetEventTypes())); //.SerializeObject(_data.GetEventTypes());
 }
Example #5
0
 public static string ToDebug(this Entity entity)
 {
     return(SimpleJson.SerializeObject(ConvertToRecord(entity)));
 }
Example #6
0
 public void Save()
 {
     SaveSettings();
     settingsStore.Write("UIState", SimpleJson.SerializeObject(UIState));
 }
Example #7
0
        protected override async Task <SetStreamMetadataResult> SetStreamMetadataInternal(
            string streamId,
            int expectedStreamMetadataVersion,
            int?maxAge,
            int?maxCount,
            string metadataJson,
            CancellationToken cancellationToken)
        {
            MsSqlAppendResult result;

            using (var connection = _createConnection())
            {
                var streamIdInfo = new StreamIdInfo(streamId);

                await connection.OpenAsync(cancellationToken).NotOnCapturedContext();

                using (var transaction = connection.BeginTransaction())
                {
                    var metadataMessage = new MetadataMessage
                    {
                        StreamId = streamId,
                        MaxAge   = maxAge,
                        MaxCount = maxCount,
                        MetaJson = metadataJson
                    };
                    var json      = SimpleJson.SerializeObject(metadataMessage);
                    var messageId = MetadataMessageIdGenerator.Create(
                        streamId,
                        expectedStreamMetadataVersion,
                        json);
                    var newmessage = new NewStreamMessage(messageId, "$stream-metadata", json);

                    result = await AppendToStreamInternal(
                        connection,
                        transaction,
                        streamIdInfo.MetadataSqlStreamId,
                        expectedStreamMetadataVersion,
                        new[] { newmessage },
                        cancellationToken);

                    using (var command = new SqlCommand(_scripts.SetStreamMetadata, connection, transaction))
                    {
                        command.Parameters.Add(new SqlParameter("streamId", SqlDbType.Char, 42)
                        {
                            Value = streamIdInfo.SqlStreamId.Id
                        });
                        command.Parameters.AddWithValue("streamIdOriginal", streamIdInfo.SqlStreamId.IdOriginal);
                        command.Parameters.Add("maxAge", SqlDbType.Int);
                        command.Parameters["maxAge"].Value = maxAge ?? -1;
                        command.Parameters.Add("maxCount", SqlDbType.Int);
                        command.Parameters["maxCount"].Value = maxCount ?? -1;
                        await command.ExecuteNonQueryAsync(cancellationToken);
                    }

                    transaction.Commit();
                }
            }

            await CheckStreamMaxCount(streamId, maxCount, cancellationToken);

            return(new SetStreamMetadataResult(result.CurrentVersion));
        }
Example #8
0
        private static void DebugReturnObjectFetchXMLToJs()
        {
            var fetchData = new
            {
                accountid             = "{60E1C27F-DD03-EC11-B6E5-000D3AA2E9C5}",
                transactioncurrencyid = "{F89D2C96-C802-EC11-B6E5-000D3AA2EB72}",
                isocurrencycode       = "VND",
                contactid             = "{74E1C27F-DD03-EC11-B6E5-000D3AA2E9C5}"
            };
            var fetchXml = $@"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='account'>
    <attribute name='name'/>
    <attribute name='primarycontactid'/>
    <attribute name='telephone1'/>
    <attribute name='accountid'/>
    <attribute name='industrycode'/>
    <attribute name='statuscode'/>
    <attribute name='statecode'/>
    <attribute name='donotpostalmail'/>
    <attribute name='numberofemployees'/>
    <attribute name='createdon'/>
    <attribute name='accountnumber'/>
    <attribute name='stageid'/>
    <order attribute='name' descending='false'/>
    <filter type='and'>
      <condition attribute='accountid' operator='eq' value='{fetchData.accountid}'/>
    </filter>
    <link-entity name='transactioncurrency' from='transactioncurrencyid' to='transactioncurrencyid' link-type='inner' alias='currency'>
      <attribute name='isocurrencycode'/>
      <filter type='and'>
        <condition attribute='transactioncurrencyid' operator='eq' value='{fetchData.transactioncurrencyid}'/>
        <condition attribute='isocurrencycode' operator='eq' value='{fetchData.isocurrencycode}'/>
      </filter>
    </link-entity>
    <link-entity name='account' from='accountid' to='parentaccountid' visible='false' link-type='outer' alias='account'>
      <attribute name='accountnumber'/>
      <attribute name='name'/>
      <attribute name='createdby'/>
    </link-entity>
    <link-entity name='contact' from='contactid' to='primarycontactid' link-type='inner' alias='contact'>
      <attribute name='lastname'/>
      <attribute name='fullname'/>
      <attribute name='firstname'/>
      <link-entity name='systemuser' from='systemuserid' to='createdby' visible='false' link-type='outer' alias='user'>
        <attribute name='fullname'/>
      </link-entity>
      <filter type='and'>
        <condition attribute='contactid' operator='eq' value='{fetchData.contactid}'/>
      </filter>
    </link-entity>
  </entity>
</fetch>
";
            var input    = new
            {
                FetchXml = fetchXml
            };
            var json   = SimpleJson.SerializeObject(input);
            var output = ReturnObjectFetchXMLToJs.Process(AppSettings.Service, null, null, json);
            var t      = string.Empty;
        }
Example #9
0
        private static void DebugConvertFetchXmlToWebAPI()
        {
            var fetchData = new
            {
                accountid              = "{60E1C27F-DD03-EC11-B6E5-000D3AA2E9C5}",
                industrycode           = "5" /* Building Supply Retail */,
                name                   = "L%",
                transactioncurrencyid  = "{F89D2C96-C802-EC11-B6E5-000D3AA2EB72}",
                isocurrencycode        = "VND",
                contactid              = "{74E1C27F-DD03-EC11-B6E5-000D3AA2E9C5}",
                parentcustomerid       = "{60E1C27F-DD03-EC11-B6E5-000D3AA2E9C5}",
                transactioncurrencyid2 = "{F89D2C96-C802-EC11-B6E5-000D3AA2EB72}"
            };
            var fetchXml = $@"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='account'>
    <attribute name='name'/>
    <attribute name='primarycontactid'/>
    <attribute name='telephone1'/>
    <attribute name='accountid'/>
    <attribute name='industrycode'/>
    <attribute name='statuscode'/>
    <attribute name='statecode'/>
    <attribute name='donotpostalmail'/>
    <attribute name='numberofemployees'/>
    <attribute name='createdon'/>
    <attribute name='accountnumber'/>
    <attribute name='stageid'/>
    <order attribute='name' descending='false'/>
    <filter type='and'>
      <filter type='and'>
        <filter type='or'>
          <condition attribute='accountid' operator='eq' value='{fetchData.accountid}'/>
          <condition attribute='industrycode' operator='eq' value='{fetchData.industrycode}'/>
        </filter>
        <filter type='and'>
          <condition attribute='name' operator='not-null'/>
          <condition attribute='name' operator='like' value='{fetchData.name}'/>
        </filter>
      </filter>
    </filter>
    <link-entity name='transactioncurrency' from='transactioncurrencyid' to='transactioncurrencyid' link-type='inner' alias='am'>
      <attribute name='isocurrencycode'/>
      <filter type='and'>
        <condition attribute='transactioncurrencyid' operator='eq' value='{fetchData.transactioncurrencyid}'/>
        <condition attribute='isocurrencycode' operator='eq' value='{fetchData.isocurrencycode}'/>
      </filter>
    </link-entity>
    <link-entity name='account' from='accountid' to='parentaccountid' visible='false' link-type='outer' alias='a_57511732b5534cfbbcf2d280f9f8c6f1'>
      <attribute name='accountnumber'/>
      <attribute name='name'/>
      <attribute name='createdby'/>
    </link-entity>
    <link-entity name='contact' from='contactid' to='primarycontactid' link-type='inner' alias='ba'>
      <attribute name='lastname'/>
      <attribute name='fullname'/>
      <attribute name='firstname'/>
      <filter type='and'>
        <condition attribute='contactid' operator='eq' value='{fetchData.contactid}'/>
        <condition attribute='parentcustomerid' operator='eq' value='{fetchData.parentcustomerid}'/>
        <condition attribute='transactioncurrencyid' operator='eq' value='{fetchData.transactioncurrencyid2}'/>
      </filter>
    </link-entity>
  </entity>
</fetch>
";
            var input    = new
            {
                FetchXml = fetchXml,
                Url      = $"https://org47503bc8.crm5.dynamics.com/api/data/v9.2"
            };
            var json   = SimpleJson.SerializeObject(input);
            var output = ConvertFetchXmlToWebAPI.Process(AppSettings.Service, null, null, json);


            var t = string.Empty;
        }
Example #10
0
        public void SerializerBigNumberCorrectly()
        {
            string json = SimpleJson.SerializeObject(new { object_id = 10150098461530576 });

            Assert.AreEqual("{\"object_id\":10150098461530576}", json);
        }
Example #11
0
        public void StringSerialization()
        {
            string str = "I am a string";

            Assert.AreEqual(@"""I am a string""", SimpleJson.SerializeObject(str));
        }
Example #12
0
        public void SerializeUnicodeTests()
        {
            var o = SimpleJson.SerializeObject("न");

            Assert.AreEqual("\"न\"", o);
        }
Example #13
0
 public void DoubleSerialization()
 {
     Assert.AreEqual("1.1", SimpleJson.SerializeObject(1.1));
 }
Example #14
0
 public void UnsingedInt32Serialization()
 {
     Assert.AreEqual("1", SimpleJson.SerializeObject((uint)1));
 }
        async Task <PreparedMessage> PrepareMessage(UnicastTransportOperation transportOperation)
        {
            var delayDeliveryWith  = transportOperation.DeliveryConstraints.OfType <DelayDeliveryWith>().SingleOrDefault();
            var doNotDeliverBefore = transportOperation.DeliveryConstraints.OfType <DoNotDeliverBefore>().SingleOrDefault();

            long delaySeconds = 0;

            if (delayDeliveryWith != null)
            {
                delaySeconds = Convert.ToInt64(Math.Ceiling(delayDeliveryWith.Delay.TotalSeconds));
            }
            else if (doNotDeliverBefore != null)
            {
                delaySeconds = Convert.ToInt64(Math.Ceiling((doNotDeliverBefore.At - DateTime.UtcNow).TotalSeconds));
            }

            if (!configuration.IsDelayedDeliveryEnabled && delaySeconds > TransportConfiguration.AwsMaximumQueueDelayTime)
            {
                throw new NotSupportedException($"To send messages with a delay time greater than '{TimeSpan.FromSeconds(TransportConfiguration.AwsMaximumQueueDelayTime)}', call '.UseTransport<SqsTransport>().UnrestrictedDelayedDelivery()'.");
            }

            var sqsTransportMessage = new TransportMessage(transportOperation.Message, transportOperation.DeliveryConstraints);

            var serializedMessage = SimpleJson.SerializeObject(sqsTransportMessage, serializerStrategy);

            var messageId = transportOperation.Message.MessageId;

            var preparedMessage = new PreparedMessage();
            var delayLongerThanConfiguredDelayedDeliveryQueueDelayTime = configuration.IsDelayedDeliveryEnabled && delaySeconds > configuration.DelayedDeliveryQueueDelayTime;

            if (delayLongerThanConfiguredDelayedDeliveryQueueDelayTime)
            {
                preparedMessage.OriginalDestination = transportOperation.Destination;
                preparedMessage.Destination         = $"{transportOperation.Destination}{TransportConfiguration.DelayedDeliveryQueueSuffix}";
                preparedMessage.QueueUrl            = await queueUrlCache.GetQueueUrl(QueueNameHelper.GetSqsQueueName(preparedMessage.Destination, configuration))
                                                      .ConfigureAwait(false);

                preparedMessage.MessageDeduplicationId = messageId;
                preparedMessage.MessageGroupId         = messageId;

                preparedMessage.MessageAttributes[TransportHeaders.DelaySeconds] = new MessageAttributeValue
                {
                    StringValue = delaySeconds.ToString(),
                    DataType    = "String"
                };
            }
            else
            {
                preparedMessage.Destination = transportOperation.Destination;
                preparedMessage.QueueUrl    = await queueUrlCache.GetQueueUrl(QueueNameHelper.GetSqsQueueName(preparedMessage.Destination, configuration))
                                              .ConfigureAwait(false);

                if (delaySeconds > 0)
                {
                    preparedMessage.DelaySeconds = Convert.ToInt32(delaySeconds);
                }
            }

            // because message attributes are part of the content size restriction we want to prevent message size from changing thus we add it
            // for native delayed deliver as well even though the information is slightly redundant (MessageId is assigned to MessageDeduplicationId for example)
            preparedMessage.MessageAttributes[Headers.MessageId] = new MessageAttributeValue
            {
                StringValue = messageId,
                DataType    = "String"
            };

            preparedMessage.Body      = serializedMessage;
            preparedMessage.MessageId = messageId;
            preparedMessage.CalculateSize();
            if (preparedMessage.Size <= TransportConfiguration.MaximumMessageSize)
            {
                return(preparedMessage);
            }

            if (string.IsNullOrEmpty(configuration.S3BucketForLargeMessages))
            {
                throw new Exception("Cannot send large message because no S3 bucket was configured. Add an S3 bucket name to your configuration.");
            }

            var key = $"{configuration.S3KeyPrefix}/{messageId}";

            using (var bodyStream = new MemoryStream(transportOperation.Message.Body))
            {
                var putObjectRequest = new PutObjectRequest
                {
                    BucketName  = configuration.S3BucketForLargeMessages,
                    InputStream = bodyStream,
                    Key         = key,
                };
                ApplyServerSideEncryptionConfiguration(putObjectRequest);

                await s3Client.PutObjectAsync(putObjectRequest).ConfigureAwait(false);
            }

            sqsTransportMessage.S3BodyKey = key;
            sqsTransportMessage.Body      = string.Empty;
            preparedMessage.Body          = SimpleJson.SerializeObject(sqsTransportMessage, serializerStrategy);
            preparedMessage.CalculateSize();

            return(preparedMessage);
        }
Example #16
0
 /// <summary>
 ///     Serialize the object as JSON
 ///     If the object is already a serialized string returns it's value
 /// </summary>
 /// <param name="obj">Object to serialize</param>
 /// <returns>JSON as String</returns>
 public string Serialize(object obj)
 => IsSerializedString(obj, out var serializedString)
         ? serializedString
         : SimpleJson.SerializeObject(obj);
Example #17
0
        public static void DebugContext(this ITracingService tracingService, IPluginExecutionContext context)
        {
#if DEBUG
            var preEntityImages  = context.PreEntityImages == null ? null : context.PreEntityImages.Values.Select(x => EntityToObject(x));
            var postEntityImages = context.PostEntityImages == null ? null : context.PostEntityImages.Values.Select(x => EntityToObject(x));
            var inputParameters  = new Dictionary <string, object>();
            foreach (var key in context.InputParameters.Keys)
            {
                if (context.InputParameters[key] is Entity x)
                {
                    inputParameters.Add(key, EntityToObject(x));
                }
                else
                {
                    inputParameters.Add(key, context.InputParameters[key]);
                }
            }
            var outputParameters = new Dictionary <string, object>();
            foreach (var key in context.OutputParameters.Keys)
            {
                if (context.OutputParameters[key] is Entity x)
                {
                    outputParameters.Add(key, EntityToObject(x));
                }
                else
                {
                    outputParameters.Add(key, context.OutputParameters[key]);
                }
            }
            var obj = new
            {
                context.BusinessUnitId,
                context.CorrelationId,
                context.Depth,
                context.InitiatingUserId,
                context.IsExecutingOffline,
                context.IsInTransaction,
                context.IsOfflinePlayback,
                context.IsolationMode,
                context.MessageName,
                context.Mode,
                context.OperationCreatedOn,
                context.OperationId,
                context.OrganizationId,
                context.OrganizationName,
                context.OwningExtension,
                context.PrimaryEntityId,
                context.PrimaryEntityName,
                context.RequestId,
                context.SecondaryEntityName,
                context.SharedVariables,
                context.Stage,
                context.UserId,
                InputParameters         = inputParameters,
                OutputParameters        = outputParameters,
                PostEntityImages        = postEntityImages,
                PreEntityImages         = preEntityImages,
                IsAutoTransact          = context.IsAutoTransact(),
                IsWithinMainTransaction = context.IsWithinMainTransaction()
            };
            tracingService.LogMessage(SimpleJson.SerializeObject(obj));
#endif
        }
Example #18
0
        public bool Update(string id, string name, string rating, string length, string releaseYear, User client, string loginfo)
        {
            try
            {
                if (!length.All(char.IsDigit) || length == null)
                {
                    throw new Exception("A hossz csak szám lehet!");
                }
                if (!releaseYear.All(char.IsDigit) || releaseYear == null)
                {
                    throw new Exception("Az évszám csak szám lehet!");
                }
                if (int.Parse(length) <= 0 || int.Parse(length) >= 5000)
                {
                    throw new Exception("A hossz 0 és 5000 között lehet!");
                }
                if (int.Parse(releaseYear) <= 1800 || int.Parse(releaseYear) > DateTime.Now.Year)
                {
                    throw new Exception("A dátum 1800-nál későbbi és a jelengei évtől korábbi lehet!");
                }

                if (HasGuid(client))
                {
                    var postBody = SimpleJson.SerializeObject(new
                    {
                        Name        = name,
                        Rating      = rating,
                        Length      = int.Parse(length),
                        ReleaseYear = int.Parse(releaseYear)
                    });

                    var    restClient = new RestClient(REST_URL);
                    string ROUTE      = "index.php";
                    var    request    = new RestRequest(ROUTE + "?log=" + loginfo + "&id=" + id, Method.PUT);
                    request.AddHeader("book_header", loginfo);
                    request.AddHeader("accept", "application/json");
                    request.AddHeader("Content-Type", "application/json");
                    request.AddParameter("id", id, ParameterType.QueryString);
                    request.AddJsonBody(postBody);

                    IRestResponse <JSONResponse> response = restClient.Execute <JSONResponse>(request);

                    if (response.Content.Substring(1, response.Content.Length - 2) == "WRONG LOG INFO")
                    {
                        return(false);
                    }

                    //if(!response.IsSuccessful) throw new BookNotFoundException();
                    else
                    {
                        return(true);
                    }
                }

                throw new LoginFailedException();
            }
            catch (NullReferenceException)
            {
                throw new FaultException <LoginFailedFault>(new LoginFailedFault("Autentikációs hiba!"), new FaultReason("Autentikációs hiba!"));
            }
            catch (BookNotFoundException)
            {
                throw new FaultException <BookNotFoundFault>(new BookNotFoundFault("Nincs ilyen könyv!!"), new FaultReason("Nincs ilyen könyv!"));
            }
            catch (LoginFailedException)
            {
                throw new FaultException <LoginFailedFault>(new LoginFailedFault("Autentikációs hiba!"), new FaultReason("Autentikációs hiba!"));
            }
            catch (Exception ex)
            {
                throw new FaultException(new FaultReason(ex.Message));
            }
        }
Example #19
0
 public virtual string Serialize <T>(T item)
 {
     return(SimpleJson.SerializeObject(item, _serializerStrategy));
 }
Example #20
0
        private object SendRecord(Dictionary <string, object> fields, bool isUpdate)
        {
            try
            {
                if (Session.Disconnected)
                {
                    Session.Reconnect();
                }

                var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), isUpdate ? Method.PUT : Method.POST);

                // "{\"record\":[{\"ID\":\"1\",\"Name\":\"Item #1\",\"UUID\":null,\"ITest\":23,\"Address\":\"Foo\",\"FTest\":\"2.4\",\"DBTest\":null,\"DETest\":null,\"TS\":0}]}"
                var o = SimpleJson.SerializeObject(fields);

                // we have to name the collection or the API will fail
                o = string.Format("{{ \"record\": [{0}] }}", o);

                // NOTE: We must use AddParameter here because we've already serialized the JSON.  AddBody attempts to serialize it again
                // At some point I want to fix RestSharp to not do this, as it's stupid behavior
                request.AddParameter("application/json", o, ParameterType.RequestBody);

                var response = Session.Client.Execute(request);

                switch (response.StatusCode)
                {
                case HttpStatusCode.Created:
                case HttpStatusCode.OK:
                    // the key for the inserted item gets returned (if there is one)
                    var pkJson = SimpleJson.DeserializeObject(response.Content) as JsonObject;
                    if (pkJson.Count == 0)
                    {
                        return(null);
                    }

                    var key = (pkJson[0] as JsonArray)[0] as JsonObject;
                    // no data sent back (i.e. there was no key field)
                    if (key == null)
                    {
                        return(null);
                    }

                    var name = key.Keys.First();
                    // no data sent back (i.e. there was no key field)
                    if (name.IsNullOrEmpty())
                    {
                        return(null);
                    }

                    var value = key[name];
                    return(value);

                case HttpStatusCode.InternalServerError:
                    var ex = DreamFactoryException.Parse(response);
                    if ((Session.ServerVersion == new Version("1.9.2")) && (ex.Message == "array (\n)"))
                    {
                        // this is an edge-case in DF 1.9.2 where a successful insert sometime will still return a 500 *even though* the record did insert.  WTF??
                        return(null);
                    }
                    throw ex;

                case HttpStatusCode.Forbidden:
                case HttpStatusCode.Unauthorized:
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }

                    Session.Disconnected = true;

                    throw DreamFactoryException.Parse(response);

                default:
                    throw DreamFactoryException.Parse(response);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #21
0
 public string Serialize(object item)
 {
     return(SimpleJson.SerializeObject(item, _serializationStrategy));
 }
Example #22
0
 internal string ToJson()
 {
     return(SimpleJson.SerializeObject(this));
 }
Example #23
0
        public string test()
        {
            var ret = _data.GetEventTypes();

            return(SimpleJson.SerializeObject(ret));
        }
Example #24
0
 /// <summary>
 /// Serialize the object as JSON
 /// </summary>
 /// <param name="obj">Object to serialize</param>
 /// <returns>JSON as String</returns>
 public string Serialize(object obj)
 {
     return(SimpleJson.SerializeObject(obj));
 }
Example #25
0
        public static void DebugContext(this ITracingService tracingService, IExecutionContext context)
        {
#if DEBUG
            try
            {
                var preEntityImages  = context?.PreEntityImages == null ? null : context?.PreEntityImages?.Values?.Select(x => EntityToObject(x));
                var postEntityImages = context?.PostEntityImages == null ? null : context?.PostEntityImages?.Values?.Select(x => EntityToObject(x));
                var inputParameters  = new Dictionary <string, object>();
                foreach (var key in context?.InputParameters?.Keys)
                {
                    if (context?.InputParameters?[key] is Entity x)
                    {
                        inputParameters.Add(key, EntityToObject(x));
                    }
                    else
                    {
                        inputParameters.Add(key, context?.InputParameters?[key]);
                    }
                }
                var outputParameters = new Dictionary <string, object>();
                foreach (var key in context?.OutputParameters?.Keys)
                {
                    if (context?.OutputParameters?[key] is Entity x)
                    {
                        outputParameters.Add(key, EntityToObject(x));
                    }
                    else
                    {
                        outputParameters.Add(key, context?.OutputParameters?[key]);
                    }
                }
                var obj = new
                {
                    BusinessUnitId     = context?.BusinessUnitId,
                    CorrelationId      = context?.CorrelationId,
                    Depth              = context?.Depth,
                    InitiatingUserId   = context?.InitiatingUserId,
                    IsExecutingOffline = context?.IsExecutingOffline,
                    IsInTransaction    = context?.IsInTransaction,
                    IsOfflinePlayback  = context?.IsOfflinePlayback,
                    IsolationMode      = context?.IsolationMode,
                    MessageName        = context?.MessageName,
                    Mode = context?.Mode,
                    OperationCreatedOn  = context?.OperationCreatedOn,
                    OperationId         = context?.OperationId,
                    OrganizationId      = context?.OrganizationId,
                    OrganizationName    = context?.OrganizationName,
                    OwningExtension     = context?.OwningExtension,
                    PrimaryEntityId     = context?.PrimaryEntityId,
                    PrimaryEntityName   = context?.PrimaryEntityName,
                    RequestId           = context?.RequestId,
                    SecondaryEntityName = context?.SecondaryEntityName,
                    SharedVariables     = context?.SharedVariables,
                    UserId           = context?.UserId,
                    InputParameters  = inputParameters,
                    OutputParameters = outputParameters,
                    PostEntityImages = postEntityImages,
                    PreEntityImages  = preEntityImages,
                };
                tracingService.LogMessage(SimpleJson.SerializeObject(obj));
            }
            catch { }
#endif
        }
Example #26
0
 public string ToJson()
 {
     return(SimpleJson.SerializeObject(this));
 }
Example #27
0
 public string ToJson()
 {
     return(SimpleJson.SerializeObject(this, SerializerStrategy));
 }
Example #28
0
 /// <summary>
 /// Serialize the object as JSON
 /// </summary>
 /// <param name="obj">Object to serialize</param>
 /// <returns>JSON as String</returns>
 public string Serialize(object obj) => SimpleJson.SerializeObject(obj);
Example #29
0
            /// <summary> Convert Scoretags to the specified user defined data type. </summary>
            public T ConvertScoretags <T> ()
            {
                string json = SimpleJson.SerializeObject(Scoretags);

                return(SimpleJson.DeserializeObject <T> (json, null));
            }
Example #30
0
 public void Int64Serialization()
 {
     Assert.AreEqual("1", SimpleJson.SerializeObject((long)1));
 }