Пример #1
0
        public Selectable(string text, string urlOrPadding, ContentType contentType)
        {
            switch (contentType)
            {
                case ContentType.Html:
                    {
                        HtmlDocument document = new HtmlDocument();
                        document.OptionAutoCloseOnEnd = true;
                        document.LoadHtml(text);

                        if (!string.IsNullOrEmpty(urlOrPadding))
                        {
                            FixAllRelativeHrefs(document, urlOrPadding);
                        }

                        Elements = new List<dynamic> { document.DocumentNode.OuterHtml };
                        break;
                    }
                case ContentType.Json:
                    {
                        string json = string.IsNullOrEmpty(urlOrPadding) ? text : RemovePadding(text, urlOrPadding);
                        Elements = new List<dynamic> { json };
                        break;
                    }
            }
        }
Пример #2
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public ContentRootFolder(ContentType type)
 {
     this.ContentType = type;
     childFolders.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(childFolders_CollectionChanged);
     this.Id = idCnt++;
     this.Temporary = false;
 }
Пример #3
0
        public override void SetDefaultValues(ContentType contentType)
        {
            base.SetDefaultValues(contentType);

            HideSiteFooter = true;
            HideSiteHeader = true;
        }
Пример #4
0
		public override byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment)
		{
			HashAlgorithm hash = CreateHashAlgorithm ();

			byte[] smac = this.Context.Read.ServerWriteMAC;
			hash.TransformBlock (smac, 0, smac.Length, smac, 0);
			hash.TransformBlock (pad1, 0, pad1.Length, pad1, 0);

			if (header == null)
				header = new byte [MacHeaderLength];

			ulong seqnum = (Context is ClientContext) ? Context.ReadSequenceNumber : Context.WriteSequenceNumber;
			Write (header, 0, seqnum);
			header [8] = (byte) contentType;
			Write (header, 9, (short)fragment.Length);
			hash.TransformBlock (header, 0, header.Length, header, 0);
			hash.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
			// hack, else the method will allocate a new buffer of the same length (negative half the optimization)
			hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);

			byte[] blockHash = hash.Hash;

			hash.Initialize ();

			hash.TransformBlock (smac, 0, smac.Length, smac, 0);
			hash.TransformBlock (pad2, 0, pad2.Length, pad2, 0);
			hash.TransformBlock (blockHash, 0, blockHash.Length, blockHash, 0);
			// hack again
			hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);

			return hash.Hash;
		}
        /// <summary>
        /// Add content type to list
        /// </summary>
        /// <param name="list"></param>
        /// <param name="contentType"></param>
        /// <param name="defaultContent"></param>
        public static void AddContentTypeToList(this List list, ContentType contentType, bool defaultContent = false)
        {
            list.ContentTypesEnabled = true;
            list.Update();
            list.Context.ExecuteQuery();
            ContentTypeCollection contentTypes = list.ContentTypes;
            list.Context.Load(contentTypes);
            list.Context.ExecuteQuery();

            foreach (ContentType ct in contentTypes)
            {
                if (ct.Name.ToLowerInvariant() == contentType.Name.ToString().ToLowerInvariant())
                {
                    // Already there, abort
                    return;
                }
            }

            contentTypes.AddExistingContentType(contentType);
            list.Context.ExecuteQuery();
            //set the default content type
            if (defaultContent)
            {
                SetDefaultContentTypeToList(list, contentType);
            }
        }
 /// <summary>
 /// Adds content type to list
 /// </summary>
 /// <param name="web"></param>
 /// <param name="listTitle"></param>
 /// <param name="contentType"></param>
 /// <param name="defaultContent">If set true, content type is updated to be default content type for the list</param>
 public static void AddContentTypeToList(this Web web, string listTitle, ContentType contentType, bool defaultContent = false)
 {
     // Get list instances
     List list = web.GetListByTitle(listTitle);
     // Add content type to list
     AddContentTypeToList(list, contentType, defaultContent);
 }
Пример #7
0
        public async Task<IDictionary<long, Program>> LoadAsync(ContentType contentType, CancellationToken cancellationToken)
        {
            var playlists = Playlists;

            foreach (var playlist in playlists)
            {
                try
                {
                    var parser = new M3U8Parser();

                    if (null != _playlistWebReader)
                        _playlistWebReader.Dispose();

                    _playlistWebReader = _webReaderManager.CreateReader(playlist, ContentKind.Playlist, contentType: contentType);

                    var actualPlaylist = await parser.ParseAsync(_playlistWebReader, _retryManager, playlist, cancellationToken)
                        .ConfigureAwait(false);

                    return await LoadAsync(_playlistWebReader, parser, contentType, cancellationToken).ConfigureAwait(false);
                }
                catch (StatusCodeWebException e)
                {
                    // This one didn't work, so try the next playlist url.
                    Debug.WriteLine("HlsProgramManager.LoadAsync: " + e.Message);
                }
            }

            return NoPrograms;
        }
        public DataStreamContext(Uri u)
        {
            string[] parts = Utility.SplitInTwo(u.PathAndQuery, ',');
            if (parts.Length != 2)
                throw RuntimeFailure.NotValidDataUri();

            var ct = Regex.Replace(parts[0], ";base64", string.Empty);
            if (ct.Length == 0)
                this.contentType = new ContentType("text", "plain");
            else
                this.contentType = ContentType.Parse(ct);

            byte[] buffer;

            this.isBase64 = ct.Length < parts[0].Length; // implied by replacement
            if (this.isBase64)
                buffer = Convert.FromBase64String(parts[1]);
            else
                buffer = System.Text.Encoding.ASCII.GetBytes(WebUtility.UrlDecode(parts[1]));

            this.baseUri = string.Concat("data:",
                                         this.contentType,
                                         this.isBase64 ? ";base64" : string.Empty,
                                         ",");
            this.data = new MemoryStream(buffer.Length);
            this.data.Write(buffer, 0, buffer.Length);
        }
 public AttachedAlbumData(ContentType type, Uri linkUrl,
     AlbumData album, AttachedImageData[] pictures, Uri plusBaseUrl)
     : base(type, linkUrl)
 {
     Album = album;
     Pictures = pictures;
 }
Пример #10
0
        protected void TestCleanTextTypeFromDocument(string fileName, ContentType contentType, string[] textThatShouldntBeCleaned)
        {
            fileName = TESTFILE_DIR + fileName;
            string outFileName = fileName + "_cleaned.doc";
            File.Copy(fileName, outFileName, true);
            using (Workshare.FCS.Lite.WordDocumentReader docReader = new WordDocumentReader(outFileName, true))
            {
                docReader.Clean(BuildContentTypeList(contentType));
            }

            using (WordDocumentReader docReader2 = new WordDocumentReader(outFileName, false))
            {
                DocumentText dt = docReader2.Read();

                IAbstractTextType tt = dt.GetUniqueTextType(contentType);
                IAbstractTextType ttHid = dt.GetUniqueTextType(ContentType.HiddenText);
                if (tt == null && ttHid == null)
                {
                    CheckHaventCleanedTooMuch(dt.GetUniqueTextType(ContentType.Paragraph), textThatShouldntBeCleaned);

                    return;
                }

                if (tt != null)
                    Assert.AreEqual(0, tt.Nodes.Count, "Expected all the items of type " + contentType.ToString() + " to have been cleaned");

                if (ttHid != null)
                    Assert.AreEqual(0, ttHid.Nodes.Count, "Expected no significant hidden text to show up");


            }
        }
 public DataStreamContext(MemoryStream data, ContentType contentType)
 {
     this.contentType = contentType;
     this.baseUri = string.Format("data:{0};base64,", this.contentType);
     this.data = data;
     this.isBase64 = true;
 }
Пример #12
0
		private TextType AddKeyWordProperty(TextType propType, string name, string value, ContentType property)
		{
			if (propType == null)
			{
				propType = new TextType(property);
				m_docText.AddTextType(propType);
			}

			TextNode newNode = new TextNode();
			newNode.AddParent(propType);
			propType.AddChild(newNode);

			newNode.AddInfo(new NodeInfo()
			{
				name = "Name",
				type = DataType.String,
				value = name
			});

			newNode.AddInfo(new NodeInfo()
			{
				name = "Value",
				type = DataType.String,
				value = value
			});

			return propType;
		}
        public bool CanFormatResponse(ContentType acceptHeaderElement, bool matchCharset, out ContentType contentType)
        {
            if (acceptHeaderElement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("acceptHeaderElement");
            }

            // Scrub the content type so that it is only mediaType and the charset
            string charset = acceptHeaderElement.CharSet;
            contentType = new ContentType(acceptHeaderElement.MediaType);
            contentType.CharSet = this.DefaultContentType.CharSet;
            string contentTypeStr = contentType.ToString();
            
            if (matchCharset &&
                !string.IsNullOrEmpty(charset) &&
                !string.Equals(charset, this.DefaultContentType.CharSet, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            if (this.contentTypeMapper != null &&
                this.contentTypeMapper.GetMessageFormatForContentType(contentType.MediaType) == this.ContentFormat)
            {
                return true;
            }

            if (this.Encoder.IsContentTypeSupported(contentTypeStr) && 
                (charset == null || contentType.CharSet == this.DefaultContentType.CharSet))
            {
                return true;
            }
            contentType = null;
            return false;
        }
Пример #14
0
		private static void CreateFields(ClientContext ctx, ContentType orderCT) {
			#region Customer
			FieldCreationInformation customer = new FieldCreationInformation(FieldType.Lookup);
			customer.DisplayName = "Customer";
			customer.InternalName = "Customer";
			customer.Group = "ODA1";
			customer.Id = Constants.GUID.OrderCT.CUSTOMER.ToGuid();

			ctx.Web.AddFieldToContentType(orderCT, ctx.Web.CreateField<FieldUrl>(customer, false));
			#endregion
			#region Product
			TaxonomyFieldCreationInformation product = new TaxonomyFieldCreationInformation();

			product.DisplayName = "Product";
			product.InternalName = "Product_2";
			product.Group = "ODA1";
			product.TaxonomyItem = GetProductTermSet(ctx);
			
			product.Id = Constants.GUID.OrderCT.PRODUCT.ToGuid();
			var meh = ctx.Web.CreateTaxonomyField(product);
			ctx.ExecuteQuery();
			ctx.Web.WireUpTaxonomyField(meh, product.TaxonomyItem as TermSet);
			ctx.Web.AddFieldToContentType(orderCT, meh );
			#endregion
			#region Price
			FieldCreationInformation price = new FieldCreationInformation(FieldType.Currency);
			price.DisplayName = "Price";
			price.InternalName = "Price";
			price.Group = "ODA1";
			price.Id = Constants.GUID.OrderCT.PRICE.ToGuid();

			FieldUrl addedPrice = ctx.Web.CreateField<FieldUrl>(price, false);
			ctx.Web.AddFieldToContentType(orderCT, addedPrice);
			#endregion
		}
Пример #15
0
    /// <summary>
    /// Get a list of entries for a specific stream.
    /// </summary>
    /// <remarks>streams-endpoint (https://developer.feedly.com/v3/streams/#get-the-content-of-a-stream)</remarks>
    /// <param name="id">A feedId, a categoryId, a tagId or a system category id.</param>
    /// <param name="type">The type of the <paramref name="id"/>.</param>
    /// <param name="count">Number of entry ids to return. Default is 20, max is 10000.</param>
    /// <param name="sorting">Newest or oldest. Default is newest.</param>
    /// <param name="unreadOnly">if <c>true</c>, return unread entries only.</param>
    /// <param name="newerThan">Date from where to search on.</param>
    /// <param name="continuation">A continuation id is used to page through the entries.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public async Task<FeedlyStreamEntriesResponse> GetStreamEntries(
      string id,
      ContentType type,
      int? count = null,
      FeedSorting sorting = FeedSorting.Newest,
      bool? unreadOnly = null,
      DateTime? newerThan = null,
      string continuation = null,
      CancellationToken cancellationToken = default(CancellationToken))
    {
      Dictionary<string, string> parameters = new Dictionary<string, string>();
      parameters["streamId"] = ValueToResource(type, id);
      parameters["ranked"] = sorting.ToString().ToLower();
      if (count.HasValue)
      {
        parameters["count"] = count.Value.ToString();
      }
      if (unreadOnly.HasValue)
      {
        parameters["unreadOnly"] = unreadOnly.Value.ToString();
      }
      if (newerThan.HasValue)
      {
        DateTime date = ((DateTime)newerThan.Value).ToUniversalTime();
        DateTime epoc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        parameters["newerThan"] = Math.Truncate(date.Subtract(epoc).TotalMilliseconds).ToString();
      }
      if (!String.IsNullOrEmpty(continuation))
      {
        parameters["continuation"] = continuation;
      }

      return await Client.Request<FeedlyStreamEntriesResponse>(HttpMethod.Get, "v3/streams/contents", parameters, false, (type == ContentType.Category || type == ContentType.Tag), cancellationToken);
    }
        public static RequestInfo Create(
            RequestMethod method, string target, string uriTemplate, Dictionary<string, object> parameters,
            string userAgent, Dictionary<string, string> headers, ContentType requestContentType,
            ContentType responseContentType, TimeSpan cacheDuration,
            int timeout, int retryCount,
            Uri uri, string requestBody, IRequestFactory requestFactory)
        {
            var result = new RequestInfo
                             {
                                 Target = target,
                                 UriTemplate = uriTemplate,
                                 AllowedRetries = retryCount,
                                 Uri = uri,
                                 Method = method,
                                 UserAgent = userAgent,
                                 _headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>()),
                                 RequestBody = requestBody,
                                 Parameters = new Dictionary<string, object>(parameters ?? new Dictionary<string, object>()),
                                 CacheDuration = cacheDuration,
                                 RequestContentType = requestContentType,
                                 ResponseContentType = responseContentType,
                                 Timeout = timeout
                             };

            return result;
        }
 public XlsxMacrosheetXmlPartFilter(CommonNamespaces commonNamespaces, Dictionary<string, string> StringContentLookup, Dictionary<string, WorkSheet> WorksheetLookup, Dictionary<string, CellFormatData> CellFormats, ContentType[] contentTypesToDetect, ref XlsxProcessingDictionaries processingDictionaries, ref PredefinedObjectsProcessingHelper predefinedObjectsHelper, PartInfo rel)
     : base(commonNamespaces, rel.Target, StringContentLookup, WorksheetLookup, CellFormats, contentTypesToDetect, ref processingDictionaries, ref predefinedObjectsHelper)
 {
     m_id = rel.Id;
     m_target = rel.Target;
     m_type = rel.GetContentType();
 }
Пример #18
0
 public StreamFormData(Stream stream, string filename)
 {
     this.fileStream = stream;
     this.filename = filename;
     //  TODO: make this dynamic
     this.contentType = ContentType.Application_vnd_ms_excel;
 }
Пример #19
0
 public void View(string contentName, ContentType type)
 {
     if (viewers.ContainsKey(type))
         viewers[type].PreviewContent(contentName);
     else
         ShowNoPreviewText(contentName);
 }
Пример #20
0
 public DocumentSetPipeBind()
 {
     _id = string.Empty;
     _name = string.Empty;
     _contentType = null;
     _documentSetTemplate = null;
 }
Пример #21
0
        public override void Get(ContentType type)
        {
            var result = string.Empty;
            var items = new List<AlbumShowModel>();

            switch (type)
            {
                case ContentType.Json:
                    result = this.Consumer.Get(this.Uri);
                    items = JsonConvert.DeserializeObject<List<AlbumShowModel>>(result);
                    break;
                case ContentType.Xml:
                    result = this.Consumer.Get(this.Uri, "application/xml");
                    XElement xml = XElement.Parse(result);
                    Console.WriteLine(xml);
                    return;
            }

            if (result == "NotFound")
            {
                Console.WriteLine("NotFound");
                return;
            }

            foreach (var item in items)
            {
                Console.WriteLine("{0} {1} {2}", item.Title, item.Producer, item.ReleaseDate);
            }
        }
Пример #22
0
        public static string GetContentType(ContentType contentType)
        {
            if (ContentTypes.ContainsKey(contentType))
                return ContentTypes[contentType];

            return null;
        }
Пример #23
0
        public void MimeHeader_ContentType_Name()
        {
            var parser = Parser10;
            ContentType contentType = null;

            contentType = new ContentType();
            contentType.RawValue = "Image/png;\r\n"
                + "\tName=\"MyFile;01.pdf\";";
            parser.ParseContentType(contentType);
            Assert.AreEqual("MyFile;01.pdf", contentType.Name);

            contentType = new ContentType();
            contentType.RawValue = "Image/png;\r\n"
                + "\tName=MyFile\"05.pdf;";
            parser.ParseContentType(contentType);
            Assert.AreEqual("MyFile\"05.pdf", contentType.Name);

            contentType = new ContentType();
            contentType.RawValue = "Image/png;\r\n"
                + "\tName=\"MyFile\"06.pdf\";";
            parser.ParseContentType(contentType);
            Assert.AreEqual("MyFile\"06.pdf", contentType.Name);

            //Maybe...
            contentType = new ContentType();
            contentType.RawValue = "Image/png;\r\n"
                + "\tName=\"MyFile\"07.pdf;\r\n"
                + "\tcharset=\"UTF-8\"";
            parser.ParseContentType(contentType);
            Assert.AreEqual("\"MyFile\"07.pdf;", contentType.Name);
        }
        public virtual CodeCompileUnit BuildContentTypeClass(ContentType contentType)
        {
            var unit = new CodeCompileUnit();

            // Add global namespace used for Imports
            _globalNameSpace = AddGlobalNamespace(unit);

            // Add main type namespace
            var mainNamespace = AddMainNamespace(unit, contentType);

            // Add main type declaration
            var typeDeclaration = AddTypeDeclaration(mainNamespace, contentType);

            // Add main type attributes
            AddContentTypeAttribute(contentType, typeDeclaration);
            AddAccessAttribute(contentType, typeDeclaration);

            // Add properties
            foreach (var propertyDefinition in contentType.PropertyDefinitions)
            {
                AddPropertyDeclaration(propertyDefinition, typeDeclaration);
            }

            AddDefaultValuesMethod(contentType, typeDeclaration);

            return unit;
        }
Пример #25
0
        public static IList<ContentType> CreateTestContentTypes()
        {
            List<ContentType> results = new List<ContentType>();

            ContentTypeRepository repo = new ContentTypeRepository();

            ContentType item = new ContentType()
            {
                Text = "text"
            };

            results.Add(item);
            repo.Add(item);

            item = new ContentType()
            {
                Text = "html"
            };

            results.Add(item);
            repo.Add(item);

            item = new ContentType()
            {
                Text = "xhtml"
            };

            results.Add(item);
            repo.Add(item);

            repo.Save();

            return results;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static Encoding GetEncoding(this byte[] message, string contentType)
        {
            var charSet = new ContentType(contentType).CharSet.ToLower();
            switch (charSet)
            {
                case "utf-8":
                    return new UTF8Encoding();

                case "utf-16":
                    if (message[0] == 0xff && message[1] == 0xfe)
                    {
                        return new UnicodeEncoding(false, true);
                    }
                    if (message[0] == 0xfe && message[1] == 0xff)
                    {
                        return new UnicodeEncoding(true, true);
                    }

                    throw new InvalidOperationException("No byte order mark detected. Byte order mark required when charset=utf-16");

                case "utf-16le":
                    return new UnicodeEncoding(false, false);

                case "utf-16be":
                    return new UnicodeEncoding(true, false);

                default:                  
                    throw new InvalidOperationException("Unrecognised charset: " + charSet);
            }
        }
Пример #27
0
 public void LoadSettings(ContentType type)
 {
     this.folders = new ContentRootFolderCollection(type);
     this.contentType = type;
     foreach (ContentRootFolder flder in contentType == ContentType.Movie ? Settings.MovieFolders : Settings.TvFolders)
         folders.Add(new ContentRootFolder(flder));
 }
		public void ContentTypeOfXmlFileDependsOnRootElement(string tag,
			ContentType expectedContentType)
		{
			string xmlData = CreateXmlDataFromTag(tag);
			ContentType contentTypeFromXmlRoot = GetContentTypeOfXmlData(xmlData);
			Assert.AreEqual(expectedContentType, contentTypeFromXmlRoot);
		}
 public IQueryable<MediaContent> GetLast(ContentType type, int count = GlobalConstants.HomeLastContentCount)
 {
     return this.contents.GetAll()
         .Where(c => c.ContentType == type)
         .OrderByDescending(c => c.CreatedOn)
         .Take(count);
 }
        protected virtual async Task<ISubProgram> LoadSubProgram(IProgramManager programManager, ContentType contentType, CancellationToken cancellationToken)
        {
            ISubProgram subProgram;

            try
            {
                var programs = await programManager.LoadAsync(contentType, cancellationToken).ConfigureAwait(false);

                var program = programs.Values.FirstOrDefault();

                if (null == program)
                {
                    Debug.WriteLine("PlaylistSegmentManagerFactory.SetMediaSource(): program not found");
                    throw new FileNotFoundException("Unable to load program");
                }

                subProgram = SelectSubProgram(program.SubPrograms);

                if (null == subProgram)
                {
                    Debug.WriteLine("PlaylistSegmentManagerFactory.SetMediaSource(): no sub programs found");
                    throw new FileNotFoundException("Unable to load program stream");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("PlaylistSegmentManagerFactory.SetMediaSource(): unable to load playlist: " + ex.Message);
                throw;
            }

            return subProgram;
        }
Пример #31
0
        public override void SetDefaultValues(ContentType contentType)
        {
            base.SetDefaultValues(contentType);

            ButtonStyle = "btn-blue";
        }
Пример #32
0
        private Dictionary <object, object> getFieldMappings(string webURL, List <ApplicationItemProperty> properties, List <ContentType> contentTypes, FolderSettings folderSettings, FolderSetting defaultFolderSetting, ISiteSetting siteSetting, string rootFolder, out ContentType contentType, bool displayFileName)
        {
            Dictionary <object, object> mappings = new Dictionary <object, object>();

            EditItemPropertiesControl editItemPropertiesControl = new EditItemPropertiesControl(webURL, properties, contentTypes, folderSettings, defaultFolderSetting, siteSetting, rootFolder, null, displayFileName);
            bool?dialogResult = editItemPropertiesControl.ShowDialog(null, Languages.Translate("Mappings..."));

            if (dialogResult.HasValue == false || dialogResult.Value == false)
            {
                contentType = null;
                return(null);
            }
            else
            {
                return(editItemPropertiesControl.GetValues(out contentType));
            }
        }
Пример #33
0
        /// <summary>
        ///     根据相传入的数据,得到相应页面数据
        /// </summary>
        /// <param name="strPostdata">传入的数据Post方式,get方式传NUll或者空字符串都可以</param>
        /// <param name="ContentType">返回的响应数据的类型</param>
        /// <returns>string类型的响应数据</returns>
        private string GetHttpRequestData(HttpWebRequest request, HttpItem objhttpitem, out ContentType ContentType, out HttpStatusCode statusCode)
        {
            var result = "";

            #region 得到请求的response

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var _stream = new MemoryStream();

                var docu = objhttpitem.GetHeaderParameter();
                if (response.Headers["set-cookie"] != null)
                {
                    docu["Cookie"] = MergeCookie(docu["Cookie"].ToString(), response.Headers["set-cookie"]);
                }

                statusCode = response.StatusCode;
                objhttpitem.ResponseHeaders = response.Headers;
                objhttpitem.Parameters      = objhttpitem.HeaderToString(docu);
                //GZIIP处理
                if (response.ContentEncoding != null &&
                    response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                {
                    //开始读取流并设置编码方式
                    //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                    //.net4.0以下写法
                    _stream =
                        GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                }
                else
                {
                    //开始读取流并设置编码方式
                    //response.GetResponseStream().CopyTo(_stream, 10240);
                    //.net4.0以下写法
                    _stream = GetMemoryStream(response.GetResponseStream());
                }
                //获取Byte
                var RawResponse = _stream.ToArray();
                //是否返回Byte类型数据

                //从这里开始我们要无视编码了
                if (objhttpitem.Encoding == EncodingType.Unknown || encoding == null)
                {
                    var temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
                    //<meta(.*?)charset([\s]?)=[^>](.*?)>
                    var meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']",
                                           RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    var charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
                    charter = charter.Replace("\"", string.Empty)
                              .Replace("'", string.Empty)
                              .Replace(";", string.Empty);
                    if (charter.Length > 0)
                    {
                        charter = charter.ToLower().Replace("iso-8859-1", "gbk");
                        if (charter.Contains("utf-8") || charter.Contains("UTF-8"))
                        {
                            encoding = Encoding.UTF8;
                        }
                        else if (charter.Contains("gb"))
                        {
                            encoding = Encoding.GetEncoding("GB2312");
                        }
                        else
                        {
                            encoding = Encoding.GetEncoding(charter);
                        }
                    }
                    else
                    {
                        if (response.CharacterSet != null && response.CharacterSet.ToLower().Trim() == "iso-8859-1")
                        {
                            encoding = Encoding.GetEncoding("gbk");
                        }
                    }
                }

                if (response.ContentType.Contains("json"))
                {
                    ContentType = ContentType.Json;
                }
                else if (response.ContentType.Contains("xml"))
                {
                    ContentType = ContentType.XML;
                }
                else
                {
                    ContentType = ContentType.Text;
                }
                //得到返回的HTML
                result = encoding.GetString(RawResponse);
                //最后释放流
                _stream.Close();
            }

            return(result);
        }
Пример #34
0
        private static void RenderCacheFootprint(IEnumerable <ObjectCache> caches, HttpContext httpContext, ContentType outputType, bool expanded)
        {
            var response = httpContext.Response;

            switch (outputType)
            {
            case ContentType.Xml:
            {
                response.ContentEncoding = System.Text.Encoding.UTF8;
                response.Expires         = -1;
                var footprint = caches.First().GetCacheFootprintXml(expanded, httpContext.Request.Url);
                footprint.Save(response.Output);
            }
            break;

            case ContentType.Json:
            default:
                using (StreamWriter writer = new StreamWriter(response.OutputStream))
                {
                    var footprint = caches.First().GetCacheFootprintJson(expanded, httpContext.Request.Url);
                    using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(writer)
                    {
                        QuoteName = false, Formatting = Newtonsoft.Json.Formatting.Indented
                    })
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(jsonWriter, footprint);
                        jsonWriter.Flush();
                    }
                }
                break;
            }
        }
Пример #35
0
        public void SetFileNameAndPathIfFileExists(ServerContext serverContext, HttpContext httpContext)
        {
            var contentType  = httpContext.Response.ContentType;
            var fileFullName = serverContext.FileServerBasePath + httpContext.Request.Uri.LocalPath;

            if (fileFullName.ToUpper().IndexOf(".HTM") != -1 || fileFullName.ToUpper().IndexOf(".HTML") != -1)
            {
                contentType = new ContentType {
                    MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Html
                };
            }
            else if (fileFullName.ToUpper().IndexOf(".CSS") != -1)
            {
                contentType = new ContentType {
                    MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Css
                };
            }
            else if (fileFullName.ToUpper().IndexOf(".TXT") != -1)
            {
                contentType = new ContentType {
                    MainContentType = EnumMainContentType.Text, SubContentType = EnumSubContentType.Plain
                };
            }
            else if (fileFullName.ToUpper().IndexOf(".JPG") != -1 ||
                     fileFullName.ToUpper().IndexOf(".BMP") != -1 ||
                     fileFullName.ToUpper().IndexOf(".JPEG") != -1)
            {
                contentType = new ContentType {
                    MainContentType = EnumMainContentType.Image, SubContentType = EnumSubContentType.Jpeg
                };
            }
            else if (fileFullName.ToUpper().IndexOf(".JS") != -1)
            {
                //note this was text/javascript; I updated because it was obsoleted in favor of application/javascript
                contentType = new ContentType {
                    MainContentType = EnumMainContentType.Application, SubContentType = EnumSubContentType.JavaScript
                };
            }

            if (contentType != null)
            {
                Debug.Print("Set Content Type: " + contentType);
                httpContext.Response.ContentType = contentType;
            }
            else
            {
                Debug.Print("No Matching Content Type set... " + contentType);
                return;
            }

            if (File.Exists(fileFullName))
            {
                var files = new DirectoryInfo(fileFullName.Substring(0, fileFullName.LastIndexOf('\\'))).GetFiles();
                foreach (var file in files)
                {
                    if (file.FullName == fileFullName)
                    {
                        httpContext.Response.FileLength = file.Length.ToString();
                    }
                }
                httpContext.Response.FileFullName   = fileFullName;
                httpContext.Response.HttpStatusCode = new Ok();
            }
        }
        private void UpdateDocumentType()
        {
            const string
                propertyAlias       = "bannerSlider",
                propertyName        = "Banner Slider",
                propertyDescription = "Slider with banner images";

            try
            {
                #region Nested Document Type
                var container   = contentTypeService.GetContainers(DOCUMENT_TYPE_CONTAINER, 1).FirstOrDefault();
                int containerId = -1;

                if (container != null)
                {
                    containerId = container.Id;
                }

                var contentType = contentTypeService.Get(NESTED_DOCUMENT_TYPE_ALIAS);
                if (contentType == null)
                {
                    ContentType docType = (ContentType)contentType ?? new ContentType(containerId)
                    {
                        Name          = NESTED_DOCUMENT_TYPE_NAME,
                        Alias         = NESTED_DOCUMENT_TYPE_ALIAS,
                        AllowedAsRoot = false,
                        Description   = NESTED_DOCUMENT_TYPE_DESCRIPTION,
                        Icon          = NESTED_DOCUMENT_TYPE_ICON,
                        IsElement     = true,
                        SortOrder     = 0,
                        ParentId      = contentTypeService.Get(NESTED_DOCUMENT_TYPE_PARENT_ALIAS).Id,
                        Variations    = ContentVariation.Culture
                    };

                    docType.AddPropertyGroup(SLIDERS_TAB);

                    #region Nested Document Type Properties
                    PropertyType ImagePropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemImage")
                    {
                        Name        = "Image",
                        Description = "Image used in the Slider",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(ImagePropType, SLIDERS_TAB);

                    PropertyType ButtonLabelPropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemButtonLabel")
                    {
                        Name        = " Button Label",
                        Description = "Label for the Button",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(ButtonLabelPropType, SLIDERS_TAB);

                    PropertyType TitlePropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemTitle")
                    {
                        Name        = "Title",
                        Description = "Title for the banner item",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(TitlePropType, SLIDERS_TAB);

                    PropertyType SubtitlePropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemSubtitle")
                    {
                        Name        = "Subtitle",
                        Description = "Subtitle for the banner item",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(SubtitlePropType, SLIDERS_TAB);

                    PropertyType UrlPropType = new PropertyType(dataTypeService.GetDataType(-88), "sliderItemUrl")
                    {
                        Name        = "Url",
                        Description = "The Link to the item",
                        Variations  = ContentVariation.Nothing
                    };
                    docType.AddPropertyType(UrlPropType, SLIDERS_TAB);
                    #endregion

                    contentTypeService.Save(docType);
                    ConnectorContext.AuditService.Add(AuditType.New, -1, docType.Id, "Document Type", $"Document Type '{NESTED_DOCUMENT_TYPE_ALIAS}' has been created");
                }

                else
                {
                    if (contentType.PropertyTypeExists("sliderItemImage") && contentType.PropertyTypes.Single(x => x.Alias == "sliderItemImage").DataTypeId == -88)
                    {
                        var mediaPickerContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                        var mediaPickerContainerId = -1;

                        if (mediaPickerContainer != null)
                        {
                            mediaPickerContainerId = mediaPickerContainer.Id;
                        }

                        var dataTypeExists = dataTypeService.GetDataType("sliderItemImageMediaPicker") != null;
                        if (!dataTypeExists)
                        {
                            var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.MediaPicker", out IDataEditor editor);
                            if (created)
                            {
                                DataType mediaPickerSliderImage = new DataType(editor, mediaPickerContainerId)
                                {
                                    Name          = "sliderItemImageMediaPicker",
                                    ParentId      = mediaPickerContainerId,
                                    Configuration = new MediaPickerConfiguration
                                    {
                                        DisableFolderSelect = true,
                                        Multiple            = false,
                                        OnlyImages          = true
                                    }
                                };
                                dataTypeService.Save(mediaPickerSliderImage);
                                contentType.PropertyTypes.Single(x => x.Alias == "sliderItemImage").DataTypeId = mediaPickerSliderImage.Id;
                                contentTypeService.Save(contentType);
                            }
                        }
                    }
                }
                #endregion

                #region Update Home Document Type
                var homeDocumentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);

                var dataTypeContainer   = dataTypeService.GetContainers(DATA_TYPE_CONTAINER, 1).FirstOrDefault();
                var dataTypeContainerId = -1;

                if (dataTypeContainer != null)
                {
                    dataTypeContainerId = dataTypeContainer.Id;
                }

                var exists = dataTypeService.GetDataType(propertyName) != null;
                if (!exists)
                {
                    var created = Web.Composing.Current.PropertyEditors.TryGet("Umbraco.NestedContent", out IDataEditor editor);
                    if (!created)
                    {
                        DataType bannerSliderNestedDataType = new DataType(editor, dataTypeContainerId)
                        {
                            Name          = propertyName,
                            ParentId      = dataTypeContainerId,
                            Configuration = new NestedContentConfiguration
                            {
                                MinItems       = 0,
                                MaxItems       = 999,
                                ConfirmDeletes = true,
                                HideLabel      = false,
                                ShowIcons      = true,
                                ContentTypes   = new[]
                                {
                                    new NestedContentConfiguration.ContentType {
                                        Alias = NESTED_DOCUMENT_TYPE_ALIAS, TabAlias = SLIDERS_TAB
                                    }
                                }
                            }
                        };
                        dataTypeService.Save(bannerSliderNestedDataType);
                    }
                }
                if (!homeDocumentType.PropertyTypeExists("bannerSlider"))
                {
                    var          bannerSliderNestedDataType = dataTypeService.GetDataType(propertyName);
                    PropertyType BannerSlider = new PropertyType(bannerSliderNestedDataType, propertyAlias)
                    {
                        Name        = propertyName,
                        Description = propertyDescription,
                        Variations  = ContentVariation.Culture
                    };

                    var propertyGroup = homeDocumentType.PropertyGroups.SingleOrDefault(x => x.Name == SLIDERS_TAB);
                    if (propertyGroup == null)
                    {
                        homeDocumentType.AddPropertyGroup(SLIDERS_TAB);
                    }

                    homeDocumentType.AddPropertyType(BannerSlider, SLIDERS_TAB);
                    contentTypeService.Save(homeDocumentType);

                    ConnectorContext.AuditService.Add(AuditType.Save, -1, homeDocumentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                }

                #endregion
            }
            catch (System.Exception ex)
            {
                logger.Error(typeof(_17_HomeDocumentTypeSlider), ex.Message);
                logger.Error(typeof(_17_HomeDocumentTypeSlider), ex.StackTrace);
            }
        }
Пример #37
0
        public async Task <bool> IsFormatSupportedAsync(string format)
        {
            ResourceFormat resourceFormat = ContentType.GetResourceFormatFromContentType(format);

            return(await IsFormatSupportedAsync(resourceFormat));
        }
Пример #38
0
        public void ProcessRequest(HttpContext context)
        {
            var section = AdxstudioCrmConfigurationManager.GetCrmSection();
            var config  = section.CacheFeed;

            if (!config.Enabled)
            {
                throw new HttpException("Feed isn't enabled.");
            }

            if (config.LocalOnly && !IsLocal(context.Request))
            {
                throw new HttpException("Feed is local only.");
            }

            // Get the output content type, let the querystring override web.config value. Default value is JSON.
            ContentType outputType = ContentType.Json;
            bool        queryStringOverrideContentType = false;

            if (!string.IsNullOrEmpty(context.Request[QueryKeys.ContentType]))
            {
                if (context.Request[QueryKeys.ContentType].ToLower().Contains("xml"))
                {
                    queryStringOverrideContentType = true;
                    outputType = ContentType.Xml;
                }
                else if (context.Request[QueryKeys.ContentType].ToLower().Contains("json"))
                {
                    // Keep output type as JSON
                    queryStringOverrideContentType = true;
                }
            }
            if (!queryStringOverrideContentType && !string.IsNullOrEmpty(config.ContentType) && config.ContentType.ToLower().Contains("xml"))
            {
                // web.config override to XML
                outputType = ContentType.Xml;
            }

            switch (outputType)
            {
            case ContentType.Xml:
                context.Response.ContentType = "text/xml";
                break;

            case ContentType.Json:
            default:
                context.Response.ContentType = "text/json";
                break;
            }

            context.Trace.IsEnabled = config.Traced;
            var showValues = config.ShowValues;

            bool showAll;

            bool.TryParse(context.Request["showAll"], out showAll);

            bool expanded;

            bool.TryParse(context.Request[QueryKeys.Expanded], out expanded);

            var regionName = context.Request["regionName"];

            bool cacheFootprint;

            bool.TryParse(context.Request[QueryKeys.CacheFootprint], out cacheFootprint);

            var url           = context.Request.Url;
            var alternateLink = new Uri(url.GetLeftPart(UriPartial.Path));

            bool clear;
            var  key    = context.Request["key"];
            var  remove = context.Request["remove"];

            var objectCacheName = context.Request["objectCacheName"] ?? config.ObjectCacheName;

            if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(objectCacheName))
            {
                var cache = GetCache(objectCacheName);

                if (cache != null)
                {
                    switch (outputType)
                    {
                    case ContentType.Xml:
                        var feed = cache.GetFeed(key, null, null, alternateLink, alternateLink, showAll, regionName, showValues);
                        Render(feed, context.Response.OutputStream, config.Stylesheet);
                        break;

                    case ContentType.Json:
                    default:
                        var json = cache.GetJson(key, null, null, alternateLink, alternateLink, showAll, regionName, showValues);
                        Render(json, context.Response.OutputStream);
                        break;
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(remove) && !string.IsNullOrWhiteSpace(objectCacheName))
            {
                var cache = GetCache(objectCacheName);

                if (cache != null)
                {
                    Remove(cache, remove, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
                }
            }
            else if (bool.TryParse(context.Request["clear"], out clear))
            {
                if (string.IsNullOrWhiteSpace(objectCacheName))
                {
                    var caches = GetCaches(objectCacheName);
                    foreach (var cache in caches)
                    {
                        Clear(cache, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
                    }
                }
                else
                {
                    var cache = GetCache(objectCacheName);

                    if (cache != null)
                    {
                        Clear(cache, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
                    }
                }
            }
            else if (cacheFootprint)
            {
                var caches = GetCaches(objectCacheName);
                RenderCacheFootprint(caches, context, outputType, expanded);
            }
            else
            {
                var caches = GetCaches(objectCacheName);
                RenderList(caches, alternateLink, showAll, regionName, context.Response.OutputStream, outputType, showValues && expanded, config.Stylesheet);
            }
        }
Пример #39
0
        private static void Remove(ObjectCache cache, string key, Uri alternateLink, bool showAll, string regionName, Stream output, ContentType outputType, bool expanded, string stylesheet)
        {
            cache.Remove(key, regionName);

            RenderList(cache, alternateLink, showAll, regionName, output, outputType, expanded, stylesheet);
        }
Пример #40
0
        private static void RenderList(ObjectCache cache, Uri alternateLink, bool showAll, string regionName, Stream output, ContentType outputType, bool expanded, string stylesheet)
        {
            switch (outputType)
            {
            case ContentType.Xml:
                var feed = cache.GetFeed(null, null, alternateLink, alternateLink, showAll, regionName, expanded);
                Render(feed, output, stylesheet);
                break;

            case ContentType.Json:
            default:
                var json = cache.GetJson(null, null, alternateLink, alternateLink, showAll, regionName, expanded);
                Render(json, output);
                break;
            }
        }
Пример #41
0
 public QueryApiStreamLastCalledDate(ContentType contentType, string subverse) : base(new CachePolicy(_timeSpan))
 {
     _contentType = contentType;
     _subverse    = subverse;
 }
Пример #42
0
 public WebRequestHelper(RequestMethod method, ContentType postContentType)
 {
     Method          = method;
     PostContentType = postContentType;
 }
Пример #43
0
 public Task UpdateContentType(ContentType contentType)
 {
     _liteRepository.Update(contentType);
     return(Task.CompletedTask);
 }
Пример #44
0
 /// <summary>
 /// 构造函数 编码默认为Utf-8
 /// </summary>
 /// <param name="url">请求地址</param>
 /// <param name="type">请求内容类型</param>
 public HttpRequest(string url, ContentType type) : this(url, type, Encoding.UTF8, Encoding.UTF8)
 {
 }
Пример #45
0
        /// <summary>
        /// </summary>
        /// <param name="contentType"> </param>
        /// <returns> </returns>
        public virtual ContentCollection <T> GetView(ContentType contentType)
        {
            return(null);

            // TODO move to base class, infer type of T to get correct collection back.
        }
Пример #46
0
 public Task <string> AddContentType(ContentType contentType)
 {
     contentType.Id = ObjectId.NewObjectId().ToString();
     _liteRepository.Insert(contentType);
     return(Task.FromResult(contentType.Id));
 }
Пример #47
0
 /// <summary>
 /// 返回一个自定义类型的内容
 /// </summary>
 /// <param name="type"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 protected virtual Result GetResultContent(ContentType type, object data)
 {
     return(new Result(type, data));
 }
Пример #48
0
        static void AssertParse(string text, ContentType expected, bool result = true, int tokenIndex = -1, int errorIndex = -1)
        {
            var         buffer  = Encoding.UTF8.GetBytes(text);
            var         options = ParserOptions.Default;
            ContentType type;

            Assert.AreEqual(result, ContentType.TryParse(text, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(options, text, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(buffer, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(options, buffer, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(buffer, 0, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(options, buffer, 0, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(buffer, 0, buffer.Length, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            Assert.AreEqual(result, ContentType.TryParse(options, buffer, 0, buffer.Length, out type), "Unexpected result for TryParse: {0}", text);
            AssertParseResults(type, expected);

            try {
                type = ContentType.Parse(text);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(options, text);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(buffer);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(options, buffer);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(buffer, 0);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(options, buffer, 0);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(buffer, 0, buffer.Length);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }

            try {
                type = ContentType.Parse(options, buffer, 0, buffer.Length);
                if (tokenIndex != -1 && errorIndex != -1)
                {
                    Assert.Fail("Parsing \"{0}\" should have failed.", text);
                }
                AssertParseResults(type, expected);
            } catch (ParseException ex) {
                Assert.AreEqual(tokenIndex, ex.TokenIndex, "Unexpected token index");
                Assert.AreEqual(errorIndex, ex.ErrorIndex, "Unexpected error index");
            } catch (Exception e) {
                Assert.Fail("Unexpected exception: {0}", e);
            }
        }
Пример #49
0
        public async Task Run()
        {
            var toAddresses = new List <MailboxAddress>();

            toAddresses.Add(new MailboxAddress("Recipient Name", "*****@*****.**"));

            var from = new List <MailboxAddress>();

            from.Add(new MailboxAddress("From Name", "*****@*****.**"));


            // Begin Attachments code
            var path            = @"C:\Users\king\Pictures\Golf Courses\golfcourse.jpg";
            var mimeType        = MimeTypes.GetMimeType(path);
            var contentType     = ContentType.Parse(mimeType);
            var imageAttachment = new MimePart(contentType)
            {
                Content                 = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(path)
            };

            var pdfPath = @"C:\Users\king\Documents\some.pdf";

            mimeType    = MimeTypes.GetMimeType(pdfPath);
            contentType = ContentType.Parse(mimeType);
            var pdfAttachment = new MimePart(contentType)
            {
                Content                 = new MimeContent(File.OpenRead(pdfPath), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(pdfPath)
            };

            List <MimeEntity> attachments = null;

            attachments = new List <MimeEntity>();
            attachments.Add(imageAttachment);
            attachments.Add(pdfAttachment);

            List <LinkedResource> linkedResources = null;

            linkedResources = new List <LinkedResource>();
            linkedResources.Add(new LinkedResource {
                Name = "logoCid", Cid = "techwizLogo", Path = @"C:\Users\king\source\repos\KahanuMailer\ConsoleApp1\Views\RegistrationMailer\techwiz-logo.png"
            });
            linkedResources.Add(new LinkedResource {
                Name = "parakeetCid", Cid = "parakeet", Path = @"C:\Users\king\source\repos\KahanuMailer\ConsoleApp1\Views\RegistrationMailer\parakeet.png"
            });

            var context = new RegistrationMailerContext
            {
                Now             = DateTime.Now.ToString(),
                FirstName       = "John",
                LastName        = "Doh",
                CustomerMessage = @"<p>Thank you for being a loyal customer.</p>
                    <p>Your next visit will get 20% off your purchase.</p>",
                Subject         = "Test from TechWiz",
                ToAddresses     = toAddresses,
                From            = from
            };

            if (linkedResources != null)
            {
                context.LinkedResources = linkedResources;
            }

            if (attachments != null)
            {
                context.AttachmentCollection = attachments;
            }

            try
            {
                await mailer.Customer(context).SendAsync().ConfigureAwait(false);

                Console.WriteLine("Sent email successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error sending email: {0}", ex.Message);
            }
            Console.ReadLine();
        }
Пример #50
0
 protected virtual Task GetResult(ContentType type, object data)
 {
     return(new Result(type, data).WriteAsync(this.context));
 }
Пример #51
0
        public bool CheckContent(string path, ContentType expectedType)
        {
            AvailableCheckResult result = contentManager.CheckAvailabe(path, expectedType);

            return(checkSourceResult(result, path, expectedType.ToString(), checkLocation));
        }
Пример #52
0
 public bool CheckContent(string path, ContentType expectedType, Location location)
 {
     checkLocation = location;
     return(CheckContent(path, expectedType));
 }
Пример #53
0
        public override void SetDefaultValues(ContentType contentType)
        {
            base.SetDefaultValues(contentType);

            this.Name = LocalizationService.Current.GetString("/contentrepositories/taxonomy/name");
        }
Пример #54
0
 public void AddAttachment(Stream contentStream, ContentType contentType)
 {
     EnsureNotDisposed();
     _attachments.Add(new Attachment(contentStream, contentType));
 }
Пример #55
0
        private async Task <IHttpResponse <T> > PerformRequestAsync <T>(HttpMethod method, string url, object query, ContentType type = ContentType.Negotiated, object data = null) where T : class
        {
            var fullUrl = _urlBuilder.Build(url, query);

            var request = _requestWrapper
                          .WithUrl(fullUrl)
                          .WithMethod(method)
                          .WithPayload(data, type)
                          .Prepare();

            var response = await request.PerformAsync();

            return(await _responseTransformer.TransformAsync <T>(response));
        }
Пример #56
0
        internal bool Read(Stream stream, IPEndPoint endPoint)
        {
            byte[]             buffer = new byte[1024];
            RequestParserState state  = RequestParserState.ReadMethod;
            string             key    = "";
            string             value  = "";
            MemoryStream       ms     = null;

            DateTime begin            = DateTime.Now;
            DateTime lastByteReceived = begin;

            if (endPoint != null)
            {
                UserHostAddress = endPoint.Address.ToString();
            }

            while (true)
            {
                if (state == RequestParserState.ReadDone)
                {
                    return(true);
                }

                int bytesRead = 0;
                int idx       = 0;

#if (MF)
                // set all bytes to null byte (strings are ending with null byte in MF)
                Array.Clear(buffer, 0, buffer.Length);
#endif

                try
                {
                    bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead > 0)
                    {
                        lastByteReceived = DateTime.Now;
                    }
                }
                catch (IOException)
                {
                    break;
                }
                catch (Exception)
                {
                    DateTime nd = DateTime.Now;
#if (MF)
                    if ((nd.Ticks - lastByteReceived.Ticks) / TimeSpan.TicksPerMillisecond > MAX_REQUEST_SLIDING_TIMEOUT)
                    {
                        break;
                    }
#else
                    //   if ((nd - lastByteReceived).TotalMilliseconds > MAX_REQUEST_SLIDING_TIMEOUT)
                    //       break;
#endif

                    if (HttpMethod == "POST" && (_body == null || _body.Length < ContentLength))
                    {
                        continue;
                    }

#if (MF)
                    if ((nd.Ticks - begin.Ticks) / TimeSpan.TicksPerMillisecond < MAX_REQUEST_TIMEOUT)
                    {
                        continue;
                    }
#else
                    // if ((nd - begin).TotalMilliseconds < MAX_REQUEST_TIMEOUT)
                    //     continue;
#endif

                    break;
                }

                if (bytesRead == 0)     // should never happen
                {
                    break;
                }

                totalBytes += bytesRead;

#if (FILELOG && !MF && !WindowsCE)
                File.AppendAllText("loghttp-" + socket.RemoteEndPoint.ToString().Replace(":", "-") + ".txt", Encoding.UTF8.GetString(buffer, 0, bytesRead) + "\r\n");
#endif

                if (totalBytes <= idx)
                {
                    continue;
                }

                do
                {
                    switch (state)
                    {
                    case RequestParserState.ReadMethod:
                        if (buffer[idx] != ' ')
                        {
                            HttpMethod += (char)buffer[idx++];
                        }
                        else
                        {
                            // TODO: add a allowed methods list

                            //if (HttpMethod != "POST" && HttpMethod != "GET" && HttpMethod != "OPTIONS")
                            //    throw new HttpException(HttpStatusCode.MethodNotAllowed);

                            idx++;
                            state = RequestParserState.ReadUrl;
                        }
                        break;

                    case RequestParserState.ReadUrl:
                        if (buffer[idx] == '?')
                        {
                            idx++;
                            key     = "";
                            _params = new MFToolkit.Collection.Spezialized.NameValueCollection();
                            state   = RequestParserState.ReadParamKey;
                        }
                        else if (buffer[idx] != ' ')
                        {
                            RawUrl += (char)buffer[idx++];
                        }
                        else
                        {
                            idx++;
                            RawUrl = HttpServerUtility.UrlDecode(RawUrl);
                            state  = RequestParserState.ReadVersion;
                        }
                        break;

                    case RequestParserState.ReadParamKey:
                        if (buffer[idx] == '=')
                        {
                            idx++;
                            value = "";
                            state = RequestParserState.ReadParamValue;
                        }
                        else if (buffer[idx] == ' ')
                        {
                            idx++;
                            RawUrl = HttpServerUtility.UrlDecode(RawUrl);
                            state  = RequestParserState.ReadVersion;
                        }
                        else
                        {
                            key += (char)buffer[idx++];
                        }
                        break;

                    case RequestParserState.ReadParamValue:
                        if (buffer[idx] == '&')
                        {
                            idx++;
                            key   = HttpServerUtility.UrlDecode(key);
                            value = HttpServerUtility.UrlDecode(value);

                            Params[key] = (Params[key] != null ? Params[key] + ", " + value : value);

                            key   = "";
                            value = "";

                            state = RequestParserState.ReadParamKey;
                        }
                        else if (buffer[idx] == ' ')
                        {
                            idx++;
                            key   = HttpServerUtility.UrlDecode(key);
                            value = HttpServerUtility.UrlDecode(value);

                            Params[key] = (Params[key] != null ? Params[key] + ", " + value : value);

                            RawUrl = HttpServerUtility.UrlDecode(RawUrl);

                            state = RequestParserState.ReadVersion;
                        }
                        else
                        {
                            value += (char)buffer[idx++];
                        }
                        break;

                    case RequestParserState.ReadVersion:
                        if (buffer[idx] == '\r')
                        {
                            idx++;
                        }
                        else if (buffer[idx] != '\n')
                        {
                            HttpVersion += (char)buffer[idx++];
                        }
                        else
                        {
                            if (HttpVersion != "HTTP/1.1" && HttpVersion != "HTTP/1.0")
                            {
                                throw new HttpException(HttpStatusCode.HttpVersionNotSupported);
                            }

                            idx++;
                            key     = "";
                            Headers = new MFToolkit.Collection.Spezialized.NameValueCollection();
                            state   = RequestParserState.ReadHeaderKey;
                        }
                        break;

                    case RequestParserState.ReadHeaderKey:
                        if (buffer[idx] == '\r')
                        {
                            idx++;
                        }
                        else if (buffer[idx] == '\n')
                        {
                            idx++;
                            if (HttpMethod == "POST")
                            {
                                state = RequestParserState.ReadBody;
                            }
                            else
                            {
                                state = RequestParserState.ReadDone;        // well, we don't really need this
                                return(true);
                            }
                        }
                        else if (buffer[idx] == ':')
                        {
                            idx++;
                        }
                        else if (buffer[idx] != ' ')
                        {
                            key += (char)buffer[idx++];
                        }
                        else
                        {
                            idx++;
                            value = "";
                            state = RequestParserState.ReadHeaderValue;
                        }
                        break;

                    case RequestParserState.ReadHeaderValue:
                        if (buffer[idx] == '\r')
                        {
                            idx++;
                        }
                        else if (buffer[idx] != '\n')
                        {
                            value += (char)buffer[idx++];
                        }
                        else
                        {
                            idx++;
                            Headers.Add(key, value);
                            key   = "";
                            state = RequestParserState.ReadHeaderKey;
                        }
                        break;

                    case RequestParserState.ReadBody:

                        if (ContentLength > MAX_CONTENT_LENGTH)
                        {
                            // TODO: how can I stop the client to cancel http request
                            //throw new HttpException(HttpStatusCode.RequestEntitiyTooLarge);
                        }

                        if (ms == null)
                        {
                            ms = new MemoryStream();
                        }

                        ms.Write(buffer, idx, bytesRead - idx);
                        idx = bytesRead;

                        if (ms.Length >= ContentLength)
                        {
                            _body = ms.ToArray();

                            // if using a <form/> tag with POST check if it is urlencoded or multipart boundary

                            if (ContentType.IndexOf("application/x-www-form-urlencoded") != -1)
                            {
                                _form = new MFToolkit.Collection.Spezialized.NameValueCollection();
                                key   = "";
                                value = null;

                                for (int i = 0; i < _body.Length; i++)
                                {
                                    if (_body[i] == '=')
                                    {
                                        value = "";
                                    }
                                    else if (_body[i] == '&')
                                    {
                                        _form.Add(key, value != null ? HttpServerUtility.UrlDecode(value) : "");
                                        key   = "";
                                        value = null;
                                    }
                                    else if (value == null)
                                    {
                                        key += (char)_body[i];
                                    }
                                    else if (value != null)
                                    {
                                        value += (char)_body[i];
                                    }
                                }

                                if (key != null && key.Length > 0)
                                {
                                    _form.Add(key, value != null ? HttpServerUtility.UrlDecode(value) : "");
                                }
                            }
                            else if (ContentType != null && ContentType.Length > "multipart/form-data; boundary=".Length && ContentType.Substring(0, "multipart/form-data; boundary=".Length) == "multipart/form-data; boundary=")
                            {
                                string boundary = ContentType.Substring("multipart/form-data; boundary=".Length);

                                _mime = new MimeContentCollection();

                                MimeParser mp = new MimeParser(_body, boundary);

                                MimeContent mime = mp.GetNextContent();
                                while (mime != null)
                                {
                                    _mime.Add(mime.Name, mime);

                                    if (mime.Headers["Content-Disposition"] != null && mime.Headers["Content-Disposition"].IndexOf("form-data") >= 0)
                                    {
                                        if (_form == null)
                                        {
                                            _form = new MFToolkit.Collection.Spezialized.NameValueCollection();
                                        }

                                        _form.Add(mime.Name, (mime.Content != null && mime.Content.Length > 0 ? new string(Encoding.UTF8.GetChars(mime.Content)) : ""));
                                    }

                                    mime = mp.GetNextContent();
                                }
                            }
                            state = RequestParserState.ReadDone;            // well, we don't really need this
                            return(true);
                        }
                        break;

                    case RequestParserState.ReadDone:                       // well, we don't really need this
                        return(true);

                    default:
                        //idx++;
                        break;
                    }
                }while (idx < bytesRead);
            }

            return(false);
        }
Пример #57
0
 public LinkedResource(Stream contentStream, ContentType contentType)
 {
     throw new NotImplementedException();
 }
Пример #58
0
 public static LinkedResource CreateLinkedResourceFromString(string content, ContentType contentType)
 {
     throw new NotImplementedException();
 }
Пример #59
0
 public LinkedResource(string fileName, ContentType contentType)
 {
     throw new NotImplementedException();
 }
Пример #60
0
        public async Task <IHttpResponse <T> > DeleteAsync <T>(string url, object data = null, object query = null, ContentType type = ContentType.Negotiated) where T : class
        {
            var response = await PerformRequestAsync <T>(HttpMethod.Delete, url, query, type, data);

            return(response);
        }