public void WriteJRaw()
        {
            ITraceWriter traceWriter = new MemoryTraceWriter();

            JRaw settings = new JRaw("$('#element')");
            string json = JsonConvert.SerializeObject(settings, new JsonSerializerSettings
            {
                TraceWriter = traceWriter
            });

            Assert.AreEqual("$('#element')", json);

            Assert.IsTrue(traceWriter.ToString().EndsWith("Verbose Serialized JSON: " + Environment.NewLine + "$('#element')", StringComparison.Ordinal));
        }
Пример #2
0
    public void RawChildValues()
    {
      JObject o = new JObject();
      o["val1"] = new JRaw("1");
      o["val2"] = new JRaw("1");

      string json = o.ToString();

      Assert.AreEqual(@"{
  ""val1"": 1,
  ""val2"": 1
}", json);
    }
Пример #3
0
 public JqGridColumn setSummaryType(SummaryType valor)
 {
     summaryType = new JRaw("\"" + valor.ToString() + "\"");
     return(this);
 }
Пример #4
0
        /// <summary>
        /// rowId - the id of the row
        /// val - the value which will be added in the cell
        /// rawObject - the raw object of the data row - i.e if datatype is json - array, if datatype is xml xml node.
        /// cm - all the properties of this column listed in the colModel
        /// rdata - the data row which will be inserted in the row. This parameter is array of type name:value, where name is the name in colModel
        /// </summary>
        /// <param name="js">function(rowId, val, rawObject, cm, rdata)</param>
        /// <returns></returns>
        public JqGridColumn setCellAttr(string js)
        {
            cellattr = new JRaw(js);

            return(this);
        }
 public JRawValue(JRaw value)
 {
     _value = value.ToString();
 }
 /// <summary>
 /// Specifies the URL used to load JSON data.
 /// </summary>
 /// <param name="url">A URL string.</param>
 public StaticJsonDataSourceBuilder Url(string url)
 {
     url = Portability.GetContentUrl(base.ViewContext, url);
     StoreOptions["load"] = new JRaw("function() { return $.getJSON(" + JsonUtils.SafeSerialize(url) + "); }");
     return(this);
 }
Пример #7
0
        private void SubscriberThread()
        {
            if (sqlController.SettingRead(Settings.token) != "UNIT_TEST___________________L:32")
            #region amazon
            {
                #region setup
                isActive       = true;
                keepSubscribed = true;

                string awsAccessKeyId     = sqlController.SettingRead(Settings.awsAccessKeyId);
                string awsSecretAccessKey = sqlController.SettingRead(Settings.awsSecretAccessKey);
                string awsQueueUrl        = sqlController.SettingRead(Settings.awsEndPoint) + sqlController.SettingRead(Settings.token);

                var      sqsClient     = new AmazonSQSClient(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.EUCentral1);
                DateTime lastExpection = DateTime.MinValue;
                DateTime lastCheckAdd15s;
                #endregion

                while (keepSubscribed)
                {
                    try
                    {
                        lastCheckAdd15s = DateTime.Now.AddSeconds(15);
                        var res = sqsClient.ReceiveMessageAsync(awsQueueUrl).Result;

                        if (res.Messages.Count > 0)
                        {
                            foreach (var message in res.Messages)
                            {
                                #region JSON -> var
                                var    parsedData      = JRaw.Parse(message.Body);
                                string notificationUId = parsedData["id"].ToString();
                                string microtingUId    = parsedData["microting_uuid"].ToString();
                                string action          = parsedData["text"].ToString();
                                #endregion
                                log.LogStandard(t.GetMethodName("Subscriber"), "Notification notificationUId : " + notificationUId + " microtingUId : " + microtingUId + " action : " + action);
                                switch (action)
                                {
                                case Constants.Notifications.Completed:
                                    sqlController.NotificationCreate(notificationUId, microtingUId, Constants.Notifications.Completed);
                                    bus.SendLocal(new EformCompleted(notificationUId, microtingUId));
                                    break;

                                case Constants.Notifications.EformParsedByServer:
                                    bus.SendLocal(new EformParsedByServer(notificationUId, microtingUId));
                                    break;

                                case Constants.Notifications.EformParsingError:
                                    bus.SendLocal(new EformParsingError(notificationUId, microtingUId));
                                    break;

                                case Constants.Notifications.RetrievedForm:
                                    sqlController.NotificationCreate(notificationUId, microtingUId, Constants.Notifications.RetrievedForm);
                                    bus.SendLocal(new EformRetrieved(notificationUId, microtingUId));
                                    break;

                                case Constants.Notifications.UnitActivate:
                                    sqlController.NotificationCreate(notificationUId, microtingUId, Constants.Notifications.UnitActivate);
                                    bus.SendLocal(new UnitActivated(notificationUId, microtingUId));
                                    break;

                                case Constants.Notifications.SpeechToTextCompleted:
                                    sqlController.NotificationCreate(notificationUId, microtingUId, Constants.Notifications.SpeechToTextCompleted);
                                    bus.SendLocal(new TranscriptionCompleted(notificationUId, microtingUId));
                                    break;
                                }

                                sqsClient.DeleteMessageAsync(awsQueueUrl, message.ReceiptHandle);
                            }
                        }
                        else
                        {
                            while (lastCheckAdd15s > DateTime.Now)
                            {
                                Thread.Sleep(500);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //Log expection
                        log.LogWarning(t.GetMethodName("Subscriber"), t.PrintException(t.GetMethodName("Subscriber") + " failed", ex));

                        if (DateTime.Compare(lastExpection.AddMinutes(5), DateTime.Now) > 0)
                        {
                            keepSubscribed = false;
                            log.LogException(t.GetMethodName("Subscriber"), "failed, twice in the last 5 minuts", ex, true);
                        }

                        lastExpection = DateTime.Now;
                    }
                }

                //EventMsgClient("Subscriber closed", null);
                keepSubscribed = false;
                isActive       = false;
            }
            #endregion
            else
            #region unit test
            {
                log.LogStandard(t.GetMethodName("Subscriber"), "Subscriber faked");
                isActive       = true;
                keepSubscribed = true;

                while (keepSubscribed)
                {
                    Thread.Sleep(100);
                }

                keepSubscribed = false;
                isActive       = false;
            }
            #endregion
        }
Пример #8
0
        /// <summary>
        /// Turns a token object into JWT payload
        /// </summary>
        /// <param name="token">The token</param>
        /// <returns>Serialized JWT payload</returns>
        public static string CreateJwtPayload(this Token token)
        {
            var payload = new JwtPayload(
                token.Issuer,
                token.Audience,
                null,
                token.CreationTime.UtcDateTime,
                token.CreationTime.AddSeconds(token.Lifetime).UtcDateTime);

            var amrClaims    = token.Claims.Where(x => x.Type == Constants.ClaimTypes.AuthenticationMethod);
            var jsonClaims   = token.Claims.Where(x => x.ValueType == Constants.ClaimValueTypes.Json);
            var normalClaims = token.Claims.Except(amrClaims).Except(jsonClaims);

            payload.AddClaims(normalClaims);

            if (token.WebService != null)
            {
                payload.AddClaim(new System.Security.Claims.Claim(Constants.ClaimTypes.WebService, token.WebService));
            }

            // deal with amr
            var amrValues = amrClaims.Select(x => x.Value).Distinct().ToArray();

            if (amrValues.Any())
            {
                payload.Add(Constants.ClaimTypes.AuthenticationMethod, amrValues);
            }

            // deal with json types
            // calling ToArray() to trigger JSON parsing once and so later
            // collection identity comparisons work for the anonymous type
            var jsonTokens = jsonClaims.Select(x => new { x.Type, JsonValue = JRaw.Parse(x.Value) }).ToArray();

            var jsonObjects      = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Object).ToArray();
            var jsonObjectGroups = jsonObjects.GroupBy(x => x.Type).ToArray();

            foreach (var group in jsonObjectGroups)
            {
                if (payload.ContainsKey(group.Key))
                {
                    throw new Exception(String.Format("Can't add two claims where one is a JSON object and the other is not a JSON object ({0})", group.Key));
                }

                if (group.Skip(1).Any())
                {
                    // add as array
                    payload.Add(group.Key, group.Select(x => x.JsonValue).ToArray());
                }
                else
                {
                    // add just one
                    payload.Add(group.Key, group.First().JsonValue);
                }
            }

            var jsonArrays      = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Array).ToArray();
            var jsonArrayGroups = jsonArrays.GroupBy(x => x.Type).ToArray();

            foreach (var group in jsonArrayGroups)
            {
                if (payload.ContainsKey(group.Key))
                {
                    throw new Exception(String.Format("Can't add two claims where one is a JSON array and the other is not a JSON array ({0})", group.Key));
                }

                List <JToken> newArr = new List <JToken>();
                foreach (var arrays in group)
                {
                    var arr = (JArray)arrays.JsonValue;
                    newArr.AddRange(arr);
                }

                // add just one array for the group/key/claim type
                payload.Add(group.Key, newArr.ToArray());
            }

            var unsupportedJsonTokens     = jsonTokens.Except(jsonObjects).Except(jsonArrays);
            var unsupportedJsonClaimTypes = unsupportedJsonTokens.Select(x => x.Type).Distinct();

            if (unsupportedJsonClaimTypes.Any())
            {
                throw new Exception(String.Format("Unsupported JSON type for claim types: {0}", unsupportedJsonClaimTypes.Aggregate((x, y) => x + ", " + y)));
            }

            return(payload.SerializeToJson());
        }
Пример #9
0
 public JRaw EchoJRaw(JRaw input)
 {
     return(input);
 }
Пример #10
0
        public async Task <ActionResult <object> > ValidateUserRole([FromBody] JRaw u)// "{"email":"","password":""}"
        {
            // string pwd = "";
            JObject stuff  = JObject.Parse(u.ToString());
            string  email  = stuff["email"].ToString();
            string  pwd    = stuff["password"].ToString();
            var     result = await _signInManager.PasswordSignInAsync(email, pwd, false, lockoutOnFailure : true);

            string role = "";

            if (!result.Succeeded)
            {
                // JRaw res = (JRaw)("{'result':'error', 'message':'Invalid email or password'}");
                var model = new
                {
                    StatusCode = 404,
                    result     = "error",
                    message    = "Invalid email or password"
                };

                /*return new JsonResult(model)
                 * {
                 *  StatusCode = 404 // Status code here
                 *
                 * };*/
                return(NotFound(model));
            }
            else
            {
                // await _signInManager.SignInAsync(newUser, isPersistent: false);
                IdentityUser user = await _userManager.FindByEmailAsync(email);

                if (_userManager.IsInRoleAsync(user, "User").Result)
                {
                    role = "User";
                }
                else if (_userManager.IsInRoleAsync(user, "Admin").Result)
                {
                    role = "Admin";
                }
                // JRaw res= (JRaw)("{'result':'success', 'message':'profile found', 'profile':{'uId':'"+user.Id+ "', 'uEmail':'" + user.Email+ "', 'uFirstName':'" + user.first_name
                //+ "', 'uMiddleName':'" + user.middle_name + "', 'uLastName':'" + user.last_name+ "', 'uPhoneNumber':'" + user.PhoneNumber + "', 'Role':'" + role+ "' } }");
                var model = new
                {
                    StatusCode = 200,
                    result     = "success",
                    message    = "profile found",
                    profile    = new
                    {
                        uId    = user.Id,
                        uEmail = user.Email

                        ,
                        uPhoneNumber = user.PhoneNumber,
                        Role         = role
                    }
                };
                // return Ok(result.Succeeded);
                // return res;
                return(Ok(model));
            }
        }
        public void GetRelatedEntitiesByPropertyOtherThanIdTest()
        {
            // Arrange
            var userType1 = new UserType {
                Id = 1, Name = "Internal"
            };
            var userType2 = new UserType {
                Id = 2, Name = "Customer"
            };

            var entities = new List <UserType> {
                userType1, userType2
            };

            var user1 = new User2 {
                Id = 1, Name = "User1", UserTypeName = "Internal"
            };
            var relatedObjectJson1 = new JRaw(JsonConvert.SerializeObject(user1));
            var relatedEntity1     = new RelatedEntity {
                Object = relatedObjectJson1
            };

            var user2 = new User2 {
                Id = 2, Name = "User2", UserTypeName = "Internal"
            };
            var relatedObjectJson2 = new JRaw(JsonConvert.SerializeObject(user2));
            var relatedEntity2     = new RelatedEntity {
                Object = relatedObjectJson2
            };

            var user3 = new User2 {
                Id = 3, Name = "User3", UserTypeName = "Customer"
            };
            var relatedObjectJson3 = new JRaw(JsonConvert.SerializeObject(user3));
            var relatedEntity3     = new RelatedEntity {
                Object = relatedObjectJson3
            };

            var user4 = new User2 {
                Id = 4, Name = "User4", UserTypeName = "Customer"
            };
            var relatedObjectJson4 = new JRaw(JsonConvert.SerializeObject(user4));
            var relatedEntity4     = new RelatedEntity {
                Object = relatedObjectJson4
            };

            var relatedEntities = new List <RelatedEntity> {
                relatedEntity1, relatedEntity2, relatedEntity3, relatedEntity4
            };

            var sorterDictionary = new SortMethodDictionary <UserType>();
            var sortDetails      = new SortDetails
            {
                EntityName     = "UserType",
                RelatedEntity  = "User2",
                EntityProperty = "Name",
                EntityToRelatedEntityProperty = "UserTypeName",
                RelatedEntityType             = RelatedEntity.Type.OneToMany
            };

            // Act
            var actualCollections = sorterDictionary[RelatedEntity.Type.OneToMany](entities, relatedEntities, sortDetails);

            // Assert
            Assert.AreEqual(2, actualCollections.Count);

            Assert.AreEqual("UserType", actualCollections[0].Entity);
            Assert.AreEqual("User2", actualCollections[0].RelatedEntity);
            Assert.AreEqual("1", actualCollections[0].EntityId);
            Assert.AreEqual(2, actualCollections[0].RelatedEntities.Count);
            Assert.AreEqual(relatedObjectJson1, actualCollections[0].RelatedEntities[0].Object);
            Assert.AreEqual(relatedObjectJson2, actualCollections[0].RelatedEntities[1].Object);

            Assert.AreEqual("UserType", actualCollections[1].Entity);
            Assert.AreEqual("User2", actualCollections[1].RelatedEntity);
            Assert.AreEqual("2", actualCollections[1].EntityId);
            Assert.AreEqual(2, actualCollections[1].RelatedEntities.Count);
            Assert.AreEqual(relatedObjectJson3, actualCollections[1].RelatedEntities[0].Object);
            Assert.AreEqual(relatedObjectJson4, actualCollections[1].RelatedEntities[1].Object);
        }
        public async Task <OperationResult> ImportProducer(ProducerImportModel producersAsJson)
        {
            try
            {
                {
                    var rawJson        = JRaw.Parse(producersAsJson.ImportList);
                    var rawHeadersJson = JRaw.Parse(producersAsJson.Headers);

                    var headers         = rawHeadersJson;
                    var fractionObjects = rawJson.Skip(1);

                    foreach (var fractionObj in fractionObjects)
                    {
                        var producerNameExists = int.TryParse(headers[0]["headerValue"].ToString(), out var nameColumn);
                        if (!producerNameExists)
                        {
                            continue;
                        }
                        var existingProducer = FindProducer(nameColumn, headers, fractionObj);
                        if (existingProducer == null)
                        {
                            var producerModel =
                                ProducersHelper.ComposeValues(new ProducerModel(), headers, fractionObj);

                            var newProducer = new Producer
                            {
                                Name          = producerModel.Name,
                                Description   = producerModel.Description,
                                ForeignId     = producerModel.ForeignId,
                                Address       = producerModel.Address,
                                City          = producerModel.City,
                                ZipCode       = producerModel.ZipCode,
                                Phone         = producerModel.Phone,
                                ContactPerson = producerModel.ContactPerson
                            };
                            await newProducer.Create(_dbContext);
                        }
                        else
                        {
                            var producerModel =
                                ProducersHelper.ComposeValues(new ProducerModel(), headers, fractionObj);
                            existingProducer.Name          = producerModel.Name;
                            existingProducer.Description   = producerModel.Description;
                            existingProducer.ForeignId     = producerModel.ForeignId;
                            existingProducer.Address       = producerModel.Address;
                            existingProducer.City          = producerModel.City;
                            existingProducer.ZipCode       = producerModel.ZipCode;
                            existingProducer.Phone         = producerModel.Phone;
                            existingProducer.ContactPerson = producerModel.ContactPerson;

                            if (existingProducer.WorkflowState == Constants.WorkflowStates.Removed)
                            {
                                existingProducer.WorkflowState = Constants.WorkflowStates.Created;
                            }

                            await existingProducer.Update(_dbContext);
                        }
                    }
                }
                return(new OperationResult(true,
                                           _trashInspectionLocalizationService.GetString("ProducerCreated")));
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                _coreHelper.LogException(e.Message);
                return(new OperationResult(false,
                                           _trashInspectionLocalizationService.GetString("ErrorWhileCreatingProducer")));
            }
        }
Пример #13
0
 public MethodSuccessResult(int status, JRaw payload)
     : base(HttpStatusCode.OK)
 {
     this.Status  = status;
     this.Payload = payload;
 }
Пример #14
0
        /// <summary>
        /// Creates the default JWT payload.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="clock">The clock.</param>
        /// <param name="options">The options</param>
        /// <param name="logger">The logger.</param>
        /// <returns></returns>
        /// <exception cref="Exception">
        /// </exception>
        public static JwtPayload CreateJwtPayload(this Token token, ISystemClock clock, IdentityServerOptions options, ILogger logger)
        {
            var issuedAtClaims = token.Claims.Where(x => x.Type == JwtClaimTypes.IssuedAt).ToArray();
            var payload        = new JwtPayload(
                token.Issuer,
                null,
                null,
                clock.UtcNow.UtcDateTime,
                clock.UtcNow.UtcDateTime.AddSeconds(token.Lifetime),
                issuedAtClaims.FirstOrDefault().GetDateTime());

            foreach (var aud in token.Audiences)
            {
                payload.AddClaim(new Claim(JwtClaimTypes.Audience, aud));
            }

            var amrClaims   = token.Claims.Where(x => x.Type == JwtClaimTypes.AuthenticationMethod).ToArray();
            var scopeClaims = token.Claims.Where(x => x.Type == JwtClaimTypes.Scope).ToArray();
            var jsonClaims  = token.Claims.Where(x => x.ValueType == IdentityServerConstants.ClaimValueTypes.Json).ToList();

            // add confirmation claim if present (it's JSON valued)
            if (token.Confirmation.IsPresent())
            {
                jsonClaims.Add(new Claim(JwtClaimTypes.Confirmation, token.Confirmation, IdentityServerConstants.ClaimValueTypes.Json));
            }

            var normalClaims = token.Claims
                               .Except(amrClaims)
                               .Except(jsonClaims)
                               .Except(scopeClaims)
                               .Except(issuedAtClaims);

            payload.AddClaims(normalClaims);

            // scope claims
            if (!scopeClaims.IsNullOrEmpty())
            {
                var scopeValues = scopeClaims.Select(x => x.Value).ToArray();

                if (options.EmitScopesAsSpaceDelimitedStringInJwt)
                {
                    payload.Add(JwtClaimTypes.Scope, string.Join(" ", scopeValues));
                }
                else
                {
                    payload.Add(JwtClaimTypes.Scope, scopeValues);
                }
            }

            // amr claims
            if (!amrClaims.IsNullOrEmpty())
            {
                var amrValues = amrClaims.Select(x => x.Value).Distinct().ToArray();
                payload.Add(JwtClaimTypes.AuthenticationMethod, amrValues);
            }

            // deal with json types
            // calling ToArray() to trigger JSON parsing once and so later
            // collection identity comparisons work for the anonymous type
            try
            {
                var jsonTokens = jsonClaims.Select(x => new { x.Type, JsonValue = JRaw.Parse(x.Value) }).ToArray();

                var jsonObjects      = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Object).ToArray();
                var jsonObjectGroups = jsonObjects.GroupBy(x => x.Type).ToArray();
                foreach (var group in jsonObjectGroups)
                {
                    if (payload.ContainsKey(group.Key))
                    {
                        throw new Exception($"Can't add two claims where one is a JSON object and the other is not a JSON object ({group.Key})");
                    }

                    if (group.Skip(1).Any())
                    {
                        // add as array
                        payload.Add(group.Key, group.Select(x => x.JsonValue).ToArray());
                    }
                    else
                    {
                        // add just one
                        payload.Add(group.Key, group.First().JsonValue);
                    }
                }

                var jsonArrays      = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Array).ToArray();
                var jsonArrayGroups = jsonArrays.GroupBy(x => x.Type).ToArray();
                foreach (var group in jsonArrayGroups)
                {
                    if (payload.ContainsKey(group.Key))
                    {
                        throw new Exception(
                                  $"Can't add two claims where one is a JSON array and the other is not a JSON array ({group.Key})");
                    }

                    var newArr = new List <JToken>();
                    foreach (var arrays in group)
                    {
                        var arr = (JArray)arrays.JsonValue;
                        newArr.AddRange(arr);
                    }

                    // add just one array for the group/key/claim type
                    payload.Add(group.Key, newArr.ToArray());
                }

                var unsupportedJsonTokens     = jsonTokens.Except(jsonObjects).Except(jsonArrays).ToArray();
                var unsupportedJsonClaimTypes = unsupportedJsonTokens.Select(x => x.Type).Distinct().ToArray();
                if (unsupportedJsonClaimTypes.Any())
                {
                    throw new Exception(
                              $"Unsupported JSON type for claim types: {unsupportedJsonClaimTypes.Aggregate((x, y) => x + ", " + y)}");
                }

                return(payload);
            }
            catch (Exception ex)
            {
                logger.LogCritical(ex, "Error creating a JSON valued claim");
                throw;
            }
        }
Пример #15
0
 protected virtual void VisitRaw(JRaw json, TContext context)
 {
 }