public FilesEventPersistence(
            ILog log,
            IJsonSerializer jsonSerializer,
            IFilesEventStoreConfiguration configuration,
            IFilesEventLocator filesEventLocator)
        {
            _log = log;
            _jsonSerializer = jsonSerializer;
            _filesEventLocator = filesEventLocator;
            _logFilePath = Path.Combine(configuration.StorePath, "Log.store");

            if (File.Exists(_logFilePath))
            {
                var json = File.ReadAllText(_logFilePath);
                var eventStoreLog = _jsonSerializer.Deserialize<EventStoreLog>(json);
                _globalSequenceNumber = eventStoreLog.GlobalSequenceNumber;
                _eventLog = eventStoreLog.Log ?? new Dictionary<long, string>();

                if (_eventLog.Count != _globalSequenceNumber)
                {
                    eventStoreLog = RecreateEventStoreLog(configuration.StorePath);
                    _globalSequenceNumber = eventStoreLog.GlobalSequenceNumber;
                    _eventLog = eventStoreLog.Log;
                }
            }
            else
            {
                _eventLog = new Dictionary<long, string>();
            }
        }
Example #2
0
        public MainWindow()
        {
            InitializeComponent();
            ConnectionsListView.ItemsSource = _storageAccountConnections;
            IDeploymentRepositoryFactory deploymentRepositoryFactory = new DeploymentRepositoryFactory();
            _deploymentRepositoryManager = new DeploymentRepositoryManager(deploymentRepositoryFactory);
            _jsonSerializer = new JsonSerializer(new DiagnosticsTraceWriter());
            _deploymentConfigSerializer = new JsonDeploymentConfigSerializer(_jsonSerializer);
            if (File.Exists(SettingsFilePath))
            {
                string json = File.ReadAllText(SettingsFilePath);
                _storageAccountConnections = _jsonSerializer.Deserialize<List<StorageAccountConnectionInfo>>(json);
                ConnectionsListView.ItemsSource = _storageAccountConnections;
            }

            if (!Directory.Exists(DeploymentsConfigsDirPath))
            {
                Directory.CreateDirectory(DeploymentsConfigsDirPath);
            }

	        _deploymentConfigFileWatcher = new FileSystemWatcher
	        {
		        Path = Path.GetFullPath(DeploymentsConfigsDirPath),
		        NotifyFilter = NotifyFilters.LastWrite,
		        Filter = "*.json"
	        };
	        _deploymentConfigFileWatcher.Changed += OnDeploymentConfigFileChanged;
            _deploymentConfigFileWatcher.EnableRaisingEvents = true;
        }
        public SettingsResponse GetSettings(ExceptionlessConfiguration config, IJsonSerializer serializer) {
            HttpWebResponse response;
            try {
                var request = CreateHttpWebRequest(config, "projects/config");
                response = request.GetJsonAsync().Result as HttpWebResponse;
            } catch (Exception ex) {
                var message = String.Concat("Unable to retrieve configuration settings. Exception: ", ex.GetMessage());
                return new SettingsResponse(false, message: message);
            }

            if (response == null || response.StatusCode != HttpStatusCode.OK)
                return new SettingsResponse(false, message: String.Format("Unable to retrieve configuration settings: {0}", GetResponseMessage(response)));

            var json = response.GetResponseText();
            if (String.IsNullOrWhiteSpace(json))
                return new SettingsResponse(false, message: "Invalid configuration settings.");

            var settings = serializer.Deserialize<ClientConfiguration>(json);
            return new SettingsResponse(true, settings.Settings, settings.Version);
        }
 /// <summary>
 /// Deserializes a json payload into an object payload.
 /// </summary>
 /// <param name="json">The json payload.</param>
 /// <returns>The deserialized object payload.</returns>
 protected virtual TPayload[] Deserialize(string json)
 {
     return(_serializer.Deserialize <TPayload[]>(json));
 }
Example #5
0
        public async Task RunBatchAsync(QualificationRunOptions runOptions)
        {
            _runOptions = runOptions;

            if (!FileHelper.FileExists(runOptions.ConfigurationFile))
            {
                throw new QualificationRunException(ConfigurationFileNotFound(runOptions.ConfigurationFile));
            }

            setupOutputFolder();

            dynamic qualificationPlan = await _jsonSerializer.Deserialize <dynamic>(runOptions.ConfigurationFile);

            IReadOnlyList <Project> projects = GetListFrom <Project>(qualificationPlan.Projects);

            if (projects == null)
            {
                throw new QualificationRunException(ProjectsNotDefinedInQualificationFile);
            }

            IReadOnlyList <SimulationPlot> allPlots  = retrieveProjectPlots(qualificationPlan);
            IReadOnlyList <Input>          allInputs = retrieveInputs(qualificationPlan);

            var begin = DateTime.UtcNow;

            await updateProjectsFullPath(projects);

            //Configurations only need to be created once!
            var projectConfigurations = await Task.WhenAll(projects.Select(p => createQualifcationConfigurationFor(p, projects, allPlots, allInputs)));

            _logger.AddDebug("Copying static files");
            StaticFiles staticFiles = await copyStaticFiles(qualificationPlan);

            _logger.AddInfo("Starting validation runs...");
            var validations = await Task.WhenAll(projectConfigurations.Select(validateProject));

            var invalidConfigurations = validations.Where(x => !x.Success).ToList();

            if (invalidConfigurations.Any())
            {
                throw new QualificationRunException(errorMessageFrom(invalidConfigurations));
            }

            //Run all qualification projects
            _logger.AddInfo("Starting qualification runs...");
            var runResults = await Task.WhenAll(projectConfigurations.Select(runQualification));

            var invalidRunResults = runResults.Where(x => !x.Success).ToList();

            if (invalidRunResults.Any())
            {
                throw new QualificationRunException(errorMessageFrom(invalidRunResults));
            }

            await createReportConfigurationPlan(runResults, staticFiles, qualificationPlan);

            var end       = DateTime.UtcNow;
            var timeSpent = end - begin;

            _logger.AddInfo($"Qualification scenario finished in {timeSpent.ToDisplay()}");
        }
    public async Task Publish_Schedule_Is_Mapped_Correctly()
    {
        const string    UsIso               = "en-US";
        const string    DkIso               = "da-DK";
        const string    SweIso              = "sv-SE";
        var             contentTypeService  = GetRequiredService <IContentTypeService>();
        var             contentService      = GetRequiredService <IContentService>();
        var             localizationService = GetRequiredService <ILocalizationService>();
        IJsonSerializer serializer          = GetRequiredService <IJsonSerializer>();

        var contentType = new ContentTypeBuilder()
                          .WithContentVariation(ContentVariation.Culture)
                          .Build();

        contentTypeService.Save(contentType);

        var dkLang = new LanguageBuilder()
                     .WithCultureInfo(DkIso)
                     .WithIsDefault(false)
                     .Build();

        var sweLang = new LanguageBuilder()
                      .WithCultureInfo(SweIso)
                      .WithIsDefault(false)
                      .Build();

        localizationService.Save(dkLang);
        localizationService.Save(sweLang);

        var content = new ContentBuilder()
                      .WithoutIdentity()
                      .WithContentType(contentType)
                      .WithCultureName(UsIso, "Same Name")
                      .WithCultureName(SweIso, "Same Name")
                      .WithCultureName(DkIso, "Same Name")
                      .Build();

        contentService.Save(content);
        var schedule = new ContentScheduleCollection();

        var dkReleaseDate = new DateTime(2022, 06, 22, 21, 30, 42);
        var dkExpireDate  = new DateTime(2022, 07, 15, 18, 00, 00);

        var sweReleaseDate = new DateTime(2022, 06, 23, 22, 30, 42);
        var sweExpireDate  = new DateTime(2022, 07, 10, 14, 20, 00);

        schedule.Add(DkIso, dkReleaseDate, dkExpireDate);
        schedule.Add(SweIso, sweReleaseDate, sweExpireDate);
        contentService.PersistContentSchedule(content, schedule);

        var url = PrepareApiControllerUrl <ContentController>(x => x.GetById(content.Id));

        HttpResponseMessage response = await Client.GetAsync(url);

        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

        var text = await response.Content.ReadAsStringAsync();

        text = text.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix);
        var display = serializer.Deserialize <ContentItemDisplayWithSchedule>(text);

        Assert.IsNotNull(display);
        Assert.AreEqual(1, _messageCount);

        var dkVariant = display.Variants.FirstOrDefault(x => x.Language?.IsoCode == DkIso);

        Assert.IsNotNull(dkVariant);
        Assert.AreEqual(dkReleaseDate, dkVariant.ReleaseDate);
        Assert.AreEqual(dkExpireDate, dkVariant.ExpireDate);

        var sweVariant = display.Variants.FirstOrDefault(x => x.Language?.IsoCode == SweIso);

        Assert.IsNotNull(sweVariant);
        Assert.AreEqual(sweReleaseDate, sweVariant.ReleaseDate);
        Assert.AreEqual(sweExpireDate, sweVariant.ExpireDate);

        var usVariant = display.Variants.FirstOrDefault(x => x.Language?.IsoCode == UsIso);

        Assert.IsNotNull(usVariant);
        Assert.IsNull(usVariant.ReleaseDate);
        Assert.IsNull(usVariant.ExpireDate);
    }
Example #7
0
        /// <inheritdoc />
        public void Validate(string payloadJson, string decodedCrypto, string decodedSignature)
        {
            if (decodedCrypto != decodedSignature)
            {
                throw new SignatureVerificationException("Invalid signature")
                      {
                          Expected = decodedCrypto,
                          Received = decodedSignature
                      };
            }

            var payloadData = _jsonSerializer.Deserialize <Dictionary <string, object> >(payloadJson);

            var now = _dateTimeProvider.GetNow();
            var secondsSinceEpoch = Math.Round((now - UnixEpoch).TotalSeconds);

            // verify exp claim https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.4
            object expObj;

            if (payloadData.TryGetValue("exp", out expObj))
            {
                if (expObj == null)
                {
                    throw new SignatureVerificationException("Claim 'exp' must be a number.");
                }

                double expValue;
                try
                {
                    expValue = Convert.ToDouble(expObj);
                }
                catch
                {
                    throw new SignatureVerificationException("Claim 'exp' must be a number.");
                }

                if (secondsSinceEpoch >= expValue)
                {
                    throw new TokenExpiredException("Token has expired.")
                          {
                              Expiration  = UnixEpoch.AddSeconds(expValue),
                              PayloadData = payloadData
                          };
                }
            }

            // verify nbf claim https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.5
            object nbfObj;

            if (payloadData.TryGetValue("nbf", out nbfObj))
            {
                if (nbfObj == null)
                {
                    throw new SignatureVerificationException("Claim 'nbf' must be a number.");
                }

                double nbfValue;
                try
                {
                    nbfValue = Convert.ToDouble(nbfObj);
                }
                catch
                {
                    throw new SignatureVerificationException("Claim 'nbf' must be a number.");
                }

                if (secondsSinceEpoch < nbfValue)
                {
                    throw new SignatureVerificationException("Token is not yet valid.");
                }
            }
        }
Example #8
0
 public object Deserialize(string json, Type returnType)
 {
     return(_jsonSerializer.Deserialize(json, returnType));
 }
Example #9
0
        /// <inheritdoc />
        public IDictionary <string, object> DecodeToObject(string token, byte[] key, bool verify)
        {
            var payloadJson = Decode(token, key, verify);

            return(_jsonSerializer.Deserialize <Dictionary <string, object> >(payloadJson));
        }
Example #10
0
 public static T SerializeAndDeserialize <T>(this object value)
 {
     return(DefaultSerializer.Deserialize <T>(DefaultSerializer.Serialize(value)));
 }
Example #11
0
        private static async Task <GitHubResponse <T> > ParseResponse <T>(HttpResponseMessage response) where T : new()
        {
            var ghr = new GitHubResponse <T> {
                StatusCode = (int)response.StatusCode
            };

            foreach (var h in response.Headers)
            {
                if (h.Key.Equals("X-RateLimit-Limit"))
                {
                    ghr.RateLimitLimit = Convert.ToInt32(h.Value.First());
                }
                else if (h.Key.Equals("X-RateLimit-Remaining"))
                {
                    ghr.RateLimitRemaining = Convert.ToInt32(h.Value.First());
                }
                else if (h.Key.Equals("ETag"))
                {
                    ghr.ETag = h.Value.First().Replace("\"", "").Trim();
                }
                else if (h.Key.Equals("Link"))
                {
                    var s = h.Value.First().Split(',');
                    foreach (var link in s)
                    {
                        var splitted = link.Split(';');
                        var url      = splitted[0].Trim();
                        var what     = splitted[1].Trim();
                        what = what.Substring(5);
                        what = what.Substring(0, what.Length - 1);
                        url  = url.Substring(1);
                        url  = url.Substring(0, url.Length - 1);

                        if (what.Equals("next"))
                        {
                            ghr.More = GitHubRequest.Get <T>(url);
                        }
                    }
                }
            }

            // Booleans have a special definition in the github responses.
            // They typically represent a status code Not Found = false
            // or 204 = true and 205 (reset content)
            if (typeof(T) == typeof(bool) && (ghr.StatusCode == 204 || ghr.StatusCode == 205 || ghr.StatusCode == 404))
            {
                var b = ghr.StatusCode == 204 || ghr.StatusCode == 205;
                ghr.Data = (T)(object)(b);
                return(ghr);
            }

            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (response.StatusCode < (HttpStatusCode)200 || response.StatusCode >= (HttpStatusCode)300)
            {
                throw StatusCodeException.FactoryCreate(response, content);
            }

            ghr.Data = Serializer.Deserialize <T>(content);

            return(ghr);
        }
Example #12
0
        public void Intercept(IInvocation invocation)
        {
            if (_cache == null)
            {
                invocation.Proceed();
                return;
            }
            var cacheAttribute = GetCacheAttribute(invocation);

            if (cacheAttribute == null)
            {
                invocation.Proceed();
                return;
            }
            var delegateType = GetDelegateType(invocation);

            if (cacheAttribute.CacheAction == CacheAction.Remove)
            {
                switch (delegateType)
                {
                case MethodType.AsyncAction:
                    invocation.ReturnValue = ExcuteRemoveAsync(invocation, cacheAttribute);
                    break;

                case MethodType.Synchronous:
                case MethodType.SynchronousVoid:
                    ExcuteRemove(invocation, cacheAttribute);
                    break;

                case MethodType.AsyncFunction:
                    ExecuteHandleAsyncWithResultUsingReflection(invocation, cacheAttribute);
                    break;
                }
            }
            else
            {
                if (delegateType == MethodType.AsyncAction || MethodType.SynchronousVoid == delegateType)
                {
                    invocation.Proceed();
                    return;
                }
                if (_cache.SimpleIsExistCache(cacheAttribute.CacheName))
                {
                    var cacheValue = _cache.SimpleGetCache <string>(cacheAttribute.CacheName);
                    if (delegateType == MethodType.Synchronous)
                    {
                        invocation.ReturnValue = _jsonSerializer.Deserialize(cacheValue, invocation.Method.ReturnType);
                    }
                    else
                    {
                        invocation.ReturnValue = _jsonSerializer.DeserializeAsync(cacheValue, invocation.Method.ReturnType.GetGenericArguments()[0]);
                    }
                }
                else
                {
                    if (delegateType == MethodType.Synchronous)
                    {
                        invocation.Proceed();
                        AddCache(invocation.ReturnValue, cacheAttribute);
                    }
                    else
                    {
                        ExecuteHandleAsyncWithResultUsingReflection(invocation, cacheAttribute);
                    }
                }
            }
        }
Example #13
0
        /// <summary>
        /// Reads the json.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value.</param>
        /// <param name="serializer">The serializer.</param>
        /// <returns>System.Object.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var obj = _jsonSerializer.Deserialize(objectType, reader, _configuration);

            return(obj);
        }
Example #14
0
            // If you chnage enything in the sql query tou need to take care to
            // FeedAggregateQuery and DocumentFeedWithFilterQuery as well
            public async Task <IEnumerable <QuestionFeedDto> > GetAsync(QuestionFeedWithFliterQuery query, CancellationToken token)
            {
                const string sqlWithCourse = @"with cte as (
select top 1 * from(select 1 as o, u2.Id as UniversityId, COALESCE(u2.country, u.country) as Country, u.id as userid
 from sb.[user] u
 left
 join sb.University u2 on u.UniversityId2 = u2.Id
 where u.id = @userid
 union
 select 2, null, @country, 0) t
    order by o
)
SELECT  'q' as type
,q.CourseId as Course
,q.UniversityId as UniversityId
,q.Updated as DateTime
,(select q.Id as Id,
q.Text as Text,
q.CourseId as Course,
(SELECT count(*) as y0_ FROM sb.[Answer] this_0_ WHERE(this_0_.QuestionId = q.Id and this_0_.State = 'Ok')) as Answers,
q.Updated as DateTime,
q.Language as CultureInfo
--TODO from cross join
,x.Id as 'FirstAnswer.User.Id'
,x.Image as 'FirstAnswer.User.Image'
,x.Name as 'FirstAnswer.User.Name'
,x.Text as 'FirstAnswer.Text'
,x.Created as 'FirstAnswer.DateTime'
,u.Id as 'User.Id'
,u.Name as 'User.Name'
,u.Image as 'User.Image'
,'Question' as documentType for json path) JsonArray
,case when (select UserId from sb.UsersRelationship ur where ur.FollowerId = @userId and u.Id = ur.UserId) = u.id then 1 else 0 end as IsFollow
FROM sb.[Question] q
join sb.[user] u
	on q.UserId = u.Id
left join sb.University un on q.UniversityId = un.Id
outer apply (
select top 1 text, u.id, u.name, u.image, a.Created from sb.Answer a join sb.[user] u on a.userid = u.id
where a.QuestionId = q.Id and state = 'Ok' order by a.created
) as x
join cte on un.country = cte.country or u.country = cte.country
where
    q.Updated > GetUtcDATE() - 182
and q.courseId = @course
and q.State = 'Ok'
order by
case when un.Id = cte.UniversityId or un.Id is null then 0 else  DATEDiff(hour, GetUtcDATE() - 180, GetUtcDATE()) end  +
DATEDiff(hour, q.Updated, GetUtcDATE()) +
case when case when (select UserId from sb.UsersRelationship ur where ur.FollowerId = @userId and u.Id = ur.UserId) = u.id then 1 else 0 end = 1 then 0 else DATEDiff(hour, GetUtcDATE() - 7, GetUtcDATE()) end
OFFSET @page*@pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY";

                const string sqlWithoutCourse = @"with cte as (
select top 1 * from (select 1 as o, u2.Id as UniversityId, COALESCE(u2.country,u.country) as Country, u.id as userid
 from sb.[user] u
 left join sb.University u2 on u.UniversityId2 = u2.Id
 where u.id = @userid
 union
 select 2,null,@country,0) t
 order by o
)


SELECT  'q' as type
,q.CourseId as Course
,q.UniversityId as UniversityId
,q.Updated as DateTime
,(select q.Id as Id,
q.Text as Text,
q.CourseId as Course,
(SELECT count(*) as y0_ FROM sb.[Answer] this_0_ WHERE (this_0_.QuestionId = q.Id and this_0_.State = 'Ok')) as Answers,
q.Updated as DateTime,
q.Language as CultureInfo
--TODO from cross join
,x.Id as 'FirstAnswer.User.Id'
,x.Image as 'FirstAnswer.User.Image'
,x.Name as 'FirstAnswer.User.Name'
,x.Text as 'FirstAnswer.Text'
,x.Created as 'FirstAnswer.DateTime'
,u.Id as 'User.Id'
,u.Name as 'User.Name'
,u.Image as 'User.Image'
,'Question' as documentType for json path) JsonArray
,case when (select UserId from sb.UsersRelationship ur where ur.FollowerId = @userId and u.Id = ur.UserId) = u.id then 1 else 0 end as IsFollow
FROM sb.[Question] q
join sb.[user] u
	on q.UserId = u.Id
left join sb.University un on q.UniversityId = un.Id
outer apply (
select  top 1 text,u.id,u.name,u.image, a.Created from sb.Answer a join sb.[user] u on a.userid = u.id
where a.QuestionId = q.Id and state = 'Ok' order by a.created

) as x
join cte on un.country = cte.country or u.country = cte.country
where 
    q.Updated > GETUTCDATE() - 182
and q.State = 'Ok'
and (q.CourseId in (select courseId from sb.usersCourses where userid = cte.userid) or @userid <= 0)
order by
case when un.Id = cte.UniversityId or un.Id is null then 0 else  DATEDiff(hour, GetUtcDATE() - 180, GetUtcDATE()) end  +
DATEDiff(hour, q.Updated, GetUtcDATE()) +
case when case when (select UserId from sb.UsersRelationship ur where ur.FollowerId = @userId and u.Id = ur.UserId) = u.id then 1 else 0 end = 1 then 0 else DATEDiff(hour, GetUtcDATE() - 7, GetUtcDATE()) end
OFFSET @page*@pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY";

                var sql = query.Course == null ? sqlWithoutCourse : sqlWithCourse;

                var result = new List <QuestionFeedDto>();

                using var conn   = _dapperRepository.OpenConnection();
                using var reader = await conn.ExecuteReaderAsync(sql, new
                {
                    query.Page,
                    query.UserId,
                    query.Country,
                    query.Course,
                    query.PageSize
                });

                if (reader.Read())
                {
                    var colJson = reader.GetOrdinal("JsonArray");
                    do
                    {
                        var v         = reader.GetString(colJson);
                        var questions = _jsonSerializer.Deserialize <IEnumerable <QuestionFeedDto> >(v);
                        result.Add(questions.First());
                    } while (reader.Read());
                }

                return(result);
            }
Example #15
0
        public async Task <T> Read <T>()
        {
            string inputText = await GetInputText().ConfigureAwait(false);

            return(_serializer.Deserialize <T>(inputText));
        }
    public void Should_Serialize_And_Deserialize()
    {
        var featureListDto = new GetFeatureListResultDto
        {
            Groups = new List<FeatureGroupDto>
                {
                    new FeatureGroupDto
                    {
                        Name = "MyGroup",
                        DisplayName = "MyGroup",
                        Features = new List<FeatureDto>
                        {
                            new FeatureDto
                            {
                                ValueType = new FreeTextStringValueType
                                {
                                    Validator = new BooleanValueValidator()
                                }
                            },
                            new FeatureDto
                            {
                                ValueType = new SelectionStringValueType
                                {
                                    ItemSource = new StaticSelectionStringValueItemSource(
                                        new LocalizableSelectionStringValueItem
                                        {
                                            Value = "TestValue",
                                            DisplayText = new LocalizableStringInfo("TestResourceName", "TestName")
                                        }),
                                    Validator = new AlwaysValidValueValidator()
                                }
                            },
                            new FeatureDto
                            {
                                ValueType = new ToggleStringValueType
                                {
                                    Validator = new NumericValueValidator
                                    {
                                        MaxValue = 1000,
                                        MinValue = 10
                                    }
                                }
                            },
                            new FeatureDto
                            {
                                Provider = new FeatureProviderDto
                                {
                                    Name = "FeatureName",
                                    Key = "FeatureKey"
                                }
                            }
                        }
                    }
                }
        };

        var serialized = _jsonSerializer.Serialize(featureListDto, indented: true);

        var featureListDto2 = _jsonSerializer.Deserialize<GetFeatureListResultDto>(serialized);

        featureListDto2.ShouldNotBeNull();
        featureListDto2.Groups[0].Features[0].ValueType.ShouldBeOfType<FreeTextStringValueType>();
        featureListDto2.Groups[0].Features[0].ValueType.Validator.ShouldBeOfType<BooleanValueValidator>();

        featureListDto2.Groups[0].Features[1].ValueType.ShouldBeOfType<SelectionStringValueType>();
        featureListDto2.Groups[0].Features[1].ValueType.Validator.ShouldBeOfType<AlwaysValidValueValidator>();
        featureListDto2.Groups[0].Features[1].ValueType.As<SelectionStringValueType>().ItemSource.Items.ShouldBeOfType<LocalizableSelectionStringValueItem[]>();
        featureListDto2.Groups[0].Features[1].ValueType.As<SelectionStringValueType>().ItemSource.Items.ShouldContain(x =>
            x.Value == "TestValue" && x.DisplayText.ResourceName == "TestResourceName" &&
            x.DisplayText.Name == "TestName");

        featureListDto2.Groups[0].Features[2].ValueType.ShouldBeOfType<ToggleStringValueType>();
        featureListDto2.Groups[0].Features[2].ValueType.Validator.ShouldBeOfType<NumericValueValidator>();
        featureListDto2.Groups[0].Features[2].ValueType.Validator.As<NumericValueValidator>().MaxValue.ShouldBe(1000);
        featureListDto2.Groups[0].Features[2].ValueType.Validator.As<NumericValueValidator>().MinValue.ShouldBe(10);

        featureListDto2.Groups[0].Features[3].Provider.Name.ShouldBe("FeatureName");
        featureListDto2.Groups[0].Features[3].Provider.Key.ShouldBe("FeatureKey");
    }
Example #17
0
 public void Process(HttpContext context)
 {
     var writeParameters = jsonSerializer.Deserialize<WriteParameters>(context.Request.Body);
     if (disk.Write(writeParameters.Key, writeParameters.Value))
         replicator.Replicate(writeParameters.Key, writeParameters.Value);
 }
Example #18
0
        /// <inheritdoc />
        /// <exception cref="ArgumentException" />
        /// <exception cref="ArgumentNullException" />
        /// <exception cref="ArgumentOutOfRangeException" />
        /// <exception cref="FormatException" />
        public T DecodeToObject <T>(string token)
        {
            var payload = Decode(token);

            return(_jsonSerializer.Deserialize <T>(payload));
        }
Example #19
0
        public async Task <IQueryResponse <TResponse> > PostAsync <TResponse, TRequest>(string endpoint, IDruidRequest <TRequest> request)
            where TRequest : QueryRequestData
        {
            var requestString = _json.Serialize(request.RequestData);

            var response = await _client.PostAsync(endpoint, new StringContent(requestString, Encoding.UTF8, "application/json"));

            if (response.IsSuccessStatusCode)
            {
                var responseString = await response.Content.ReadAsStringAsync();

                var data = _json.Deserialize <TResponse>(responseString);

                var queryResponse = new DruidResponse <TResponse>
                {
                    Data        = data,
                    RequestData = new DruidQueryRequestData
                    {
                        Address = _client.BaseAddress + endpoint,
                        Method  = "POST",
                        Query   = requestString
                    }
                };

                return(queryResponse);
            }
            else
            {
                // Error or timeout, try and read the error response (if any)
                Exception     ex            = new DruidClientException($"Failed request to {_client.BaseAddress}{endpoint} with status {response.StatusCode}");
                ErrorResponse errorResponse = null;

                try
                {
                    var responseString = await response.Content.ReadAsStringAsync();

                    errorResponse = _json.Deserialize <ErrorResponse>(responseString);
                }
                catch (Exception e)
                {
                    ex = new DruidClientException($"Failed request to {_client.BaseAddress}{endpoint} with status {response.StatusCode}", e);
                }

                if (errorResponse != null)
                {
                    switch (errorResponse.ErrorClass)
                    {
                    case "io.druid.query.ResourceLimitExceededException":
                        ex = new DruidResourceExceededException(errorResponse.ErrorMessage);
                        break;

                    case "com.fasterxml.jackson.databind.JsonMappingException":
                        ex = new DruidJsonMappingException(errorResponse.ErrorMessage);
                        break;

                    case "io.druid.java.util.common.RE":
                        if (errorResponse.ErrorMessage.Contains("ReadTimeoutException"))
                        {
                            ex = new DruidTimeoutException(errorResponse.ErrorMessage);
                        }

                        break;

                    default:
                        var message = errorResponse.ErrorMessage ?? errorResponse.Error;
                        ex = new DruidClientException($"Failed request to {_client.BaseAddress}{endpoint} {message}");
                        break;
                    }

                    ex.Data["host"]  = errorResponse.Host;
                    ex.Data["error"] = errorResponse.Error;
                }

                ex.Data["query"] = requestString;
                throw ex;
            }
        }
Example #20
0
        private IList <TestFileSummary> ReadFromStream(StreamReader stream, TestContext testContext, TestOptions testOptions, IList <StreamingTestFileContext> streamingTestFileContexts, IList <Action <StreamingTestFileContext> > deferredEvents, ITestMethodRunnerCallback callback, bool debugEnabled)
        {
            var testIndex = 0;

            string line;
            StreamingTestFileContext currentTestFileContext = null;

            if (streamingTestFileContexts.Count == 1)
            {
                currentTestFileContext = streamingTestFileContexts.First();
            }


            while ((line = stream.ReadLine()) != null)
            {
                if (debugEnabled)
                {
                    Console.WriteLine(line);
                }

                var match = prefixRegex.Match(line);
                if (!match.Success)
                {
                    continue;
                }
                var type = match.Groups["type"].Value;
                var json = match.Groups["json"].Value;

                // Only update last event timestamp if it is an important event.
                // Log and error could happen even though no test progress is made
                if (!type.Equals("Log") && !type.Equals("Error"))
                {
                    lastTestEvent = DateTime.Now;
                }


                try
                {
                    switch (type)
                    {
                    case "FileStart":

                        FireFileStarted(callback, testContext);

                        break;

                    case "CoverageObject":

                        var jsCov = jsonSerializer.Deserialize <JsCoverage>(json);

                        if (currentTestFileContext == null)
                        {
                            AddDeferredEvent((fileContext) => FireCoverageObject(callback, fileContext, jsCov), deferredEvents);
                        }
                        else
                        {
                            FireCoverageObject(callback, currentTestFileContext, jsCov);
                        }

                        break;

                    case "FileDone":

                        var jsFileDone = jsonSerializer.Deserialize <JsFileDone>(json);
                        FireFileFinished(callback, testContext.InputTestFilesString, streamingTestFileContexts, jsFileDone);

                        break;

                    case "TestStart":
                        var jsTestCaseStart = jsonSerializer.Deserialize <JsTestCase>(json);
                        StreamingTestFileContext newContext = null;
                        var testName   = jsTestCaseStart.TestCase.TestName.Trim();
                        var moduleName = (jsTestCaseStart.TestCase.ModuleName ?? "").Trim();


                        var fileContexts = GetFileMatches(testName, streamingTestFileContexts);
                        if (fileContexts.Count == 0 && currentTestFileContext == null)
                        {
                            // If there are no matches and not file context has been used yet
                            // then just choose the first context
                            newContext = streamingTestFileContexts[0];
                        }
                        else if (fileContexts.Count == 0)
                        {
                            // If there is already a current context and no matches we just keep using that context
                            // unless this test name has been used already in the current context. In that case
                            // move to the next one that hasn't seen this file yet

                            var testAlreadySeenInCurrentContext = currentTestFileContext.HasTestBeenSeen(moduleName, testName);
                            if (testAlreadySeenInCurrentContext)
                            {
                                newContext = streamingTestFileContexts.FirstOrDefault(x => !x.HasTestBeenSeen(moduleName, testName)) ?? currentTestFileContext;
                            }
                        }
                        else if (fileContexts.Count > 1)
                        {
                            // If we found the test has more than one file match
                            // try to choose the best match, otherwise just choose the first one

                            // If we have no file context yet take the first one
                            if (currentTestFileContext == null)
                            {
                                newContext = fileContexts.First();
                            }
                            else
                            {
                                // In this case we have an existing file context so we need to
                                // 1. Check to see if this test has been seen already on that context
                                //    if so we need to try the next file context that matches it
                                // 2. If it is not seen yet in the current context and the current context
                                //    is one of the matches then keep using it

                                var testAlreadySeenInCurrentContext = currentTestFileContext.HasTestBeenSeen(moduleName, testName);
                                var currentContextInFileMatches     = fileContexts.Any(x => x == currentTestFileContext);
                                if (!testAlreadySeenInCurrentContext && currentContextInFileMatches)
                                {
                                    // Keep the current context
                                    newContext = currentTestFileContext;
                                }
                                else
                                {
                                    // Either take first not used context OR the first one
                                    newContext = fileContexts.Where(x => !x.IsUsed).FirstOrDefault() ?? fileContexts.First();
                                }
                            }
                        }
                        else if (fileContexts.Count == 1)
                        {
                            // We found a unique match
                            newContext = fileContexts[0];
                        }


                        if (newContext != null && newContext != currentTestFileContext)
                        {
                            currentTestFileContext = newContext;
                            testIndex = 0;
                        }

                        currentTestFileContext.IsUsed = true;

                        currentTestFileContext.MarkTestSeen(moduleName, testName);

                        PlayDeferredEvents(currentTestFileContext, deferredEvents);

                        jsTestCaseStart.TestCase.InputTestFile = currentTestFileContext.ReferencedFile.Path;
                        callback.TestStarted(jsTestCaseStart.TestCase);

                        break;

                    case "TestDone":
                        var jsTestCaseDone   = jsonSerializer.Deserialize <JsTestCase>(json);
                        var currentTestIndex = testIndex;

                        FireTestFinished(callback, currentTestFileContext, jsTestCaseDone, currentTestIndex);

                        testIndex++;

                        break;

                    case "Log":
                        var log = jsonSerializer.Deserialize <JsLog>(json);

                        if (currentTestFileContext != null)
                        {
                            FireLogOutput(callback, currentTestFileContext, log);
                        }
                        else
                        {
                            AddDeferredEvent((fileContext) => FireLogOutput(callback, fileContext, log), deferredEvents);
                        }
                        break;

                    case "Error":
                        var error = jsonSerializer.Deserialize <JsError>(json);
                        if (currentTestFileContext != null)
                        {
                            FireErrorOutput(callback, currentTestFileContext, error);
                        }
                        else
                        {
                            AddDeferredEvent((fileContext) => FireErrorOutput(callback, fileContext, error), deferredEvents);
                        }

                        break;
                    }
                }
                catch (SerializationException e)
                {
                    // Ignore malformed json and move on
                    ChutzpahTracer.TraceError(e, "Recieved malformed json from Phantom in this line: '{0}'", line);
                }
            }

            return(streamingTestFileContexts.Select(x => x.TestFileSummary).ToList());
        }
        /// <summary>
        /// Verifies a user's hashed password
        /// </summary>
        /// <param name="user"></param>
        /// <param name="hashedPassword"></param>
        /// <param name="providedPassword"></param>
        /// <returns></returns>
        /// <remarks>
        /// This will check the user's current hashed password format stored with their user row and use that to verify the hash. This could be any hashes
        /// from the very old v4, to the older v6-v8, to the older aspnet identity and finally to the most recent
        /// </remarks>
        public override PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
        {
            if (user is null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            try
            {
                // Best case and most likely scenario, a modern hash supported by ASP.Net identity.
                PasswordVerificationResult upstreamResult = base.VerifyHashedPassword(user, hashedPassword, providedPassword);
                if (upstreamResult != PasswordVerificationResult.Failed)
                {
                    return(upstreamResult);
                }
            }
            catch (FormatException)
            {
                // hash wasn't a valid base64 encoded string, MS concat the salt bytes and hash bytes and base 64 encode both together.
                // We however historically base 64 encoded the salt bytes and hash bytes separately then concat the strings so we got 2 sets of padding.
                // both salt bytes and hash bytes lengths were not evenly divisible by 3 hence 2 sets of padding.

                // We could check upfront with TryFromBase64String, but not whilst we target netstandard 2.0
                // so might as well just deal with the exception.
            }

            // At this point we either have a legacy password or a bad attempt.

            // Check the supported worst case scenario, a "useLegacyEncoding" password - HMACSHA1 but with password used as key so not unique for users sharing same password
            // This was the standard for v4.
            // Do this first because with useLegacyEncoding the algorithm stored in the database is irrelevant.
            if (LegacyPasswordSecurity.VerifyLegacyHashedPassword(providedPassword, hashedPassword))
            {
                return(PasswordVerificationResult.SuccessRehashNeeded);
            }

            // For users we expect to know the historic algorithm.
            // NOTE: MemberPasswordHasher subclasses this class to deal with the fact that PasswordConfig wasn't stored.
            if (user.PasswordConfig.IsNullOrWhiteSpace())
            {
                return(PasswordVerificationResult.Failed);
            }

            PersistedPasswordSettings?deserialized;

            try
            {
                deserialized = _jsonSerializer.Deserialize <PersistedPasswordSettings>(user.PasswordConfig ?? string.Empty);
            }
            catch
            {
                return(PasswordVerificationResult.Failed);
            }

            if (deserialized?.HashAlgorithm is null || !LegacyPasswordSecurity.SupportHashAlgorithm(deserialized.HashAlgorithm))
            {
                return(PasswordVerificationResult.Failed);
            }

            // Last chance must be HMACSHA256 or SHA1
            return(LegacyPasswordSecurity.VerifyPassword(deserialized.HashAlgorithm, providedPassword, hashedPassword)
                ? PasswordVerificationResult.SuccessRehashNeeded
                : PasswordVerificationResult.Failed);
        }
Example #22
0
        public async Task <FetchTogglesResult> FetchToggles(string etag, CancellationToken cancellationToken)
        {
            const string resourceUri = "api/client/features";

            using (var request = new HttpRequestMessage(HttpMethod.Get, resourceUri))
            {
                SetRequestHeaders(request, clientRequestHeaders);

                if (EntityTagHeaderValue.TryParse(etag, out var etagHeaderValue))
                {
                    request.Headers.IfNoneMatch.Add(etagHeaderValue);
                }

                using (var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                        Logger.Trace($"UNLEASH: Error {response.StatusCode} from server in '{nameof(FetchToggles)}': " + error);

                        return(new FetchTogglesResult
                        {
                            HasChanged = false,
                            Etag = null,
                        });
                    }

                    var newEtag = response.Headers.ETag?.Tag;
                    if (newEtag == etag)
                    {
                        return(new FetchTogglesResult
                        {
                            HasChanged = false,
                            Etag = newEtag,
                            ToggleCollection = null,
                        });
                    }

                    var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                    var toggleCollection = jsonSerializer.Deserialize <ToggleCollection>(stream);

                    if (toggleCollection == null)
                    {
                        return(new FetchTogglesResult
                        {
                            HasChanged = false
                        });
                    }

                    // Success
                    return(new FetchTogglesResult
                    {
                        HasChanged = true,
                        Etag = newEtag,
                        ToggleCollection = toggleCollection
                    });
                }
            }
        }
Example #23
0
        public Response Save(IEnterspeedEntity entity)
        {
            if (entity == null)
            {
                return(new Response
                {
                    Success = false,
                    Exception = new ArgumentNullException(nameof(entity)),
                    Message = "Missing entity"
                });
            }

            HttpResponseMessage response       = null;
            IngestResponse      ingestResponse = null;

            try
            {
                var content = _jsonSerializer.Serialize(entity);

                var buffer      = Encoding.UTF8.GetBytes(content);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                response = _connection.HttpClientConnection.PostAsync(_ingestEndpoint, byteContent)
                           .ConfigureAwait(false)
                           .GetAwaiter()
                           .GetResult();

                var ingestResponseJson = response?.Content
                                         .ReadAsStringAsync()
                                         .ConfigureAwait(false)
                                         .GetAwaiter()
                                         .GetResult();
                if (!string.IsNullOrWhiteSpace(ingestResponseJson))
                {
                    ingestResponse = _jsonSerializer.Deserialize <IngestResponse>(ingestResponseJson);
                }
            }
            catch (Exception e)
            {
                return(new Response
                {
                    Success = false,
                    Status = response?.StatusCode ?? HttpStatusCode.BadRequest,
                    Exception = e
                });
            }

            if (response == null)
            {
                return(new Response
                {
                    Success = false,
                    Exception = new Exception("Failed sending data")
                });
            }

            var statusCode = ingestResponse?.Status ?? response.StatusCode;

            return(new Response
            {
                Message = ingestResponse?.Message,
                Status = statusCode,
                Success = statusCode == HttpStatusCode.OK
            });
        }
Example #24
0
 public object Deserialize(byte[] value, Type type)
 {
     return(_jsonSerializer.Deserialize(type, Encoding.UTF8.GetString(value)));
 }
Example #25
0
        public IDomainEvent Deserialize(ICommittedDomainEvent committedDomainEvent)
        {
            var metadata = (IMetadata)_jsonSerializer.Deserialize <Metadata>(committedDomainEvent.Metadata);

            return(Deserialize(committedDomainEvent.AggregateId, committedDomainEvent.Data, metadata));
        }
Example #26
0
 public static T SerializeAndDeserialize <T>(this T value)
 {
     return(DefaultSerializer.Deserialize <Tuple <T> >(DefaultSerializer.Serialize(Tuple.Create(value))).Item1);
 }
Example #27
0
 /// <summary>
 /// Loads the object from the given string value.
 /// </summary>
 public static T LoadJson <T>(this IJsonSerializer serializer, string value)
 => (T)serializer.Deserialize(new StringReader(value), typeof(T));
Example #28
0
        public static T SerializeAndDeserialize <T>(this object value)
        {
            var json = DefaultSerializer.Serialize(value);

            return(DefaultSerializer.Deserialize <T>(json));
        }
        public SettingsResponse GetSettings(ExceptionlessConfiguration config, int version, IJsonSerializer serializer) {
            if (!config.IsValid)
                return new SettingsResponse(false, message: "Invalid client configuration settings.");

            string url = String.Format("{0}/projects/config?v={1}", GetServiceEndPoint(config), version);

            HttpResponseMessage response;
            try {
                _client.Value.AddAuthorizationHeader(config.ApiKey);
                response = _client.Value.GetAsync(url).ConfigureAwait(false).GetAwaiter().GetResult();
            } catch (Exception ex) {
                var message = String.Concat("Unable to retrieve configuration settings. Exception: ", ex.GetMessage());
                return new SettingsResponse(false, message: message);
            }

            if (response != null && response.StatusCode == HttpStatusCode.NotModified)
                return new SettingsResponse(false, message: "Settings have not been modified.");

            if (response == null || response.StatusCode != HttpStatusCode.OK)
                return new SettingsResponse(false, message: String.Concat("Unable to retrieve configuration settings: ", GetResponseMessage(response)));

            var json = GetResponseText(response);
            if (String.IsNullOrWhiteSpace(json))
                return new SettingsResponse(false, message: "Invalid configuration settings.");

            var settings = serializer.Deserialize<ClientConfiguration>(json);
            return new SettingsResponse(true, settings.Settings, settings.Version);
        }
 public Task <IEnumerable <Guid> > DeserializeAsync(string serializedAttributeOptionIds)
 {
     return(Task.FromResult(_jsonSerializer.Deserialize <IEnumerable <Guid> >(serializedAttributeOptionIds)));
 }
Example #31
0
        private async Task InnerExecute(byte[] signature, byte[] body)
        {
            _Logger.LogDebug("Signature received: {Signature}", signature);

            _BodyBytes = body;

            if ((signature?.Length ?? 0) != _WorkflowConfig.PostKeysSignatureLength) //TODO const
            {
                _Logger.LogError("Signature is null or incorrect length.");
                return;
            }

            try
            {
                var argsJson = Encoding.UTF8.GetString(_BodyBytes);
                _Logger.LogDebug("Body -\n{ArgsJson}.", argsJson);
                _ArgsObject = _JsonSerializer.Deserialize <PostTeksArgs>(argsJson);
            }
            catch (Exception e)
            {
                //TODO: check if you want to use Serilog's Exception logging, or just use ToString
                //i.e., _logger.LogError(e, "Error reading body");
                _Logger.LogError("Error reading body -\n{E}", e);
                return;
            }

            var base64Parser       = new Base64();
            var base64ParserResult = base64Parser.TryParseAndValidate(_ArgsObject.BucketId, _WorkflowConfig.BucketIdLength);

            if (!base64ParserResult.Valid)
            {
                _Logger.LogValidationMessages(base64ParserResult.Messages.Select(x => $"BuckedId - {x}").ToArray());
                return;
            }

            _BucketIdBytes = base64ParserResult.Item;

            if (_Logger.LogValidationMessages(_KeyValidator.Validate(_ArgsObject)))
            {
                return;
            }

            var teks = _ArgsObject.Keys.Select(Mapper.MapToTek).ToArray();

            foreach (var i in teks)
            {
                i.PublishAfter = _DateTimeProvider.Snapshot;
            }

            if (_Logger.LogValidationMessages(new TekListDuplicateValidator().Validate(teks)))
            {
                return;
            }

            var workflow = _DbContextProvider
                           .KeyReleaseWorkflowStates
                           .Include(x => x.Teks)
                           .SingleOrDefault(x => x.BucketId == _BucketIdBytes);

            if (workflow == null)
            {
                _Logger.LogError("Workflow does not exist - {BucketId}.", _ArgsObject.BucketId);
                return;
            }

            if (!_SignatureValidator.Valid(signature, workflow.ConfirmationKey, _BodyBytes))
            {
                _Logger.LogError("Signature not valid: {Signature}", signature);
                return;
            }

            var filterResults = _TekListWorkflowFilter.Validate(teks, workflow);

            _Logger.LogValidationMessages(filterResults.Messages);

            if (filterResults.Items.Length == 0)
            {
                _Logger.LogInformation("No teks survived the workflow filter.");
                return;
            }

            //Run after the filter removes the existing TEKs from the args.
            var allTeks = workflow.Teks.Select(Mapper.MapToTek).Concat(filterResults.Items).ToArray();

            if (_Logger.LogValidationMessages(new TekListDuplicateKeyDataValidator().Validate(allTeks)))
            {
                return;
            }

            _Logger.LogDebug("Writing.");
            var writeArgs = new TekWriteArgs
            {
                WorkflowStateEntityEntity = workflow,
                NewItems = filterResults.Items
            };

            await _Writer.Execute(writeArgs);

            _DbContextProvider.SaveAndCommit();
            _Logger.LogDebug("Committed.");

            if (filterResults.Items.Length != 0)
            {
                _Logger.LogInformation("Teks added - Count:{FilterResultsLength}.", filterResults.Items.Length);
            }
        }
Example #32
0
        public static T DeserializeFile <T>(this IFileStorage storage, string path, IJsonSerializer serializer)
        {
            string json = storage.GetFileContents(path);

            return(serializer.Deserialize <T>(json));
        }
Example #33
0
        public IDomainEvent Deserialize(string eventJson, string metadataJson)
        {
            var metadata = (IMetadata)_jsonSerializer.Deserialize <Metadata>(metadataJson);

            return(Deserialize(eventJson, metadata));
        }
        public virtual T GetJsonResponse <T>(string url) where T : class
        {
            var response = DownloadResponse(url);

            return(_jsonSerializer.Deserialize <T>(response));
        }
Example #35
0
 private static XProject ReadProject(ZipArchiveEntry projectEntry, IFileSystem fileIO, IJsonSerializer serializer)
 {
     using (var entryStream = projectEntry.Open())
     {
         return serializer.Deserialize<XProject>(fileIO.ReadUtf8Text(entryStream));
     }
 }