public async Task <IEnumerable <MessageRecord> > GetAsync(MessageQuery messageQuery, CancellationToken cancellationToken) { if (disposed) { throw new ObjectDisposedException(nameof(AdoNetMessageRepository)); } // Execute. var messages = new List <MessageRecord>(); var connection = GetConnection(); using (var command = connection.CreateCommand()) { command.CommandText = queryProvider.GetFilterScript(messageQuery); command.CommandTimeout = 120; // Set timeout to 2 mins since query may take long time. using (var reader = await command.ExecuteReaderAsync(cancellationToken)) { while (await reader.ReadAsync(cancellationToken)) { var messageRecord = new MessageRecord { Type = reader.GetByte(1), Id = reader.GetGuid(2), ContentType = reader.GetString(3) }; var content = serializer.IsText ? Encoding.UTF8.GetBytes(reader.GetString(4)) : (byte[])reader[4]; var contentType = Type.GetType(messageRecord.ContentType); messageRecord.Content = serializer.Deserialize(content, contentType); if (!reader.IsDBNull(5)) { messageRecord.Data = serializer.Deserialize( Encoding.UTF8.GetBytes(reader.GetString(5)), typeof(IDictionary <string, string>)) as IDictionary <string, string>; } if (!reader.IsDBNull(7) && !reader.IsDBNull(8)) { messageRecord.ErrorMessage = reader.GetString(7); messageRecord.ErrorType = reader.GetString(8); var errorType = Type.GetType(messageRecord.ErrorType); if (!reader.IsDBNull(6) && !string.IsNullOrEmpty(messageRecord.ErrorType)) { var error = serializer.IsText ? Encoding.UTF8.GetBytes(reader.GetString(6)) : (byte[])reader[6]; if (error.Length > 0) { messageRecord.Error = serializer.Deserialize(error, errorType) as Exception; } } } messageRecord.CreatedAt = reader.GetDateTime(9); messageRecord.ExecutionDuration = reader.GetInt32(10); messageRecord.Status = (ProcessingStatus)reader.GetByte(11); messages.Add(messageRecord); } } } return(messages); }
/// <summary> /// Implements <see cref="INotificationFormatter"/> /// Delayed notification. In our demo handled by <see cref="IftttNotificationProvider"/>. /// </summary> /// <param name="notifications">Notifications to send out.</param> /// <param name="recipient">Recipient of the notification. Transformed and filtered by <see cref="IftttNotificationProvider"/>.</param> /// <param name="format">Parameters for supported format by <see cref="IftttNotificationProvider"/></param> /// <param name="channelName">Channel name, but we only support one so it's ignored here.</param> /// <returns>The formatted messages.</returns> public IEnumerable <FormatterNotificationMessage> FormatMessages( IEnumerable <FormatterNotificationMessage> notifications, string recipient, NotificationFormat format, string channelName) { // Join messages with the same content. var groupedMessages = notifications.GroupBy(x => x.Content); foreach (var group in groupedMessages) { // Get the serialized content data var data = _objectSerializer.Deserialize <TweetedPageViewModel>(group.Last().Content); // Respect the provider's Format. var content = $@"Your article ""{data.PageName}"" has {data.ShareCount} shares!"; if (format.MaxLength.HasValue) { content = content.Substring(0, Math.Min(content.Length, format.MaxLength.Value)); } // Mark all ID's as processed (otherwise the dispatcher will try again with them) var messageIds = group.SelectMany(y => y.ContainedIDs); var formattedMessage = new FormatterNotificationMessage(messageIds) { Content = content }; yield return(formattedMessage); } }
/// <summary> /// Retrieves a single item by its key. /// </summary> /// <typeparam name="T">Type of object retrieved</typeparam> /// <param name="key">Key of the object</param> /// <param name="default">Default value of the object</param> /// <returns>The T object</returns> public T Read <T>(string key, T @default = default) { if (!Settings.Values.TryGetValue(key, out var value) || value == null) { return(@default); } return(serializer.Deserialize <T>(value)); }
/// <inheritdoc /> public T Read<T>(string key, T @default = default) { if (!Settings.TryGetValue(key, out object value) || value == null) { return @default; } return _serializer.Deserialize<T>((string)value); }
/// <summary> /// Reads a typed array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="Provider">Database provider object.</param> /// <param name="Reader">Binary reader.</param> /// <param name="FieldDataType">Field data type.</param> /// <returns>String value.</returns> /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception> public static T[] ReadArray <T>(FilesProvider Provider, BinaryDeserializer Reader, uint FieldDataType) { switch (FieldDataType) { case ObjectSerializer.TYPE_ARRAY: List <T> Elements = new List <T>(); IObjectSerializer S = Provider.GetObjectSerializer(typeof(T)); ulong NrElements = Reader.ReadVariableLengthUInt64(); uint ElementDataType = Reader.ReadBits(6); uint?ElementDataTypeN = ElementDataType == ObjectSerializer.TYPE_NULL ? (uint?)null : (uint?)ElementDataType; while (NrElements-- > 0) { Elements.Add((T)S.Deserialize(Reader, ElementDataTypeN, true)); } return(Elements.ToArray()); case ObjectSerializer.TYPE_NULL: return(null); default: throw new Exception("Array expected."); } }
/// <summary> /// Reads a typed array. /// </summary> /// <param name="T">Element type.</param> /// <param name="Provider">Database provider object.</param> /// <param name="Reader">Binary reader.</param> /// <param name="FieldDataType">Field data type.</param> /// <returns>String value.</returns> /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception> public static Array ReadArray(Type T, FilesProvider Provider, BinaryDeserializer Reader, uint FieldDataType) { switch (FieldDataType) { case ObjectSerializer.TYPE_ARRAY: IObjectSerializer S = Provider.GetObjectSerializer(T); ulong NrElements = Reader.ReadVariableLengthUInt64(); if (NrElements > int.MaxValue) { throw new Exception("Array too long."); } int i, c = (int)NrElements;; Array Result = Array.CreateInstance(T, c); uint ElementDataType = Reader.ReadBits(6); uint?ElementDataTypeN = ElementDataType == ObjectSerializer.TYPE_NULL ? (uint?)null : (uint?)ElementDataType; for (i = 0; i < c; i++) { Result.SetValue(S.Deserialize(Reader, ElementDataTypeN, true), i); } return(Result); case ObjectSerializer.TYPE_NULL: return(null); default: throw new Exception("Array expected."); } }
public T Load <T>(IObjectSerializer <T> serializer, string path) { string str = File.ReadAllText(path); T item = serializer.Deserialize(str); return(item); }
/// <summary> /// Reads a typed array. /// </summary> /// <param name="T">Element type.</param> /// <param name="Provider">Database provider object.</param> /// <param name="Reader">Binary reader.</param> /// <param name="FieldDataType">Field data type.</param> /// <returns>String value.</returns> /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception> public static Array ReadArray(Type T, MongoDBProvider Provider, IBsonReader Reader, BsonType FieldDataType) { switch (FieldDataType) { case BsonType.Array: List <object> Elements = new List <object>(); IObjectSerializer S = Provider.GetObjectSerializer(T ?? typeof(GenericObject)); Reader.ReadStartArray(); while (Reader.State != BsonReaderState.EndOfArray) { BsonType?ElementType = null; if (Reader.State == BsonReaderState.Type) { ElementType = Reader.ReadBsonType(); if (ElementType == BsonType.EndOfDocument) { break; } } Elements.Add(S.Deserialize(Reader, ElementType, true)); } Reader.ReadEndArray(); if (T is null) { return(Elements.ToArray()); } int c = Elements.Count; Array Result = Array.CreateInstance(T, c); Array.Copy(Elements.ToArray(), 0, Result, 0, c); return(Result); case BsonType.Binary: byte[] Bin = Reader.ReadBytes(); if (T is null || T == typeof(byte)) { return(Bin); } c = Bin.Length; Result = Array.CreateInstance(T, c); Array.Copy(Bin, 0, Result, 0, c); return(Result); case BsonType.Null: Reader.ReadNull(); return(null); default: throw new Exception("Array expected."); } }
protected override void OnHandleVerifiedPacket(INetworkPeer sender, RpcPacket incomingPacket) { var componentInstance = m_NetworkComponentManager.GetComponent(incomingPacket.ComponentId); var method = componentInstance.GetRcpMethod(incomingPacket.MethodIndex); List <object> invokeArgs = new List <object> { sender }; int index = 0; var data = incomingPacket.Arguments; foreach (var parameter in method.GetParameters()) { int size = BitConverter.ToInt32(data, index); index += sizeof(int); var segment = new ArraySegment <byte>(data, index, size); var arg = m_ObjectSerializer.Deserialize(segment, parameter.ParameterType); invokeArgs.Add(arg); index += size; } method.Invoke(componentInstance, invokeArgs.ToArray()); }
/// <summary> /// Gets the telemetry configuration from azure function endpoint. /// </summary> /// <returns> /// A dictionary containing the configuration; otherwise null if the request to /// the azure function failed. /// </returns> private async Task <IDictionary <string, object> > GetTelemetryConfiguration(TelemetryConfigModel telemetryConfigModel) { var endpointUrl = new Uri("https://cmsui.episerver.net/api/telemetryconfig"); var uriBuilder = new UriBuilder(endpointUrl); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query.Add("client", telemetryConfigModel.Client); query.Add("user", telemetryConfigModel.User); query.Add("version", telemetryConfigModel.Versions["CMS"]); uriBuilder.Query = query.ToString(); var url = uriBuilder.Uri.ToString(); try { using (var response = await GetRequestAsync(url).ConfigureAwait(false)) using (var content = response.Content) { if (!response.IsSuccessStatusCode) { return(null); } var raw = await content.ReadAsStringAsync().ConfigureAwait(false); return(_objectSerializer.Deserialize <IDictionary <string, object> >(raw)); } } catch (HttpRequestException) { // Occurs when the request fails due to server issues or timeout. return(null); } }
private bool IsProjectAvailable(ExtendedProjectViewModel projectViewModel, string currentUser, ICollection <string> currentUserRoles) { try { var visibleTo = _objectSerializer.Deserialize <IList <UserRole> >(projectViewModel.VisibleTo); if (visibleTo.Count == 0 || projectViewModel.CreatedBy.Equals(currentUser)) { return(true); } foreach (var userRole in visibleTo) { if (userRole.ReviewerType == ApprovalDefinitionReviewerType.User && userRole.Name == currentUser) { return(true); } if (currentUserRoles.Contains(userRole.Name)) { return(true); } } return(false); } catch { return(true); } }
// BlobInfo private BlobInfo ReadBlobInfo(string blobId) { BlobInfo blobInfo = null; var infoFilePath = GetBlobInfoFilePath(blobId); // Если файл с мета-информацией существует if (IsFileExists(infoFilePath)) { using (var infoFile = OpenReadFileStream(infoFilePath)) { blobInfo = _objectSerializer.Deserialize(infoFile, typeof(BlobInfo)) as BlobInfo; } } // Если файл с мета-информацией не существует else { var dataFilePath = GetBlobDataFilePath(blobId); var dataFileInfo = new FileInfo(dataFilePath); if (dataFileInfo.Exists) { blobInfo = new BlobInfo { Id = blobId, Name = blobId, Type = _mimeTypeResolver.GetMimeType(blobId), Size = dataFileInfo.Length, Time = dataFileInfo.LastWriteTimeUtc }; } } return(blobInfo); }
public void Write(Stream stream, IEnumerable <byte[]> instances) { var results = instances.Select(i => _outSerializer.Deserialize(i)); results = SortOutput(results); _outWriter.Serialize(stream, results); }
public Task <UserNotificationMessage> FormatUserMessageAsync(UserNotificationMessage message) { var result = CreateBasicFormattedUserNotificationMessage(message); ReviewContentNotificationModel reviewContent; try { reviewContent = _objectSerializer.Deserialize <ReviewContentNotificationModel>(message.Content); } catch (Exception) { reviewContent = new ReviewContentNotificationModel(); } if (reviewContent == null) { return(Task.FromResult(result)); } result.Subject = reviewContent.Title; if (!ContentReference.IsNullOrEmpty(reviewContent.ContentLink)) { result.Link = new Uri("epi.cms.contentdata:///" + reviewContent.ContentLink); } var userNameContainer = "<span class='epi-username external-review'>{0}</span>"; var userName = reviewContent.SenderDisplayName ?? "external editor"; userName = string.Format(userNameContainer, userName); result.Content = $"{userName} added new comment: \"'{reviewContent.Text?.Ellipsis(50)}'\""; return(Task.FromResult(result)); }
/// <summary> /// Retrieves a single item by its key. /// </summary> /// <typeparam name="T">Type of object retrieved</typeparam> /// <param name="key">Key of the object</param> /// <param name="default">Default value of the object</param> /// <returns>The T object</returns> public T Read <T>(string key, T @default = default(T)) { if (!Settings.Values.TryGetValue(key, out var value) || value == null) { return(@default); } var type = typeof(T); var typeInfo = type.GetTypeInfo(); if (typeInfo.IsPrimitive || type == typeof(string)) { return((T)Convert.ChangeType(value, type)); } return(serializer.Deserialize <T>((string)value)); }
/// <summary> /// Get a file from the remote. /// </summary> /// <param name="graph">Instance of the <see cref="GraphServiceClient"/>.</param> /// <param name="userId">The id of the target Graph user.</param> /// <param name="itemPath">The path of the target item.</param> /// <param name="serializer">A serializer for converting stored values.</param> /// <typeparam name="T">The type of object to return.</typeparam> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task <T> GetFileAsync <T>(this GraphServiceClient graph, string userId, string itemPath, IObjectSerializer serializer) { Stream stream = await graph.Users[userId].Drive.Special.AppRoot.ItemWithPath(itemPath).Content.Request().GetAsync(); string streamContents = new StreamReader(stream).ReadToEnd(); return(serializer.Deserialize <T>(streamContents)); }
public static object DeserializeFromValueSet(this IObjectSerializer serializer, ValueSet valueSet) { if (valueSet.TryGetValue("SerializedData", out var dataObject) && dataObject is string data) { return(serializer.Deserialize(data)); } return(null); }
private void HandleRequest(HttpListenerContext listenerContext) { HttpListenerRequest request = listenerContext.Request; using (var response = listenerContext.Response) { listenerContext.Response.AddHeader("Server", Server); if (request.HttpMethod == HttpVerbPost) { var message = new MessageRecord { Type = GetMessageTypeFromUri(request.Url), ContentType = GetMessageContentTypeFromUri(request.Url), CreatedAt = DateTime.Now }; response.ContentType = ContentTypeJson; using (var streamReader = new StreamReader(request.InputStream)) { byte[] bytes = null; try { var body = streamReader.ReadToEnd(); bytes = Encoding.Default.GetBytes(body); var t = Type.GetType(message.ContentType); message.Content = serializer.Deserialize(bytes, t); } catch (Exception ex) { response.StatusCode = HttpStatusBadRequest; response.ContentType = ContentTypePlainText; FormatStreamFromString(ex.ToString(), response); } try { ProcessMessage(message); } catch (Exception ex) { response.StatusCode = HttpStatusBadRequest; response.ContentType = ContentTypePlainText; FormatStreamFromString(ex.ToString(), response); } FormatStreamFromString(JsonConvert.SerializeObject(message), response); } } else { response.StatusCode = HttpStatusMethodNotAllowed; response.ContentType = ContentTypePlainText; FormatStreamFromString("Method Not Allowed", response); } } }
/// <summary> /// Returns null if document is not found /// </summary> /// <param name="id"></param> /// <returns></returns> public T GetDocument <T>(string id, bool attachments, IObjectSerializer objectSerializer) { var resp = GetRequest(String.Format("{0}/{1}{2}", databaseBaseUri, id, attachments ? "?attachments=true" : string.Empty)).Get().Json().GetCouchResponse(); if (resp.StatusCode == HttpStatusCode.NotFound) { return(default(T)); } return(objectSerializer.Deserialize <T>(resp.ResponseString)); }
/// <summary> /// Initializes a new instance of <c>XmlStorageMappingResolver</c> class. /// </summary> /// <param name="fileName">The file name of the external XML mapping file.</param> public XmlStorageMappingResolver(string fileName) { using (var fileStream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName), FileMode.Open, FileAccess.Read)) { var bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length)); _mappingSchema = _serializer.Deserialize <StorageMappingSchema>(bytes); fileStream.Close(); } }
public T GetDocument <T>(string id, IObjectSerializer objectSerializer) { var resp = GetRequest(databaseBaseUri + "/" + id).Get().Json().GetResponse(); if (resp.StatusCode == HttpStatusCode.NotFound) { return(default(T)); } return(objectSerializer.Deserialize <T>(resp.GetResponseString())); }
public CommentDto GetLastComment(string data) { var dto = _objectSerializer.Deserialize <ReviewLocationDto>(data); if (dto.Comments == null || dto.Comments.Any() == false) { return(dto.FirstComment); } return(dto.Comments.FirstOrDefault()); }
/// <summary> /// Initializes a new instance of <c>XmlStorageMappingResolver</c> class. /// </summary> /// <param name="fileName">The file name of the external XML mapping file.</param> public XmlObjectMappingResolver(string fileName) { this.fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); using (FileStream fileStream = new FileStream(this.fileName, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length)); this.entityMappingConfiguration = serializer.Deserialize <EntityMappingConfiguration>(bytes); fileStream.Close(); } }
public T Load(string path) { if (!File.Exists(path)) { return(new T()); } string objStr = File.ReadAllText(path); T t = _serializer.Deserialize(objStr); return(t); }
public async Task <AggregateEvent[]> GetEventsAsync(Guid aggregateId) { List <string> serializedEvents = await _context.GetDbSet() .Where(x => x.AggregateId == aggregateId) .OrderBy(x => x.AggregateVersion) .Select(x => x.Serialized) .ToListAsync(); return(serializedEvents .Select(x => _eventSerializer.Deserialize <AggregateEvent>(x)) .ToArray()); }
private T[] ReadArray <T>(BinaryDeserializer Reader, ulong NrElements, uint ElementDataType) { List <T> Elements = new List <T>(); IObjectSerializer S = this.provider.GetObjectSerializer(typeof(T)); while (NrElements-- > 0) { Elements.Add((T)S.Deserialize(Reader, ElementDataType, true)); } return(Elements.ToArray()); }
public FilesHashesHandler(IDuplicateChecker duplicateChecker, IObjectSerializer serializer, UnregisteredHashesAdder unregisteredHashesAdder, IOptions <BackuperConfiguration> configuration) { mDuplicateChecker = duplicateChecker ?? throw new ArgumentNullException(nameof(duplicateChecker)); mSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); mUnregisteredHashesAdder = unregisteredHashesAdder ?? throw new ArgumentNullException(nameof(unregisteredHashesAdder)); mConfiguration = configuration ?? throw new ArgumentNullException(nameof(configuration)); HashToFilePathDict = mSerializer.Deserialize <Dictionary <string, List <string> > >(Path.Combine(mConfiguration.Value.DriveRootDirectory, HashFileName)); }
public IEnumerable <WorkflowActivityDto> Get(Expression <Func <Entities.WorkflowActivity, bool> > expression) { var workflowActivities = _dbContext.WorkflowActivity.AsNoTracking().Where(expression); var workflowActivityList = new List <WorkflowActivityDto>(); workflowActivities.ToList() .ForEach(workflowActivity => { var context = _objectSerializer.Deserialize <WorkflowActivityContentDto>(workflowActivity.Context); workflowActivityList.Add(new WorkflowActivityDto { Id = workflowActivity.Id, UniqueId = workflowActivity.UniqueId, Context = context }); }); return(workflowActivityList); }
public async Task <IAggregateEvent <TAggregateKey>[]> GetEventsAsync(TAggregateKey aggregateId, CancellationToken cancellationToken = default) { List <string> serializedEvents = await _context.GetDbSet() .Where(x => x.AggregateId.Equals(aggregateId)) .OrderBy(x => x.AggregateVersion) .Select(x => x.Serialized) .ToListAsync(cancellationToken); return(serializedEvents .Select(x => _eventSerializer.Deserialize(x)) .ToArray()); }
private async Task <Simple> LoadSimple() { if (!File.Exists(DBFilesBTreeTests.ObjFileName)) { Assert.Inconclusive("No binary object file to test against."); } byte[] Bin = File.ReadAllBytes(DBFilesBTreeTests.ObjFileName); BinaryDeserializer Reader = new BinaryDeserializer(DBFilesBTreeTests.CollectionName, Encoding.UTF8, Bin, uint.MaxValue); IObjectSerializer Serializer = await this.provider.GetObjectSerializer(typeof(Simple)); return((Simple)await Serializer.Deserialize(Reader, ObjectSerializer.TYPE_OBJECT, false)); }
public XmlDataStoreRepository() { dataStoreRepositoryPath = ConfigurationItem<string>.ReadSetting("XmlDataStoreRepositoryPath").GetValue(); serializer = new XmlObjectSerializer(); if (!File.Exists(dataStoreRepositoryPath)) { dataStores = new XmlDataStoreCollection(); File.WriteAllText(dataStoreRepositoryPath, serializer.Serialize(dataStores)); return; } dataStores = serializer.Deserialize<XmlDataStoreCollection>(File.ReadAllText(dataStoreRepositoryPath)); }
public SecureXmlDataStoreRepository() { key = ConfigurationItem<string>.ReadSetting("SecureXmlDataStoreRepositoryKey").GetValue(); dataStoreRepositoryPath = ConfigurationItem<string>.ReadSetting("SecureXmlDataStoreRepositoryPath").GetValue(); serializer = new XmlObjectSerializer(); if (!File.Exists(dataStoreRepositoryPath)) { dataStores = new XmlDataStoreCollection(); File.WriteAllText(dataStoreRepositoryPath, serializer.Serialize(dataStores)); return; } dataStores = serializer.Deserialize<XmlDataStoreCollection>(File.ReadAllText(dataStoreRepositoryPath)); PersistStore(); // force encryption for any insecure connection strings }