/// <summary>Initializes a new instance of the <see cref="OntologyFactory"/> class.</summary> public OntologyFactory() { _container = new ServiceContainer(); _container.RegisterAssembly(GetType().GetTypeInfo().Assembly); _ontologyFactoryMimeTypeMappingCache = new Dictionary <string, IOntologyLoader>(); _contentTypeResolver = new ContentTypeResolver(_container.GetAllInstances <IContentTypeResolver>()); }
public void Resolve_EmptyHeadersCollection_ReturnsJsonAsDefault() { // Arrange var contentTypes = new[] { new ApplicationJsonContentType(_jsonSerializerMock.Object) }; var contentTypeResolver = new ContentTypeResolver(contentTypes); // Act var contentType = contentTypeResolver.Resolve(new HeaderDictionary()); // Assert Assert.AreEqual(ContentType.ApplicationJson, contentType.HeaderValue); }
protected override ResourceInfo GetResourceInfo(WebDavTicket ticket) { ResourceInfo retVal = new ResourceInfo(); EmailStorageAbsolutePath absPath = ticket.AbsolutePath as EmailStorageAbsolutePath; if (absPath == null) { throw new ArgumentException("absPath"); } EMailMessageRow row = new EMailMessageRow(absPath.EmailMsgId); MemoryStream memStream = new MemoryStream(row.EmlMessage.Length); memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length); memStream.Position = 0; Pop3Message message = new Pop3Message(memStream); int attachmentIndex = absPath.EmailAttachmentIndex; Mediachase.IBN.Business.EMail.EMailMessageInfo.AttachmentData entry = EMailMessageInfo.GetAttachment(message.MimeEntries, ref attachmentIndex); if (entry != null) { retVal.AbsolutePath = ticket.ToString(); retVal.Tag = entry; retVal.Name = entry.FileName; //Fix ET:26-11-2008 Solve trouble inconsistency Content-Type email attachment and file extension //try first get Content-Type by file extension retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(entry.FileName)); if (String.IsNullOrEmpty(retVal.ContentType)) { //otherwise set ContentType as ContentType email attachment retVal.ContentType = entry.ContentType; } retVal.ContentLength = entry.Data.Length; retVal.ParentName = "root"; DateTime created = Database.DBCommon.GetLocalDate(Security.CurrentUser.TimeZoneId, row.Created); retVal.Created = created; retVal.Modified = created; } return(retVal); }
private void ResolveContentTypes(JContainer container) { if (ContentTypeResolver == null || container["$type"] != null) { return; } var contentType = container["sys"]?["contentType"]?["sys"]?["id"]?.ToString(); if (contentType == null) { return; } var type = ContentTypeResolver.Resolve(contentType); if (type != null) { container.AddFirst(new JProperty("$type", type.AssemblyQualifiedName)); } }
public void Resolve_HeadersCollectionWithAnyAcceptedContentType_ReturnsTheContentTypeEquivalentToTheFirstOne() { // Arrange const string expectedContentType = ContentType.ApplicationXml; var headers = new Dictionary <string, StringValues> { { HeaderNames.Accept, new StringValues(new [] { expectedContentType, ContentType.ApplicationJson }) } }; var contentTypes = new IApplicationContentType[] { new ApplicationXmlContentType(_xmlSerializerMock.Object), new ApplicationJsonContentType(_jsonSerializerMock.Object) }; var contentTypeResolver = new ContentTypeResolver(contentTypes); // Act var contentType = contentTypeResolver.Resolve(new HeaderDictionary(headers)); // Assert Assert.AreEqual(expectedContentType, contentType.HeaderValue); }
protected virtual ResourceInfo GetResourceInfo(WebDavTicket ticket) { if (ticket == null) { throw new ArgumentNullException("ticket"); } MetaDataPlusAbsolutePath metaAbsPath = ticket.AbsolutePath as MetaDataPlusAbsolutePath; if (metaAbsPath == null) { throw new NullReferenceException("metaAbsPath"); } ResourceInfo retVal = new ResourceInfo(); MetaObject obj = MetaDataWrapper.LoadMetaObject(metaAbsPath.MetaObjectId, metaAbsPath.MetaObjectType); if (obj == null) { throw new NullReferenceException("obj"); } MetaFile metaFile = (MetaFile)obj[metaAbsPath.MetaFieldName]; if (metaFile != null) { retVal.AbsolutePath = ticket.ToString(); retVal.Tag = new object[] { obj, metaFile, metaAbsPath }; retVal.Name = metaFile.Name; retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(metaFile.Name)); retVal.ContentLength = metaFile.Size; retVal.ParentName = "root"; retVal.Modified = metaFile.LastWriteTime; retVal.Created = metaFile.CreationTime; } return(retVal); }
protected override ResourceInfo GetResourceInfo(WebDavTicket ticket) { MetaDataAbsolutePath metaAbsPath = ticket.AbsolutePath as MetaDataAbsolutePath; if (metaAbsPath == null) { throw new ArgumentException("absPath"); } ResourceInfo retVal = new ResourceInfo(); Mediachase.Ibn.Data.Meta.FileInfo fileInfo = new Mediachase.Ibn.Data.Meta.FileInfo(metaAbsPath.FileUID); retVal.AbsolutePath = ticket.ToString(); retVal.Tag = fileInfo; retVal.Name = fileInfo.Name; retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(fileInfo.Name)); retVal.ContentLength = fileInfo.Length; retVal.ParentName = "root"; retVal.Modified = DateTime.Now; retVal.Created = DateTime.Now; return(retVal); }
/// <summary> /// Gets the active locked webdav resources. /// </summary> /// <returns></returns> public static IEnumerable <WebDavLockInfo> GetActiveLocksInfo() { WebDavAbstractFactory factory = new WebDavAbstractFactory(); foreach (WebDavStorageElementPropertiesRow row in WebDavStorageElementPropertiesRow.List()) { WebDavElementStorageProvider provider = factory.Create <WebDavElementStorageProvider>(row.ObjectTypeId); ResourceInfo resInfo = GetResourceInfoFromPropertyRow(row); if (resInfo != null) { foreach (ActiveLockElement activeLockEl in provider.GetActiveLocks(resInfo)) { OpaqueLockToken lockToken = OpaqueLockToken.Parse(activeLockEl.LockToken.InnerText); McLockElement mcLockEl = GetMcLockElement(lockToken, provider.GetProperties(resInfo)); WebDavLockInfo retval = new WebDavLockInfo(); retval.WebDavElementPropertyId = row.PrimaryKeyId.Value; retval.FileName = resInfo.Name; retval.ContentTypeId = ContentTypeResolver.GetContentTypeId(resInfo.ContentType); retval.StartLocking = new DateTime(mcLockEl.CreationDate * TimeSpan.TicksPerSecond); retval.Duration = DateTime.UtcNow - retval.StartLocking; UserLight user = UserLight.Load(activeLockEl.Owner); if (user != null) { retval.LockedBy = user.DisplayName; } else { retval.LockedBy = "Unknow"; } yield return(retval); } } } }
public void ProcessRequest(HttpContext context) { //try //{ //проверяем есть ли в ticket-е идентификатор сессии WebDavTicket ticket = WebDavUrlBuilder.GetWebDavTicket(context.Request.Url.ToString()); if (ticket == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI."); } if (!WebDavAuthHelper.WebDavAuthentificate(context, ticket)) { //Используем стандартный механизм аутентификации System.Web.Security.FormsAuthentication.RedirectToLoginPage(); return; } //throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized"); WebDavAbstractFactory factory = new WebDavAbstractFactory(); WebDavElementStorageProvider storageProvider = factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType); if (storageProvider == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI."); } //Запускаем механизм обработки web dav запроса WebDavTicketRequest request = new WebDavTicketRequest(context.Request, ePluginToken.webdav); WebDavTicketResponse response = new WebDavTicketResponse(context.Response); WebDavApplication.DefaultProvider = storageProvider; try { bool enableTrace = Convert.ToBoolean(ConfigurationManager.AppSettings[ConstEnableTrace]); if (enableTrace) { WebDavTracer.TraceBinaryBody = false; WebDavTracer.EnableTrace = true; } } catch (FormatException) { } if (request.HttpMethod == WebDavHttpMethod.GET) { //для get запросов выключаем буферизацию для работы с большими файлами context.Response.BufferOutput = false; //Некоторые браузеры кешируют результаты GET запроса при редактировании на сервере. //Установка expires равную текущей дате позволят указать браузеру что кеширование не требуется HttpCachePolicy cache = HttpContext.Current.Response.Cache; cache.SetExpires(DateTime.Now); //Если для запрошенного файла стоит флаг ForceDownload и не включен фдаг WebDav //то вернуть как attachment для выбора пользователем приложения для работы с документом if (!string.IsNullOrEmpty(ticket.AbsolutePath.FileName)) { string fileExtension = Path.GetExtension(ticket.AbsolutePath.FileName); if (!ContentTypeResolver.IsWebDAVSupportedExtension(fileExtension) && ContentTypeResolver.IsAllowForceDownload(fileExtension)) { context.Response.AddHeader("Content-Disposition", "attachment;" + "filename=" + ticket.AbsolutePath.FileName); } } } WebDavApplication.ProcessRequest(request, response); //} //catch (HttpException ex) //{ // // Http Exception // context.Response.Clear(); // context.Response.ContentEncoding = System.Text.Encoding.UTF8; // context.Response.StatusCode = ex.GetHttpCode(); // context.Response.StatusDescription = ex.Message; //} //catch (Exception ex) //{ // // Global Exception // context.Response.Clear(); // context.Response.ContentEncoding = System.Text.Encoding.UTF8; // context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; // context.Response.StatusDescription = ex.Message; // byte[] errorBuffer = System.Text.Encoding.UTF8.GetBytes(ex.ToString()); // context.Response.OutputStream.Write(errorBuffer, 0, errorBuffer.Length); //} //context.Response.Flush(); }
/// <summary> /// Gets all the entries of a space, filtered by an optional querystring. A simpler approach than /// to construct a query manually is to use the <see cref="QueryBuilder{T}"/> class. /// </summary> /// <typeparam name="T">The class to serialize the response into. If you want the metadata to /// be included in the serialized response use the <see cref="Entry{T}"/> class as a type parameter.</typeparam> /// <param name="queryString">The optional querystring to add additional filtering to the query.</param> /// <param name="cancellationToken">The optional cancellation token to cancel the operation.</param> /// <returns>A <see cref="ContentfulCollection{T}"/> of items.</returns> /// <exception cref="ContentfulException">There was an error when communicating with the Contentful API.</exception> public async Task <ContentfulCollection <T> > GetEntriesAsync <T>(string queryString = null, CancellationToken cancellationToken = default(CancellationToken)) { var res = await GetAsync($"{_baseUrl}{_options.SpaceId}/entries{queryString}", cancellationToken).ConfigureAwait(false); IEnumerable <T> entries; var json = JObject.Parse(await res.Content.ReadAsStringAsync().ConfigureAwait(false)); var isContentfulResource = typeof(IContentfulResource).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); var processedIds = new HashSet <string>(); foreach (var item in json.SelectTokens("$.items[*]").OfType <JObject>()) { if (isContentfulResource) { ResolveLinks(json, item, processedIds, typeof(T).GetRuntimeProperty("Fields").PropertyType); } else { ResolveLinks(json, item, processedIds, typeof(T)); } } if (isContentfulResource) { entries = json.SelectToken("$.items").ToObject <IEnumerable <T> >(Serializer); } else { var entryTokens = json.SelectTokens("$.items[*]..fields").ToList(); for (var i = entryTokens.Count - 1; i >= 0; i--) { var token = entryTokens[i]; var grandParent = token.Parent.Parent; if (grandParent["sys"]?["type"] != null && grandParent["sys"]["type"]?.ToString() != "Entry") { continue; } if (ContentTypeResolver != null) { var contentType = grandParent["sys"]["contentType"]["sys"]["id"]?.ToString(); var type = ContentTypeResolver.Resolve(contentType); if (type != null) { grandParent.AddFirst(new JProperty("$type", type.AssemblyQualifiedName)); } } //Remove the fields property and let the fields be direct descendants of the node to make deserialization logical. token.Parent.Remove(); grandParent.Add(token.Children()); } entries = json.SelectToken("$.items").ToObject <IEnumerable <T> >(Serializer); } var collection = json.ToObject <ContentfulCollection <T> >(Serializer); collection.Items = entries; collection.IncludedAssets = json.SelectTokens("$.includes.Asset[*]")?.Select(t => t.ToObject <Asset>(Serializer)); collection.IncludedEntries = json.SelectTokens("$.includes.Entry[*]")?.Select(t => t.ToObject <Entry <dynamic> >(Serializer)); return(collection); }