Example #1
0
 public FixFileDetail(ContentTypeEnum contentTypeEnum, HitTypeEnum hitType, bool deleted, bool renamed, string path, long size) : base(path, size)
 {
     ContentType = contentTypeEnum;
     HitType     = hitType;
     Deleted     = deleted;
     Renamed     = renamed;
 }
Example #2
0
 public TlsRecord(ContentTypeEnum ContentType, Byte MajorVersion, Byte MinorVersion, ISerializer Content)
 {
     this.ContentType  = ContentType;
     this.MajorVersion = MajorVersion;
     this.MinorVersion = MinorVersion;
     this.Content      = Content;
 }
Example #3
0
        /// <summary>
        /// Строит базовый запрос с токеном авторизации и параметрами страниц
        /// </summary>
        /// <param name="action"></param>
        /// <param name="itemsPerPage"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        private RestRequest BuildRequest(string action, ContentTypeEnum type, int itemsPerPage, int page)
        {
            var request = new RestRequest("/v1/items/" + action,
                                          Method.GET);

            request.AddHeader("Authorization",
                              AccessToken);

            // @todo Сделать какой-то более красивый враппер для этого распределения
            string chosenType = null; //Пусть будет пока выбор по умолчанию такой

            switch (type)
            {
            case ContentTypeEnum.Movie:
                chosenType = "movie";
                break;

            case ContentTypeEnum.TvShow:
                chosenType = "tvshow";
                break;
            }
            if (!String.IsNullOrEmpty(chosenType))
            {
                request.AddParameter("type", chosenType);
            }

            request.AddParameter("perpage", itemsPerPage);
            request.AddParameter("page", page);
            return(request);
        }
Example #4
0
        public static string GetContentType(ContentTypeEnum contentType)
        {
            switch (contentType)
            {
            case ContentTypeEnum.Movie:
                return(Movie);

            case ContentTypeEnum.TvShow:
                return(TvShow);

            case ContentTypeEnum.Movie3d:
                return(Movie3d);

            case ContentTypeEnum.Concert:
                return(Concert);

            case ContentTypeEnum.MovieDocumental:
                return(MovieDocumental);

            case ContentTypeEnum.TvShowDocumental:
                return(TvShowDocumental);

            default: return(null);
            }
        }
 public CMPHttpConnection ByteArrayBody(byte[] byteBodyArray)
 {
     _byteBodyArray = new byte[byteBodyArray.Length];
     ContentType    = ContentTypeEnum.eByteArray;
     Array.Copy(byteBodyArray, _byteBodyArray, byteBodyArray.Length);
     return(this);
 }
Example #6
0
        protected string InvokeService <T>(IRequest <T> request, string fullUrl, ContentTypeEnum type, IServiceEncryptor encryptor = null) where T : BaseResponse
        {
            object req      = request;
            var    response = InvokeService(req, fullUrl, type, encryptor);

            return(response);
        }
Example #7
0
        public bool AssessContentType(ContentTypeEnum assessedContentType)
        {
            bool            contentTypeSet    = false;
            ContentTypeEnum actualContentType = ContentTypeEnum.NotResolved;

            string contentType = ExtractInboundHttpHeader("Content-Type");

            if (!string.IsNullOrEmpty(contentType))
            {
                ChooseContentType(ref actualContentType, contentType);
                contentTypeSet = true;
                TraceManager.PipelineComponent.TraceInfo("{0} - Used Content-Type HTTP header to determine that the request content type is {1}", CallToken, actualContentType.ToString());
            }

            if (!contentTypeSet)
            {
                ReflectContentTypeBasedOnMessageContent(ref contentTypeSet, ref actualContentType);
            }

            if (!contentTypeSet)
            {
                TraceManager.PipelineComponent.TraceWarning("{0} - Could not determine the request content type, as Content-Type header was either blank or not provided, and request body appeared to be neither XML nor JSON", CallToken);
            }

            return(assessedContentType == actualContentType);
        }
Example #8
0
 private void DetectContentType(ref ContentTypeEnum contentType, byte[] BinaryData)
 {
     try
     {
         using (MemoryStream imgStream = new MemoryStream(BinaryData))
         {
             using (Bitmap bitmap = new Bitmap(imgStream))
             {
                 if (bitmap.RawFormat.Equals(ImageFormat.Jpeg))
                 {
                     contentType = ContentTypeEnum.ContentTypeJpeg;
                 }
                 else if (bitmap.RawFormat.Equals(ImageFormat.Png))
                 {
                     contentType = ContentTypeEnum.ContentTypePng;
                 }
                 else if (bitmap.RawFormat.Equals(ImageFormat.Gif))
                 {
                     contentType = ContentTypeEnum.ContentTypeGif;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("Error during image type detection: {0}", ex.Message));
     }
 }
Example #9
0
        /// <summary>
        /// Post 等待回傳
        /// </summary>
        /// <param name="ApiUrl"></param>
        /// <param name="param"></param>
        /// <param name="ContentType"></param>
        /// <returns></returns>
        public static T Post <T>(string ApiUrl, string param = null, ContentTypeEnum ContentType = ContentTypeEnum.json)
        {
            try
            {
                HttpClient ClientF     = new HttpClient();
                var        httpContent = new StringContent(param, Encoding.UTF8);

                switch (ContentType)
                {
                case ContentTypeEnum.urlencoded:
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    break;

                case ContentTypeEnum.json:
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    break;
                }

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                using (HttpResponseMessage responseMessage = ClientF.PostAsync(ApiUrl, httpContent).GetAwaiter().GetResult())
                {
                    return(JsonSerializer.Deserialize <T>(responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(default(T));
        }
        private T ExecuteDelete <T>(
            string url,
            string parameters,
            ContentTypeEnum contentType = ContentTypeEnum.ApplicationJson,
            Credentials credentials     = null,
            int?timeoutInMilliseconds   = null)
        {
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                SetAuthorization(httpClient, credentials);

                SetTimeout(httpClient, timeoutInMilliseconds);

                var mediaType = GetMediaType(contentType);

                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri(url),
                    Method     = HttpMethod.Delete,
                    Content    = new StringContent(parameters, Encoding.UTF8, mediaType),
                };

                var response = httpClient.SendAsync(request).RunSync();

                return(response.Content.ReadAsAsync <T>().RunSync());
            }
        }
Example #11
0
        /// <summary>
        /// Получает новые видео выбранного типа
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="itemsPerPage"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task <SearchEntity> GetNewItems
            (ContentTypeEnum contentType, int itemsPerPage, int page)
        {
            var request      = BuildRequest("new", contentType, itemsPerPage, page);
            var restResponse = await GetRestClient().ExecuteTaskAsync <SearchEntity>(request);

            return(restResponse.Data);
        }
 public Homework(string content, ContentTypeEnum contentType, DateTime submissionDate, Course course, Student student)
 {
     this.HomeWorkContent = content;
     this.ContentType     = contentType;
     this.SubmissionDate  = submissionDate;
     this.Course          = course;
     this.Student         = student;
 }
        /// <summary>
        /// Facilitates the discovery of core account configuration information by using the user's Simple Mail Transfer Protocol (SMTP) address as the primary input
        /// </summary>
        /// <param name="request">An AutodiscoverRequest object that contains the request information.</param>
        /// <param name="contentType">Content Type that indicates the body's format</param>
        /// <returns>Autodiscover command response</returns>
        public AutodiscoverResponse Autodiscover(AutodiscoverRequest request, ContentTypeEnum contentType)
        {
            AutodiscoverResponse response = this.activeSyncClient.Autodiscover(request, contentType);

            this.VerifyTransportRequirements();
            this.VerifyWBXMLCapture(CommandName.Autodiscover, response);
            this.VerifyAutodiscoverCommand(response);
            return(response);
        }
Example #14
0
            //public HttpWebGetter ContentType(string contentType)
            //{
            //    _contentType = contentType;
            //    _hasChangeContentType = true;
            //    return this;
            //}

            /// <summary>
            /// 提交数据的内容类型
            /// </summary>
            /// <param name="type"></param>
            /// <returns></returns>
            public HttpWebGetter ContentType(ContentTypeEnum type)
            {
                //_contentType = getContentType(type);
                _contentType = type;
                //ContentType(getContentType(type));

                _hasChangeContentType = true;

                return(this);
            }
Example #15
0
        /// <summary>
        /// post
        /// </summary>
        /// <param name="ApiUrl">API接口</param>
        /// <param name="param">傳遞參數</param>
        /// <param name="ContentType">ContentType類型</param>
        /// <param name="HeaderList">Header資訊</param>
        /// <param name="Timeout">設定逾時秒數</param>
        /// <returns>回傳結果</returns>
        public static string Post(string ApiUrl, ContentTypeEnum ContentType, string param = null, List <PostHeader> HeaderList = null, string Timeout = null)
        {
            string result = string.Empty;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiUrl);
                request.Method = "POST";
                switch (ContentType)
                {
                case ContentTypeEnum.urlencoded:
                    request.ContentType = "application/x-www-form-urlencoded";
                    break;

                case ContentTypeEnum.json:
                    request.ContentType = "application/json";
                    break;
                }
                if (HeaderList != null && HeaderList.Count > 0)
                {
                    foreach (PostHeader data in HeaderList)
                    {
                        request.Headers[data.HeaderKey] = data.HeaderContent;
                    }
                }

                if (!string.IsNullOrEmpty(Timeout))
                {
                    int timeoutvalue;
                    if (int.TryParse(Timeout, out timeoutvalue))
                    {
                        request.Timeout = timeoutvalue * 1000;
                    }
                }
                byte[] byteArray = Encoding.UTF8.GetBytes(param);
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);
                }
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(result);
        }
Example #16
0
        internal void Load(XElement binarye)
        {
            if (binarye == null)
            {
                throw new ArgumentNullException("binarye");
            }

            if (binarye.Name.LocalName != Fb2BinaryItemName)
            {
                throw new ArgumentException("Element of wrong type passed", "binarye");
            }

            XAttribute xContentType = binarye.Attribute(ContentTypeAttributeName);

            if ((xContentType == null) || (xContentType.Value == null))
            {
                throw new NullReferenceException("content type not defined/present");
            }
            switch (xContentType.Value.ToLower())
            {
            case "image/jpeg":
            case "image/jpg":
                ContentType = ContentTypeEnum.ContentTypeJpeg;
                break;

            case "image/png":
                ContentType = ContentTypeEnum.ContentTypePng;
                break;

            case "image/gif":
                ContentType = ContentTypeEnum.ContentTypeGif;
                break;

            default:
                throw new Exception("Unknown image content type passed");
            }

            XAttribute idAttribute = binarye.Attribute(IdAttributeName);

            if ((idAttribute == null) || (idAttribute.Value == null))
            {
                throw new NullReferenceException("ID not defined/present");
            }
            Id = idAttribute.Value;

            if (BinaryData != null)
            {
                BinaryData = null;
            }
            BinaryData = Convert.FromBase64String(binarye.Value);
            ContentTypeEnum content = ContentType;

            DetectContentType(ref content, BinaryData);
            ContentType = content;
        }
Example #17
0
        /// <summary>
        /// Получает горячие видео выбранного типа
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="itemsPerPage"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task <SearchEntity> GetHotItems
            (ContentTypeEnum contentType, int itemsPerPage, int page)
        {
            var request      = BuildRequest("hot", contentType, itemsPerPage, page);
            var restResponse = await GetRestClient().ExecuteTaskAsync <SearchEntity>(request);

            // @todo Сделать нормальный таймаут и обработчик ошибок
            //@body При некорректном запросе здесь приложение просто вешается. Так быть не должно.
            //Нужно корректная обработка ошибок с выводом тех, которые могут быть важны пользователю, на экран.
            return(restResponse.Data);
        }
Example #18
0
        public int Load(byte[] buffer, long offset)
        {
            long value;

            BufferTools.ReadNumberFromBuffer(buffer, offset, num_bytes, out value);
            if (Enum.IsDefined(typeof(ContentTypeEnum), value))
            {
                this.value = (ContentTypeEnum)value;
            }
            return(num_bytes);
        }
Example #19
0
        public static Post CreateInstance(Guid?id, string title, short order, ContentTypeEnum postType, string content, Guid lessonplanId, bool isActive, string description)
        {
            var post = CreateInstance(id, isActive, description);

            post.AssignTitle(title);
            post.AssignOrder(order);
            post.AssignPostType(postType);
            post.AssignContent(content);
            post.AssignLessonPlan(lessonplanId);

            return(post);
        }
Example #20
0
 public RequestJob(string objectName,
                   OperationEnum operation,
                   string externalIdFieldName          = null,
                   ColumnDelimiterEnum columnDelimiter = ColumnDelimiterEnum.COMMA,
                   ContentTypeEnum contentType         = ContentTypeEnum.CSV,
                   LineEndingEnum lineEnding           = LineEndingEnum.CRLF,
                   int maxLinesFileCSV  = 10000,
                   string directoryWork = ""
                   )
 {
     Init(objectName, externalIdFieldName, operation, columnDelimiter, contentType, lineEnding, maxLinesFileCSV, directoryWork);
 }
        public CMPHttpConnection JsonDocumentBody(string documentBodyString)
        {
            if ((string.IsNullOrEmpty(documentBodyString) == true) ||
                (string.IsNullOrEmpty(documentBodyString) == true))
            {
                return(this);
            }

            ContentType         = ContentTypeEnum.eApplicationDocumentJson;
            _documentBodyString = string.Copy(documentBodyString);
            return(this);
        }
        public static IPostDataFormatter Create(ContentTypeEnum type)
        {
            switch (type)
            {
            case ContentTypeEnum.Xml:
                return(new XMLPostDataFomatter());

            case ContentTypeEnum.UrlEncoded:
                return(new FormPostDataFormatter());

            default:
                return(new JsonPostDataFormatter());
            }
        }
Example #23
0
        /// <summary>
        /// post
        /// </summary>
        /// <param name="ApiUrl">API接口</param>
        /// <param name="param">傳遞參數</param>
        /// <param name="ContentType">ContentType類型</param>
        /// <param name="HeaderList">Header資訊</param>
        /// <returns>回傳結果</returns>
        public static JObject PATCH(string ApiUrl, ContentTypeEnum ContentType, string param = null, List <PostHeader> HeaderList = null)
        {
            JObject result = new JObject();

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiUrl);
                request.Method = "PATCH";
                switch (ContentType)
                {
                case ContentTypeEnum.urlencoded:
                    request.ContentType = "application/x-www-form-urlencoded";
                    break;

                case ContentTypeEnum.json:
                    request.ContentType = "application/json";
                    break;
                }
                if (HeaderList != null && HeaderList.Count > 0)
                {
                    foreach (PostHeader data in HeaderList)
                    {
                        request.Headers[data.HeaderKey] = data.HeaderContent;
                    }
                }

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                if (param != null)
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(param);
                    using (Stream reqStream = request.GetRequestStream())
                    {
                        reqStream.Write(byteArray, 0, byteArray.Length);
                    }
                }
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        result = JObject.Parse(sr.ReadToEnd());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(result);
        }
Example #24
0
        public static ISerializable Create(ContentTypeEnum dataType = ContentTypeEnum.Json)
        {
            switch (dataType)
            {
            case ContentTypeEnum.Json:
                return(new JsonSerializor());

            case ContentTypeEnum.Xml:
                return(new XmlSerializor());

            case ContentTypeEnum.UrlEncoded:
                return(new UrlSerializor());

            default:
                return(null);
            }
        }
        private async Task <T> ExecutePutAsync <T>(string url, string parameters, ContentTypeEnum contentType,
                                                   Credentials credentials, int?timeoutInMilliseconds = null) where T : class
        {
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                SetAuthorization(httpClient, credentials);

                SetTimeout(httpClient, timeoutInMilliseconds);

                var mediaType = GetMediaType(contentType);

                var content = new StringContent(parameters, Encoding.UTF8, mediaType);

                var responseMessage = await httpClient.PutAsync(url, content);

                return(await ProcessResponseMessageAsync <T>(responseMessage, url, parameters, contentType));
            }
        }
Example #26
0
 /// <summary>
 /// Set up simple message
 /// messageType = eviivo
 /// contentType = plain text
 /// Status = unread
 /// text = "Test text"
 /// business id = 1
 /// message id = 1
 /// </summary>
 /// <param name="businessId">business to create message for, default 1</param>
 /// <param name="messageId">id of message, default 1</param>
 /// <param name="messageTypeEnum">message type, default eviivo</param>
 /// <param name="contentTypeEnum">content type, default plain</param>
 /// <param name="messageStatusEnum">message status, default unread</param>
 /// <param name="content">content text, default "Test text"</param>
 /// <returns>a new Message</returns>
 public static Message BuildSimple(long businessId = 1, int messageId = 1,
                                   MessageTypeEnum messageTypeEnum = MessageTypeEnum.EviivoMessage,
                                   ContentTypeEnum contentTypeEnum = ContentTypeEnum.PlainText,
                                   MessageStatusEnum messageStatusEnum = MessageStatusEnum.Unread,
                                   string content = "Test text")
 {
     return new Message
         {
             BusinessId = businessId,
             Id = messageId,
             MessageStatusEnum = messageStatusEnum,
             MessageTypeEnum = messageTypeEnum,
             ContentTypeEnum = contentTypeEnum,
             Content = content,
             CreatedDateTime = DateTime.Now,
             Events = new System.Collections.Generic.List<MessageEvent>()
         };
 }
Example #27
0
        public static ContentTypeEnum ToSerialType(TextType type)
        {
            ContentTypeEnum serailType = ContentTypeEnum.Nothing;

            switch (type)
            {
            case TextType.Json:
                serailType = ContentTypeEnum.Json;
                break;

            case TextType.PlainText:
                break;

            case TextType.Xml:
                serailType = ContentTypeEnum.Xml;
                break;
            }
            return(serailType);
        }
        private CMPHttpConnection MultipartFormDataBody(string contentNameString, HttpContent httpContent,
                                                        string fileNameString = null)
        {
            if ((string.IsNullOrEmpty(contentNameString) == true) || (httpContent == null))
            {
                return(this);
            }

            ContentType = ContentTypeEnum.eMultipartFormData;

            if (_multipartBodyDictionary == null)
            {
                _multipartBodyDictionary = new Dictionary <string, Tuple <HttpContent, string> >();
            }

            _multipartBodyDictionary.Add(contentNameString, new Tuple <HttpContent, string>(httpContent,
                                                                                            fileNameString));
            return(this);
        }
Example #29
0
 private void Init(string objectName,
                   string externalIdFieldName,
                   OperationEnum operation,
                   ColumnDelimiterEnum columnDelimiter,
                   ContentTypeEnum contentType,
                   LineEndingEnum lineEnding,
                   int maxLinesFileCSV,
                   string directoryWork
                   )
 {
     ColumnDelimiter     = columnDelimiter;
     ContentType         = contentType;
     ExternalIdFieldName = externalIdFieldName;
     Operation           = operation;
     LineEnding          = lineEnding;
     Object          = objectName;
     MaxLinesFileCSV = maxLinesFileCSV;
     DirectoryWork   = directoryWork;
 }
Example #30
0
        public Hit(ContentTypeEnum contentTypeEnum, string path, HitTypeEnum type)
        {
            ContentTypeEnum = contentTypeEnum;
            ContentType     = contentTypeEnum.GetDescription();
            Path            = path;
            File            = System.IO.Path.GetFileName(path);
            Size            = type == HitTypeEnum.Missing ? null : new FileInfo(path).Length;
            SizeString      = type == HitTypeEnum.Missing ? null : ByteSize.FromBytes(new FileInfo(path).Length).ToString("#");
            Type            = type;

            // performance tweak - explicitly assign a property instead of relying on ToString during subsequent binding
            Description = ToString();

            // viewmodel
            IsPresent       = Type != HitTypeEnum.Missing;
            OpenFileCommand = new ActionCommand(OpenFile, _ => IsPresent);
            ExplorerCommand = new ActionCommand(ShowInExplorer);
            CopyPathCommand = new ActionCommand(CopyPath);
        }
        private string GetMediaType(ContentTypeEnum contentType)
        {
            switch (contentType)
            {
            case ContentTypeEnum.ApplicationJson:
                return("application/json");

            case ContentTypeEnum.ApplicationXml:
                return("application/xml");

            case ContentTypeEnum.TextJson:
                return("text/json");

            case ContentTypeEnum.TextXml:
                return("text/xml");

            default:
                throw new NotSupportedException($"{contentType} is not supported");
            }
        }
Example #32
0
 public void UpdateParentElementProcessStatus(ContentTypeEnum contentType)
 {
     ElementProcessStatus parentElementProcessStatus = this.elementProcessStatusStack.Peek();
     parentElementProcessStatus.ContentType |= contentType;
 }
		private void FindRemoveTrackChangesState(ContentTypeEnum contentType, IActionProperty removeTrackChangesProperty, bool execute, ref TriState tsWord, ref TriState tsExcel, ref TriState tsPPT, ref TriState tsDefault)
		{
			switch (contentType)
			{
			case ContentTypeEnum.WordDocument:
			case ContentTypeEnum.WordDocumentX:
			case ContentTypeEnum.WordDocumentMacroX:
			case ContentTypeEnum.WordDocumentTemplateX:
			case ContentTypeEnum.WordDocumentMacroTemplateX:
				SetRemoveTrackChangesState(ref tsWord, removeTrackChangesProperty, execute);
				break;
			case ContentTypeEnum.ExcelSheet:
			case ContentTypeEnum.ExcelSheetX:
			case ContentTypeEnum.ExcelSheetMacroX:
			case ContentTypeEnum.ExcelSheetTemplateX:
			case ContentTypeEnum.ExcelSheetMacroTemplateX:
				SetRemoveTrackChangesState(ref tsExcel, removeTrackChangesProperty, execute);
				break;
			case ContentTypeEnum.PowerPoint:
			case ContentTypeEnum.PowerPointX:
			case ContentTypeEnum.PowerPointMacroX:
			case ContentTypeEnum.PowerPointTemplateX:
			case ContentTypeEnum.PowerPointMacroTemplateX:
			case ContentTypeEnum.PowerPointShowX:
			case ContentTypeEnum.PowerPointMacroShowX:
				tsPPT = TriState.False;
				break;
			default:
				SetRemoveTrackChangesState(ref tsDefault, removeTrackChangesProperty, execute);
				break;
			}
		}
Example #34
0
        private void UpdateParentElementProcessStatus(ContentTypeEnum contentType)
        {
            ElementProcessStatus parentElementProcessStatus = _elementProcessStatusStack.Peek();

            parentElementProcessStatus.ContentType |= contentType;
        }
Example #35
0
        private void DetectContentType(out ContentTypeEnum contentType, byte[] binaryData)
        {
            contentType = ContentTypeEnum.ContentTypeUnknown;
            try
            {

                using (MemoryStream imgStream = new MemoryStream(binaryData))
                {
                    using (Bitmap bitmap = new Bitmap(imgStream))
                    {
                        if (bitmap.RawFormat.Equals(ImageFormat.Jpeg))
                        {
                            contentType = ContentTypeEnum.ContentTypeJpeg;
                        }
                        else if (bitmap.RawFormat.Equals(ImageFormat.Png))
                        {
                            contentType = ContentTypeEnum.ContentTypePng;
                        }
                        else if (bitmap.RawFormat.Equals(ImageFormat.Gif))
                        {
                            contentType = ContentTypeEnum.ContentTypeGif;
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                throw new Exception(string.Format("Error during image type detection: {0}",ex),ex);
            }
        }
Example #36
0
 /// <summary>
 ///		Obtiene la descripción de un tipo de contenido
 /// </summary>
 internal static string GetContentType(ContentTypeEnum intContentType)
 {
     switch (intContentType)
         {	case ContentTypeEnum.Base64:
                 return cnstStrContentTypeBase64;
             case ContentTypeEnum.HTML:
                 return cnstStrContentTypeHTML;
             case ContentTypeEnum.MultipartAlternative:
                 return cnstStrContentTypeMultipartAlternative;
             case ContentTypeEnum.MultipartMixed:
                 return cnstStrContentTypeMultipartMixed;
             case ContentTypeEnum.MultipartRelated:
                 return cnstStrContentTypeMultipartRelated;
             case ContentTypeEnum.MultipartReport:
                 return cnstStrContentTypeMultipartReport;
             case ContentTypeEnum.Multipart:
                 return cnstStrContentTypeMultipart;
             case ContentTypeEnum.OctectStream:
                 return cnstStrContentTypeOctectStream;
             case ContentTypeEnum.Text:
                 return cnstStrContentTypeText;
             default:
                 return "";
         }
 }