示例#1
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var templateVariablesConverter = new ValueConverter <List <TemplateVariable>, String>(
                model => _json.Serialize(model.ToDictionary(x => x.VarName)),
                value => _json.Deserialize <Dictionary <string, TemplateVariable> >(value).Values.ToList());

            var templateVariablesComparer = new ValueComparer <List <TemplateVariable> >(
                (l, r) => _json.Serialize(l) == _json.Serialize(r),
                v => v == null ? 0 : _json.Serialize(v).GetHashCode(),
                v => _json.Deserialize <List <TemplateVariable> >(_json.Serialize(v)));


            modelBuilder.Entity <BannerTemplateEntity>(builder =>
            {
                builder.Property(x => x.Variables)
                .HasConversion(templateVariablesConverter, templateVariablesComparer);
            });


            //modelBuilder.Entity<BannerTemplateEntity>(builder =>
            //{
            //	builder.Property(x => x.Variables)
            //			 .HasConversion<TemplateVariableConverter, JsonComparer<List<TemplateVariable>>>();
            //});
            modelBuilder.Entity <BannerEntity>(builder =>
            {
                builder.Property(x => x.VariableOptions)
                .HasConversion <VariableOptionListConverter, JsonComparer <List <VariableOption> > >();
            });
        }
示例#2
0
        private string GetInvokeScript(string id, object data)
        {
            if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException(nameof(id)); }

            string dataJson = JsonConverter.Serialize(data);
            string idJson = JsonConverter.Serialize(id); // this makes sure that the name is properly escaped
            return $"window._spidereye._sendEvent({idJson}, {dataJson})";
        }
示例#3
0
        public void Serialize(Boo[] array)
        {
            var stringWriter = new StringWriter();

            _converter.Serialize(array, stringWriter);

            var result = stringWriter.ToString();

            result.Should().Be(JsonConvert.SerializeObject(array));
        }
        public void CacheItem(IContent contentItem, string displayType, ItemLevelCacheItem itemLevelCacheItem)
        {
            if (contentItem == null)
            {
                return;
            }

            var itemLevelCachePart = contentItem.As <ItemLevelCachePart>();

            if (itemLevelCachePart == null || !itemLevelCachePart.ItemLevelCacheSettings.ContainsKey(displayType) || itemLevelCachePart.ItemLevelCacheSettings[displayType].Mode != ItemLevelCacheMode.CacheItem)
            {
                return;
            }

            var settings = itemLevelCachePart.ItemLevelCacheSettings[displayType];
            var cacheKey = GetCacheKey(contentItem, displayType);

            var cachedItem = mOutputCacheStorageProvider.GetCacheItem(cacheKey);

            if (cachedItem == null || cachedItem.IsInGracePeriod(mClock.UtcNow)) // TODO: Should this method check the cache first, or just blindly insert?
            {
                var serializedCacheItem = mJsonConverter.Serialize(itemLevelCacheItem);

                var cacheItem = new CacheItem()
                {
                    CachedOnUtc = mClock.UtcNow,
                    Duration    = settings.CacheDurationSeconds,
                    GraceTime   = settings.CacheGraceTimeSeconds,
                    Output      = mHttpContextAccessor.Current().Request.ContentEncoding.GetBytes(serializedCacheItem),
                    Tags        = new[]
                    {
                        ItemLevelCacheTag.GenericTag,
                        ItemLevelCacheTag.For(contentItem),
                        ItemLevelCacheTag.For(contentItem, displayType),
                        ItemLevelCacheTag.For(contentItem.ContentItem.TypeDefinition)
                    },
                    Tenant            = mShellSettings.Name,
                    CacheKey          = cacheKey,
                    InvariantCacheKey = cacheKey,
                    Url = ""
                };

                mOutputCacheStorageProvider.Set(cacheKey, cacheItem);

                // Also add the item tags to the tag cache.
                foreach (var tag in cacheItem.Tags)
                {
                    mTagCache.Tag(tag, cacheKey);
                }
            }
        }
示例#5
0
        public void Serialize(List <TElement> list, TextWriter writer)
        {
            if (list == null)
            {
                writer.Write(JsonTokenizer.TokenNullValue);
                return;
            }

            writer.Write('[');

            var first = true;

            foreach (var element in list)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    writer.Write(',');
                }

                _elementConverter.Serialize(element, writer);
            }

            writer.Write(']');
        }
示例#6
0
        private void SetAccounts(IEnumerable <CustomerOverview> accounts)
        {
            var accountsToBeSaved = jsonConverter.Serialize(accounts);

            preferences.Remove(nameSpace, key);
            preferences.Set(nameSpace, key, accountsToBeSaved);
        }
        protected override void Importing(ContentPart part, MediaGalleryField field, ImportContentContext context)
        {
            var mediaItems = new List <MediaGalleryItem>();
            var root       = context.Data.Element(field.FieldDefinition.Name + "." + field.Name);

            if (root == null)
            {
                return;
            }

            foreach (var element in root.Elements("MediaItem"))
            {
                mediaItems.Add(new MediaGalleryItem {
                    Url           = element.Attribute("Url").Value,
                    AlternateText = element.Attribute("AlternateText").Value,
                    Class         = element.Attribute("Class").Value,
                    Style         = element.Attribute("Style").Value,
                    Alignment     = element.Attribute("Alignment").Value,
                    Width         = int.Parse(element.Attribute("Width").Value, CultureInfo.InvariantCulture),
                    Height        = int.Parse(element.Attribute("Height").Value, CultureInfo.InvariantCulture),
                });
            }

            field.SelectedItems = mediaItems.Any() ? _jsonConverter.Serialize(mediaItems.ToArray()) : "[]";
        }
示例#8
0
        /// <summary>
        /// Dispatch job as sync.
        /// </summary>
        /// <typeparam name="TData">Type of data to send to worker.</typeparam>
        /// <param name="job">Job instance to dispatch.</param>
        /// <returns>If job dispatched successfully, returns true, otherwise returns false.</returns>
        /// <exception cref="Exception">Throws when job could not be dispatched.</exception>>
        public bool Dispatch <TData>(IJob <TData> job) where TData : class
        {
            this.ValidateJob(job);

            try
            {
                // Send.
                var result = _messageQueue.Send(job.Name, _jsonConverter.Serialize(job.Data));

                // Log, if could not be dispatched.
                if (!result)
                {
                    var message = $"Job {job.GetType().FullName} could not be dispatched.";

                    _logger.LogError(message);

                    return(false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    new EventId(),
                    ex,
                    $"Job {job.GetType().FullName} dispatching failed. {ex.Message}");

                throw ex;
            }

            return(true);
        }
示例#9
0
        public static PropertyBuilder <T> HasJsonConversion <T>(this PropertyBuilder <T> propertyBuilder,
                                                                IJsonConverter json)
        {
            var converter = new ValueConverter <T, String>(
                v => json.Serialize(v),
                v => json.Deserialize <T>(v));

            var comparer = new ValueComparer <T>(
                (l, r) => json.Serialize(l) == json.Serialize(r),
                v => v == null ? 0 : json.Serialize(v).GetHashCode(),
                v => json.Deserialize <T>(json.Serialize(v)));

            propertyBuilder.HasConversion(converter);
            propertyBuilder.Metadata.SetValueConverter(converter);
            propertyBuilder.Metadata.SetValueComparer(comparer);
            return(propertyBuilder);
        }
示例#10
0
        /// <summary>
        /// Implementation of commands
        /// </summary>
        private void FindFlights()
        {
            _dataOfFlights.DateOneWay = DateOneWay.ToString("yyyy-MM-dd");
            _dataOfFlights.DateReturn = DateReturn.ToString("yyyy-MM-dd");
            var param = _jsonConverter.Serialize(_dataOfFlights);

            ShowViewModel <FlightsListViewModel>(new { param });
        }
        private string Stringify <T>(T signal)
        {
            if (signal is string)
            {
                return(signal.ToString());
            }

            return(_jsonConverter.Serialize(signal)); // This is to achieve that the string should only depend on the object's content.
        }
示例#12
0
        public void Serialize(int value)
        {
            var stringWriter = new StringWriter();

            _converter.Serialize(value, stringWriter);

            var result = stringWriter.ToString();

            result.Should().Be(JsonConvert.SerializeObject(value));
        }
示例#13
0
 public void Serialize(TNullable?value, TextWriter writer)
 {
     if (value == null)
     {
         writer.Write(JsonTokenizer.TokenNullValue);
     }
     else
     {
         _valueConverter.Serialize(value.Value, writer);
     }
 }
示例#14
0
 public void Serialize(TNullable?value, TextWriter output)
 {
     if (value == null)
     {
         output.Write(JsonValue.NullToken);
     }
     else
     {
         _valueConverter.Serialize(value.Value, output);
     }
 }
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var errorResponse = new ErrorResponse();

            if (exception is HttpException httpException)
            {
                errorResponse.StatusCode = httpException.StatusCode;
                errorResponse.Message    = httpException.Message;
            }

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)errorResponse.StatusCode;
            await context.Response.WriteAsync(_jsonConverter.Serialize(errorResponse));
        }
示例#16
0
        protected override DriverResult Editor(ItemLevelCachePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (!mAuthorizer.Authorize(ItemLevelCachePermissions.EditItemLevelCacheSettings))
            {
                return(null);
            }

            updater.TryUpdateModel(part, Prefix, null, null);

            part.SerializedItemLevelCacheSettings = mJsonConverter.Serialize(part.ItemLevelCacheSettings);

            if (mTagCache.GetTaggedItems(PageLevelCacheTag.For(part).ToString()).Any())
            {
                var contentType = part.ContentItem.TypeDefinition.DisplayName;
                var returnUrl   = mUrlHelper.Action("Index", new
                {
                    area       = "Orchard.Widgets",
                    controller = "Admin"
                });

                var url = mUrlHelper.Action("EvictByTag", new
                {
                    area       = "IDeliverable.Donuts",
                    controller = "CacheItems",
                    tag        = PageLevelCacheTag.For(part),
                    returnUrl
                });

                mNotifier.Warning(
                    T("There are some page level cache items that contain the {0} you have just edited. " +
                      "Any new item level cache settings you have applied to this item will not apply on those pages until their page level cache items expire. " +
                      "You can <a href=\"{1}\">evict these items now</a> in order for the changes to take effect immediately.", contentType, url));
            }

            return(Editor(part, shapeHelper));
        }
示例#17
0
        public async Task Add(EventualConsistentEvent eventualConsistent)
        {
            // TODO: don't call GetType() and get name from some cached context?
            var @event           = eventualConsistent.Event;
            var eventHandlerName = eventualConsistent.EventHandlerName;
            var eventName        = @event.GetType().FullName;
            var customConverter  = CreateConverter(eventName);
            var payload          = customConverter == null
                ? _jsonConverter.Serialize(@event)
                : customConverter.Convert(@event);

            await UnitOfWork.ExecuteAsync(
                "INSERT INTO events VALUES (DEFAULT, @eventName, @eventHandlerName, 0, 0, @payload)",
                new { eventName, eventHandlerName, payload });
        }
        public WatchablePartHandler(
            IRepository<WatchablePartRecord> repository,
            IJsonConverter jsonConverter)
        {
            Filters.Add(StorageFilter.For(repository));

            OnActivated<WatchablePart>((ctx, part) =>
                {
                    part.WatcherIdsField.Loader(() =>
                        {
                            var seed = string.IsNullOrEmpty(part.WatcherIdsSerialized) ? Enumerable.Empty<int>() : jsonConverter.Deserialize<IEnumerable<int>>(part.WatcherIdsSerialized);
                            var collection = new ObservableCollection<int>(seed);
                            collection.CollectionChanged += (sender, e) =>
                                {
                                    part.WatcherIdsSerialized = jsonConverter.Serialize((IEnumerable<int>)collection);
                                };
                            return collection;
                        });
                });
        }
示例#19
0
        public WatchablePartHandler(
            IRepository <WatchablePartRecord> repository,
            IJsonConverter jsonConverter)
        {
            Filters.Add(StorageFilter.For(repository));

            OnActivated <WatchablePart>((ctx, part) =>
            {
                part.WatcherIdsField.Loader(() =>
                {
                    var seed       = string.IsNullOrEmpty(part.WatcherIdsSerialized) ? Enumerable.Empty <int>() : jsonConverter.Deserialize <IEnumerable <int> >(part.WatcherIdsSerialized);
                    var collection = new ObservableCollection <int>(seed);
                    collection.CollectionChanged += (sender, e) =>
                    {
                        part.WatcherIdsSerialized = jsonConverter.Serialize((IEnumerable <int>)collection);
                    };
                    return(collection);
                });
            });
        }
示例#20
0
        public void Serialize(TElement[] array, TextWriter writer)
        {
            if (array == null)
            {
                writer.Write(JsonTokenizer.TokenNullValue);
                return;
            }

            writer.Write('[');

            for (var i = 0; i < array.Length; i++)
            {
                if (i > 0)
                {
                    writer.Write(',');
                }
                _elementConverter.Serialize(array[i], writer);
            }

            writer.Write(']');
        }
        public NotificationsUserPartHandler(IJsonConverter jsonConverter, Lazy<INotificationsToUserDispatcher> notificationDispatcherLazy)
        {
            Filters.Add(new ActivatingFilter<NotificationsUserPart>("User"));

            OnActivated<NotificationsUserPart>((context, part) =>
            {
                part.RecentNotificationEntriesField.Loader(() =>
                    {
                        var serializedEntries = part.Retrieve<string>("RecentNotificationEntriesSerialized");
                        if (string.IsNullOrEmpty(serializedEntries)) return Enumerable.Empty<NotificationUserEntry>();
                        return jsonConverter.Deserialize<IEnumerable<NotificationUserEntry>>(serializedEntries);
                    });

                part.RecentNotificationEntriesField.Setter(entries =>
                    {
                        Argument.ThrowIfNull(entries, "entries");
                        part.Store<string>("RecentNotificationEntriesSerialized", jsonConverter.Serialize(entries));
                        return entries;
                    });
            });
        }
示例#22
0
        private dynamic BeginRenderItem(IContent content, string displayType, string groupId)
        {
            WorkContext workContext = _workContextAccessor.GetContext();
            var         output      = _shapeDisplay.Display(BuildShape(content, displayType, groupId));

            _cacheSettings     = GetOutputCacheSettings(content);
            _cacheKey          = ComputeCacheKey(content, displayType, groupId);
            _invariantCacheKey = string.Format("tenant={0};id={1};", _shellSettings.Name, content.ContentItem.Id);

            var cacheItem = new CacheItem()
            {
                CachedOnUtc = _now,
                ValidFor    = _cacheSettings.CacheDuration,
                Output      = _jsonConverter.Serialize(new OutputCacheItem
                {
                    Id        = content.ContentItem.Id,
                    Output    = output,
                    Resources = _resourceManager.GetRequiredResources("script")
                                .Concat(_resourceManager.GetRequiredResources("stylesheet")).Select(GetCacheItemResource).ToList()
                }),
                ContentType       = content.ContentItem.ContentType,
                QueryString       = workContext.HttpContext.Request.Url.Query,
                CacheKey          = _cacheKey,
                InvariantCacheKey = _invariantCacheKey,
                Url        = workContext.HttpContext.Request.Url.AbsolutePath,
                Tenant     = _shellSettings.Name,
                StatusCode = workContext.HttpContext.Response.StatusCode,
                Tags       = new[] { _invariantCacheKey, content.ContentItem.Id.ToString(CultureInfo.InvariantCulture) }
            };

            _cacheStorageProvider.Remove(_cacheKey);
            _cacheStorageProvider.Set(_cacheKey, cacheItem);

            foreach (var tag in cacheItem.Tags)
            {
                _tagCache.Tag(tag, _cacheKey);
            }

            return(ServeCachedItem(cacheItem, content, displayType, groupId));
        }
示例#23
0
        public T Set <T>(string cacheItemKey, CacherItemPolicy cacheItemPolicy, T cacheItem)
        {
            var regionKey = GetRegionKeyCore(
                cacheItemKey: cacheItemKey,
                regionName: _regionName
                );
            var putCacheItem = _jsonConverter.Serialize(
                value: cacheItem
                );
            var putCacheItemPolicy = GetCacheItemPolicy(cacheItemPolicy);

            lock (this)
            {
                SetCore(
                    regionKey: regionKey,
                    cacheItem: putCacheItem,
                    cacheItemPolicy: putCacheItemPolicy
                    );
            }

            return(cacheItem);
        }
示例#24
0
        public NotificationsUserPartHandler(IJsonConverter jsonConverter, Lazy <INotificationsToUserDispatcher> notificationDispatcherLazy)
        {
            Filters.Add(new ActivatingFilter <NotificationsUserPart>("User"));

            OnActivated <NotificationsUserPart>((context, part) =>
            {
                part.RecentNotificationEntriesField.Loader(() =>
                {
                    var serializedEntries = part.Retrieve <string>("RecentNotificationEntriesSerialized");
                    if (string.IsNullOrEmpty(serializedEntries))
                    {
                        return(Enumerable.Empty <NotificationUserEntry>());
                    }
                    return(jsonConverter.Deserialize <IEnumerable <NotificationUserEntry> >(serializedEntries));
                });

                part.RecentNotificationEntriesField.Setter(entries =>
                {
                    Argument.ThrowIfNull(entries, "entries");
                    part.Store <string>("RecentNotificationEntriesSerialized", jsonConverter.Serialize(entries));
                    return(entries);
                });
            });
        }
示例#25
0
        /// <summary>
        /// Dispatch job as sync.
        /// </summary>
        /// <typeparam name="TData">Type of data to send to worker.</typeparam>
        /// <param name="job">Job instance to dispatch.</param>
        /// <returns>If job dispatched successfully, returns true, otherwise returns false.</returns>
        /// <exception cref="Exception">Throws when job could not be dispatched.</exception>>
        public bool Dispatch <TData>(IJob <TData> job) where TData : class
        {
            this.ValidateJob(job);

            try
            {
                var result = _messageQueue.Send(
                    job.Name,
                    _jsonConverter.Serialize(job.Data),
                    new Tossit.Core.Options {
                    ConfirmIsActive = _jobOptions.Value.WorkerConfirmsIsActive,
                    ConfirmTimeout  = _jobOptions.Value.WorkerConfirmsTimeoutSeconds
                });

                // Log, if could not be dispatched.
                if (!result)
                {
                    var message = $"Job {job.GetType().FullName} could not be dispatched.";

                    _logger.LogError(message);

                    return(false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    new EventId(),
                    ex,
                    $"Job {job.GetType().FullName} dispatching failed. {ex.Message}");

                throw ex;
            }

            return(true);
        }
示例#26
0
 /// <summary>
 /// Save data to file
 /// </summary>
 /// <param name="fileName">File's name</param>
 /// <param name="obj">Data to store</param>
 public void Save(string fileName, object obj)
 {
     _fileStore.WriteFile(fileName, _jsonConverter.Serialize(obj));
 }
 /// <summary>
 ///     Adds tag and json-serialized replacement-data pair to parameters
 /// </summary>
 /// <param name="parTag">The tag id</param>
 /// <param name="parData">The replacement-data object for the tag</param>
 public void Add(string parTag, object parData)
 {
     _dict.Add(new KeyValuePair <string, string>(parTag, Converter.Serialize(parData)));
 }
        public override bool RunTask(WFTaskEntity taskEntity, WFFinsEntity fins, WFTinsEntity tinsEntity, WFTEventEntity enventEntity)
        {
            // 根据tasksetting 节点的配置信息读取要发送到的远端地址
            //可以是多个地址
            if (!string.IsNullOrWhiteSpace(taskEntity.Setting))
            {
                var list = _jsonConverter.Deserialize <List <SendHttpModel> >(taskEntity.Setting);
                if (list != null)
                {
                    Dictionary <string, string> dicPostdata = null;
                    foreach (var item in list)
                    {
                        //Console.WriteLine($"发送数据到远端{item.Url}");

                        dicPostdata = new Dictionary <string, string>();
                        dicPostdata.Add("callbackTag", enventEntity.ID);
                        dicPostdata.Add("customTag", item.CustomTag);
                        dicPostdata.Add("dataId", enventEntity.Dataid);
                        var content    = new FormUrlEncodedContent(dicPostdata);
                        var httpClient = _httpClientFactory.CreateClient();
                        try
                        {
                            var response = httpClient.PostAsync(item.Url, content).GetAwaiter().GetResult();
                            if (response.IsSuccessStatusCode)
                            {
                                response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                            }
                            else
                            {
                                var a = "";
                            }
                        }
                        catch (HttpRequestException ex)
                        {
                            throw new HttpRequestException($"{ex.Message},RunTask url:{item.Url} content:{_jsonConverter.Serialize(dicPostdata) }");
                        }
                    }
                    return(false);
                }
            }
            return(true);
        }
示例#29
0
        void SaveInternal()
        {
            StringBuilder sb = new StringBuilder();

            HashSet <Tuple <Type, string, string> > matches = MatchEntityToFinalTableAndTemporaryTable(_entities);


            foreach (var item in _entities)
            {
                //make sure we have tables for all types
                GetOrCreateTable(item.Value.GetType());
            }

            sb.Append("BEGIN;");
            foreach (var match in matches)
            {
                sb.Append(string.Format("CREATE TEMPORARY TABLE \"{0}\" (id uuid, body jsonb);", match.Item3));
            }

            foreach (var item in _entities)
            {
                sb.Append(string.Format("INSERT INTO \"{0}\" (id, body) VALUES ('{1}', '{2}');", matches.Where(c => c.Item1 == item.Value.GetType()).Select(j => j.Item3).First(), item.Key, _jsonConverter.Serialize(item.Value).EscapeQuotes()));
            }

            foreach (var match in matches)
            {
                sb.Append(string.Format("LOCK TABLE {0} IN EXCLUSIVE MODE;", match.Item2));
                sb.Append(string.Format("UPDATE {0} SET body = tmp.body from \"{1}\" tmp where tmp.id = {0}.id;", match.Item2, match.Item3));
                sb.Append(string.Format("INSERT INTO {0} SELECT tmp.id, tmp.body from \"{1}\" tmp LEFT OUTER JOIN {0} ON ({0}.id = tmp.id) where {0}.id IS NULL;", match.Item2, match.Item3));
            }


            sb.Append("COMMIT;");

            using (var command = _conn.CreateCommand())
            {
                command.CommandTimeout = 60;
                command.CommandType    = CommandType.Text;
                command.CommandText    = sb.ToString();
                command.ExecuteNonQuery();
            }

            _entities.Clear();
        }
        protected override DriverResult Editor(FeedSyncProfilePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var oldContentTypeValue = part.ContentType;
            var oldFeedUrl          = part.FeedUrl;

            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                // These properties cannot be changed, because the mappings will be generated according
                // to this type and URL.
                if (part.PublishedCount >= 1)
                {
                    part.ContentType = oldContentTypeValue;
                    part.FeedUrl     = oldFeedUrl;
                }

                if (!GetTypesWithFeedSyncProfileItemPart().Contains(part.ContentType))
                {
                    updater.AddModelError("InvalidContentType", T("Please select a content type with FeedSyncProfileItemPart."));
                }

                if (part.PublishedCount == 0)
                {
                    var feedType = _feedManager.GetValidFeedType(part);
                    if (string.IsNullOrEmpty(feedType))
                    {
                        updater.AddModelError("InvalidFeedUrl", T("The given feed URL is invalid or unsupported."));
                    }
                    else
                    {
                        part.FeedType = feedType;
                    }
                }

                // Clearing the empty mappings so only the filled ones will be saved.
                part
                .Mappings
                .RemoveAll(mapping =>
                           string.IsNullOrEmpty(mapping.FeedMapping) ||
                           string.IsNullOrEmpty(mapping.ContentItemStorageMapping));

                var invalidFeedMapping = false;
                foreach (var mapping in part.Mappings)
                {
                    mapping.FeedMapping = mapping.FeedMapping.Trim();
                    if (mapping.FeedMapping.Any(char.IsWhiteSpace))
                    {
                        invalidFeedMapping = true;
                        updater.
                        AddModelError(
                            "InvalidFeedMapping",
                            T("The given feed mapping: \"{0}\" is invalid because it contains a whitespace character.", mapping.FeedMapping));
                    }
                }

                if (!invalidFeedMapping)
                {
                    part.MappingsSerialized = _jsonConverter.Serialize(part.Mappings);
                }

                if (part.PublishedCount == 0)
                {
                    _notifier.Information(T("Please don't forget to save again after filling out the required fields!"));
                }
            }

            return(Editor(part, shapeHelper));
        }
示例#31
0
 public byte[] Serialize(object obj)
 {
     return(Encode(jsonConverter.Serialize(obj)));
 }
示例#32
0
        public LuceneSettingsPartHandler(IJsonConverter jsonConverter)
        {
            T = NullLocalizer.Instance;

            Filters.Add(new ActivatingFilter <LuceneSettingsPart>("Site"));

            OnActivated <LuceneSettingsPart>((context, part) => {
                part.LuceneAnalyzerSelectorMappingsField.Loader(() => {
                    return(string.IsNullOrEmpty(part.LuceneAnalyzerSelectorMappingsSerialized)
                        ? new List <LuceneAnalyzerSelectorMapping>()
                        : jsonConverter.Deserialize <List <LuceneAnalyzerSelectorMapping> >(part.LuceneAnalyzerSelectorMappingsSerialized));
                });

                part.LuceneAnalyzerSelectorMappingsField.Setter((value) => {
                    part.LuceneAnalyzerSelectorMappingsSerialized = value == null ? "[]" : jsonConverter.Serialize(value);
                    return(value);
                });
            });
        }