public ImapSinglePartBodyStructure(string section,
                                       MimeType mediaType,
                                       IDictionary<string, string> parameters,
                                       string id,
                                       string description,
                                       string encoding,
                                       long size,
                                       long lineCount)
        {
            if (section == null)
            throw new ArgumentNullException("section");
              if (mediaType == null)
            throw new ArgumentNullException("mediaType");
              if (size < 0)
            throw new ArgumentOutOfRangeException("size", size, "must be zero or positive number");
              if (lineCount < 0)
            throw new ArgumentOutOfRangeException("lineCount", lineCount, "must be zero or positive number");

              this.Section        = section;
              this.MediaType      = mediaType;
              this.Parameters     = (parameters ?? new Dictionary<string, string>()).AsReadOnly(StringComparer.OrdinalIgnoreCase);
              this.Id             = id;
              this.Description    = description;
              this.Encoding       = encoding;
              this.Size           = size;
              this.LineCount      = lineCount;
        }
示例#2
0
 // Browsers will ask for "text/html" and we will give it to them
 // by loading the contents of the URI in our Html property
 public override string AsMimeType(MimeType type)
 {
     if (type == MimeType.Text_Html) {
         return X.GET<string>(Html);
     }
     return base.AsMimeType(type);
 }
示例#3
0
        public void TestConstructor()
        {
            var mime = new MimeType("text", "plain");

              Assert.AreEqual("text", mime.Type);
              Assert.AreEqual("plain", mime.SubType);
        }
示例#4
0
 public Request()
 {
     this.contentLength = 0;
     this.contentType = MimeType.Default;
     this.cookies = new CookieCollection();
     this.hasEntityBody = false;
     this.headers = new HeaderCollection();
     this.isAuthenticated = false;
     this.isLocal = false;
     this.isSecureConnection = false;
     this.keepAlive = false;
     this.localEndPoint = null;
     this.method = RequestMethod.Unknown;
     this.protocolType = null;
     this.protocolVersion = null;
     this.rawMethod = null;
     this.rawRequest = null;
     this.rawUrl = null;
     this.referrer = null;
     this.remoteEndPoint = null;
     this.requestData = new RequestDataCollection();
     this.url = null;
     this.userAgent = null;
     this.userHostName = null;
 }
示例#5
0
        protected override void BuildResponseFile(string filepath, MimeType mime)
        {
            if (filepath.Contains(imgPrefix))
            {
                string[] rules = filepath.Split(new string[] { img_value_delimeter }, StringSplitOptions.RemoveEmptyEntries);
                int zoomX = int.Parse(rules[1]);
                int zoomY = int.Parse(rules[2]);

                Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width / zoomX, Screen.PrimaryScreen.Bounds.Height / zoomY);
                Graphics graphics = Graphics.FromImage(printscreen as Image);
                graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

                MemoryStream ms = new MemoryStream();

                printscreen.Save(ms, ImageFormat.Jpeg);

                ms.Seek(0, SeekOrigin.Begin);
                byte[] frame = ms.ToArray();
                ms.Close();
                BuildResponse(frame, mime, false);
            }
            else
            {
                base.BuildResponseFile(filepath, mime);
            }
        }
        public override byte[] AsMimeType(MimeType mimeType, out MimeType resultingMimeType, Request request = null) {

            resultingMimeType = mimeType;

            if (mimeType == MimeType.Text_Html) {
                Byte[] byteRepres = Self.GET<Byte[]>(Html);

                // Checking if file not found.
                if (null == byteRepres) {
                    throw new ArgumentOutOfRangeException("Can not find file in Page->Html property: \"" + Html + "\"");
                }

                if (IsFullPageHtml(byteRepres)) {
                    return byteRepres;
                }
                else {
                    if (ImplicitStandalonePageBytes == null) {
                        string html = String.Format(ImplicitStandaloneTemplate, ImplicitStandaloneTitle);
                        ImplicitStandalonePageBytes = Encoding.ASCII.GetBytes(html);
                    }
                    return ImplicitStandalonePageBytes;
                }
            }

            return base.AsMimeType(mimeType, out resultingMimeType, request);
        }
 /// <summary>
 /// Build a response 
 /// </summary>
 /// <param name="data"></param>
 /// <param name="mime"></param>
 /// <param name="dropConn"></param>
 protected virtual void BuildResponse(byte[] data, MimeType mime, bool dropConn = true)
 {
     bool gzip = Request.isGZIPSupported();
     data = gzip ? HttpHelper.CompressGZIP(data) : data;
     byte[] header = HttpHelper.GetHeader(data.Length, mime, dropConn, gzip);
     byte[] complete = header.Concat(data);
     this.response = new HttpResponse(complete, Request);
 }
示例#8
0
文件: TagForm.cs 项目: bzure/BSA.Net
        /// <summary>Assigns all needed attributes to the tag</summary>
        /// <returns>This instance downcasted to base class</returns>
        public virtual IndexedTag attr(
            string action = null,
            Method? method = null,
            MimeType enctype = null,
            Target target = null,
            string onsubmit = null,
            string onreset = null,
            MimeType[] accept = null,
            Charset[] acceptcharset = null,
            string id = null,
            string name = null,
            string @class = null,
            string style = null,
            string title = null,
            LangCode lang = null,
            string xmllang = null,
            Dir? dir = null,
            string onclick = null,
            string ondblclick = null,
            string onmousedown = null,
            string onmouseup = null,
            string onmouseover = null,
            string onmousemove = null,
            string onmouseout = null,
            string onkeypress = null,
            string onkeydown = null,
            string onkeyup = null
        )
        {
            Action = action;
            Method = method;
            EncType = enctype;
            Target = target;
            OnSubmit = onsubmit;
            OnReset = onreset;
            Accept = accept;
            AcceptCharset = acceptcharset;
            Id = id;
            Name = name;
            Class = @class;
            Style = style;
            Title = title;
            Lang = lang;
            XmlLang = xmllang;
            Dir = dir;
            OnClick = onclick;
            OnDblClick = ondblclick;
            OnMouseDown = onmousedown;
            OnMouseUp = onmouseup;
            OnMouseOver = onmouseover;
            OnMouseMove = onmousemove;
            OnMouseOut = onmouseout;
            OnKeyPress = onkeypress;
            OnKeyDown = onkeydown;
            OnKeyUp = onkeyup;

            return this;
        }
        public static IEnumerable<IImapBodyStructure> FindAll(this IImapBodyStructure bodyStructure, MimeType mediaType)
        {
            if (mediaType == null)
            throw new ArgumentNullException("mediaType");

              return FindAll(bodyStructure, delegate(IImapBodyStructure s) {
            return s.MediaType.EqualsIgnoreCase(mediaType);
              });
        }
示例#10
0
文件: TagLink.cs 项目: bzure/BSA.Net
        /// <summary>Assigns all needed attributes to the tag</summary>
        /// <returns>This instance downcasted to base class</returns>
        public virtual IndexedTag attr(
            Charset charset = null,
            string href = null,
            LangCode hreflang = null,
            Target target = null,
            MimeType type = null,
            LinkType? rel = null,
            LinkType? rev = null,
            Media? media = null,
            string id = null,
            string @class = null,
            string style = null,
            string title = null,
            LangCode lang = null,
            string xmllang = null,
            Dir? dir = null,
            string onclick = null,
            string ondblclick = null,
            string onmousedown = null,
            string onmouseup = null,
            string onmouseover = null,
            string onmousemove = null,
            string onmouseout = null,
            string onkeypress = null,
            string onkeydown = null,
            string onkeyup = null
        )
        {
            Charset = charset;
            Href = href;
            HrefLang = hreflang;
            Target = target;
            Type = type;
            Rel = rel;
            Rev = rev;
            Media = media;
            Id = id;
            Class = @class;
            Style = style;
            Title = title;
            Lang = lang;
            XmlLang = xmllang;
            Dir = dir;
            OnClick = onclick;
            OnDblClick = ondblclick;
            OnMouseDown = onmousedown;
            OnMouseUp = onmouseup;
            OnMouseOver = onmouseover;
            OnMouseMove = onmousemove;
            OnMouseOut = onmouseout;
            OnKeyPress = onkeypress;
            OnKeyDown = onkeydown;
            OnKeyUp = onkeyup;

            return this;
        }
示例#11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Response"/> class.
 /// </summary>
 public Response()
 {
     this.cookies = new CookieCollection();
     this.headers = new HeaderCollection();
     this.headersSent = false;
     this.contentType = MimeType.Default;
     this.outputBuffer = new List<byte>();
     this.sent = 0;
     this.status = StatusCode.Http500InternalServerError;
     this.useChunkedTransferEncoding = false;
     this.useCompression = false;
 }
示例#12
0
        /// <summary>Assigns all needed attributes to the tag</summary>
        /// <returns>This instance downcasted to base class</returns>
        public virtual IndexedTag attr(
            Charset charset = null,
            MimeType type = null,
            string src = null,
            Defer? defer = null,
            string xmlspace = null
        )
        {
            Charset = charset;
            Type = type;
            Src = src;
            Defer = defer;
            XmlSpace = xmlspace;

            return this;
        }
示例#13
0
文件: TagParam.cs 项目: bzure/BSA.Net
        /// <summary>Assigns all needed attributes to the tag</summary>
        /// <returns>This instance downcasted to base class</returns>
        public virtual IndexedTag attr(
            string id = null,
            string name = null,
            string value = null,
            ValueType? valuetype = null,
            MimeType type = null
        )
        {
            Id = id;
            Name = name;
            Value = value;
            ValueType = valuetype;
            Type = type;

            return this;
        }
示例#14
0
文件: TagStyle.cs 项目: bzure/BSA.Net
        /// <summary>Assigns all needed attributes to the tag</summary>
        /// <returns>This instance downcasted to base class</returns>
        public virtual IndexedTag attr(
            MimeType type = null,
            Media? media = null,
            string title = null,
            string xmlspace = null,
            LangCode lang = null,
            string xmllang = null,
            Dir? dir = null
        )
        {
            Type = type;
            Media = media;
            Title = title;
            XmlSpace = xmlspace;
            Lang = lang;
            XmlLang = xmllang;
            Dir = dir;

            return this;
        }
        public ImapMessageRfc822BodyStructure(string section,
                                          MimeType mediaType,
                                          IDictionary<string, string> parameters,
                                          string id,
                                          string description,
                                          string encoding,
                                          long size,
                                          ImapEnvelope envelope,
                                          IImapBodyStructure bodyStructure,
                                          long lineCount)
            : base(section, mediaType, parameters, id, description, encoding, size, lineCount)
        {
            if (envelope == null)
            throw new ArgumentNullException("envelope");
              if (bodyStructure == null)
            throw new ArgumentNullException("bodyStructure");

              this.Envelope       = envelope;
              this.BodyStructure  = bodyStructure;

              ImapBodyStructureUtils.SetParentStructure(this);
        }
示例#16
0
 public static void SaveBitmap(MimeType mineType, BitmapSource source, string savePath)
 {
     SaveBitmap(mineType, BitmapFrame.Create(source), savePath);
 }
 public StaticContentResult(byte[] uncompressedContent, string fileName)
 {
     this.FileName     = fileName;
     this.ContentType  = MimeType.FromFileName(fileName);
     this.Uncompressed = uncompressedContent;
 }
示例#18
0
        static void Main(string[] args)
        {
            //string file = args[0];
            string file = @"C:\Users\MIRVIN\Desktop\Training Wheels\SampleAttachment\bin\Debug\testfile.rtf";

            if (File.Exists(file))
            {
                Console.WriteLine("Uploading {0}", file);
                string mimeType = MimeType.Resolve(file);

                IMetaModel   metaModel   = new MetaModel(new V1APIConnector(ApplicationURL + "meta.v1/"));
                IServices    services    = new Services(metaModel, new V1APIConnector(ApplicationURL + "rest-1.v1/", _username, _password, _integrated));
                IAttachments attachments = new Attachments(new V1APIConnector(ApplicationURL + "attachment.img/", _username, _password, _integrated));


                //cleanjeans scope
                Oid attachmentContext = Oid.FromToken("Scope:5067", metaModel);



                IAssetType attachmentType = metaModel.GetAssetType("Attachment");

                IAttributeDefinition attachmentNameDef = attachmentType.GetAttributeDefinition("Name");

                IAttributeDefinition attachmentContentDef = attachmentType.GetAttributeDefinition("Content");

                IAttributeDefinition attachmentContentTypeDef = attachmentType.GetAttributeDefinition("ContentType");

                IAttributeDefinition attachmentFileNameDef = attachmentType.GetAttributeDefinition("Filename");



                Asset newAttachment = services.New(attachmentType, attachmentContext);

                newAttachment.SetAttributeValue(attachmentNameDef, "New Attachment");

                newAttachment.SetAttributeValue(attachmentContentDef, string.Empty);

                newAttachment.SetAttributeValue(attachmentContentTypeDef, mimeType);

                newAttachment.SetAttributeValue(attachmentFileNameDef, file);

                services.Save(newAttachment);

                //Setup and attach the payload

                string attachmentKey = newAttachment.Oid.Key.ToString();
                int    buffersize    = 4096;

                using (FileStream input = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    using (Stream output = attachments.GetWriteStream(attachmentKey))
                    {
                        byte[] buffer = new byte[buffersize];

                        for (; ;)
                        {
                            int read = input.Read(buffer, 0, buffersize);

                            if (read == 0)
                            {
                                break;
                            }

                            output.Write(buffer, 0, read);
                        }
                    }
                }

                attachments.SetWriteStream(attachmentKey, mimeType);



                Console.WriteLine("{0} uploaded", file);
            }

            else
            {
                Console.WriteLine("{0} does not exist", file);
            }
        }
示例#19
0
 public void Unsupported_charset_defaults_to_utf8_encoding()
 {
     var mimeType = new MimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=binary");
     Assert.AreEqual(Encoding.UTF8, mimeType.CharSet);
 }
示例#20
0
 public static bool Writes(this IMediaWriter media, MimeType mimeType)
 {
     return(media.Mimetypes.Contains(mimeType.Value));
 }
示例#21
0
 public IFormatter FormatterFor(MimeType mimeType)
 {
     return(FormatterFor(mimeType.Value));
 }
示例#22
0
        public static ImmutableList <MediaTrack> FromSdp(SessionDescription sdp, Uri baseUri, MimeType filter = null)
        {
            var builder = ImmutableList.CreateBuilder <MediaTrack>();

            string sdpConnectionAddr = baseUri.Host;

            if (sdp.Connection != null && IsAddressSet(sdp.Connection.Address))
            {
                sdpConnectionAddr = sdp.Connection.Address;
            }

            sdp.MediaDescriptions.ForEach(md =>
            {
                Uri controlUri = baseUri;
                string type    = md.Media.ToString().ToLower();
                string subType = "unknown";

                // Prefer the media description's connection address over the sdp connection address.
                var connectionAddr = md.Connection != null && !string.IsNullOrEmpty(md.Connection.Address)
                        ? md.Connection.Address
                        : sdpConnectionAddr;

                var rtmpmaps = md.GetRtpMaps();

                // Via spec there can be multiple types and rtpmaps, but
                // we will assume a single one since all cameras/encoders
                // appear to only provide one per Media Description.
                var rtpmap = rtmpmaps.IsEmpty ? FromPayloadType(md.MediaFormats[0]) : rtmpmaps.First();
                subType    = rtpmap.EncodingName;

                var control = md.Attributes.Where(a => "control" == a.Name).DefaultIfEmpty(null).First();
                if (control != null)
                {
                    controlUri = ResolveUri(baseUri, new Uri(control.Value, UriKind.RelativeOrAbsolute));
                }

                var mimeType = MimeType.Create(type, rtpmap.EncodingName);

                if (mimeType.Is(APPLICATION_SPOOFED))
                {
                    // The MediaGateway and Vxpro us spoofing to determine the client's intentions of
                    // either playing live or recorded data.  Because of the current design they do not
                    // have a way to know the client's intentions until a play call is issued that contains
                    // and RTSP Range header with an absolute start-time.
                    //
                    // To handle metadata, in a pretty hacky way, a new media description is added to the SDP
                    // of type application/vnd.pelco.spoofed to indicate to a client that the data is bogus
                    // The client should continue processing up until the play call is made.  At this point the
                    // MediaGateway or VxPro will issues a redirect to the actual source.
                    //
                    // We will make a bogus metadata track to allow the client to continue processing.
                    builder.Add(MediaTrack.CreateBuilder()
                                .Address(Dns.GetHostAddresses(baseUri.Host)[0])
                                .Port(md.Port)
                                .Type(mimeType)
                                .Uri(controlUri)
                                .Build());
                }
                else if ((filter != null && mimeType.Is(filter)) || (filter == null))
                {
                    // If a filter is defined only return tracks that match the
                    // defined filter type; otherwise, return all tracks.

                    if (IsAddressSet(connectionAddr))
                    {
                        // If defined as 0.0.0.0 or ::0 then replace with the SDP connection address.
                        connectionAddr = sdpConnectionAddr;
                    }

                    var addrs = Dns.GetHostAddresses(connectionAddr);

                    builder.Add(MediaTrack.CreateBuilder()
                                .Address(Dns.GetHostAddresses(connectionAddr)[0])
                                .Port(md.Port)
                                .RtpMap(rtpmap)
                                .Type(mimeType)
                                .Uri(controlUri)
                                .Build());
                }
            });

            return(builder.ToImmutable());
        }
        public override IMessage DoPreSend(IMessage message, IMessageChannel channel)
        {
            // If handler is a function, FunctionInvoker will already perform message
            // conversion.
            // In fact in the future we should consider propagating knowledge of the
            // default content type
            // to MessageConverters instead of interceptors
            if (message.Payload is byte[] && message.Headers.ContainsKey(MessageHeaders.CONTENT_TYPE))
            {
                return(message);
            }

            // ===== 1.3 backward compatibility code part-1 ===
            string oct = null;

            if (message.Headers.ContainsKey(MessageHeaders.CONTENT_TYPE))
            {
                oct = message.Headers.Get <MimeType>(MessageHeaders.CONTENT_TYPE).ToString();
            }

            var ct = oct;

            if (message.Payload is string)
            {
                if (MimeTypeUtils.APPLICATION_JSON_VALUE.Equals(oct))
                {
                    ct = MimeTypeUtils.APPLICATION_JSON_VALUE;
                }
                else
                {
                    ct = MimeTypeUtils.TEXT_PLAIN_VALUE;
                }
            }

            // ===== END 1.3 backward compatibility code part-1 ===
            if (!message.Headers.ContainsKey(MessageHeaders.CONTENT_TYPE))
            {
                var messageHeaders = message.Headers as MessageHeaders;
                messageHeaders.RawHeaders[MessageHeaders.CONTENT_TYPE] = _mimeType;
            }

            IMessage result;

            if (message.Payload is byte[])
            {
                result = message;
            }
            else
            {
                result = _messageConverter.ToMessage(message.Payload, message.Headers);
            }

            if (result == null)
            {
                throw new InvalidOperationException("Failed to convert message: '" + message + "' to outbound message.");
            }

            // ===== 1.3 backward compatibility code part-2 ===
            if (ct != null && !ct.Equals(oct) && oct != null)
            {
                var messageHeaders = result.Headers as MessageHeaders;
                messageHeaders.RawHeaders[MessageHeaders.CONTENT_TYPE] = MimeType.ToMimeType(ct);
                messageHeaders.RawHeaders[BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE] = MimeType.ToMimeType(oct);
            }

            // ===== END 1.3 backward compatibility code part-2 ===
            return(result);
        }
 protected AbstractContentTypeInterceptor(string contentType)
 {
     _mimeType = MimeTypeUtils.ParseMimeType(contentType);
 }
示例#25
0
 public static MimeMessage CreateAttachment(Stream contentStream, MimeType mimeType, string filename, bool inline)
 {
     return CreateAttachment(contentStream, mimeType, filename, null, inline);
 }
示例#26
0
 public static void Write(this IOutputWriter writer, MimeType mimeType, string contents)
 {
     writer.Write(mimeType.Value, contents);
 }
示例#27
0
        public void SetContentStreamTest(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);

            IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath);

            string filename = "testfile.txt";
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            try {
                IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            IDocument emptyDoc = folder.CreateDocument(properties, null, null);

            Assert.That(emptyDoc.ContentStreamLength == null || emptyDoc.ContentStreamLength == 0, "returned document shouldn't got any content");
            string content = string.Empty;

            content += "Test ";
            ContentStream contentStream = new ContentStream();

            contentStream.FileName = filename;
            contentStream.MimeType = MimeType.GetMIMEType(filename);
            contentStream.Length   = content.Length;
            using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
                contentStream.Stream = memstream;
                emptyDoc.SetContentStream(contentStream, true, true);
            }

            Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength);
            emptyDoc.DeleteContentStream(true);
            content               += "Test ";
            contentStream          = new ContentStream();
            contentStream.FileName = filename;
            contentStream.MimeType = MimeType.GetMIMEType(filename);
            contentStream.Length   = content.Length;
            using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
                contentStream.Stream = memstream;
                emptyDoc.SetContentStream(contentStream, true, true);
            }

            Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength);
            emptyDoc.DeleteContentStream(true);
            content               += "Test ";
            contentStream          = new ContentStream();
            contentStream.FileName = filename;
            contentStream.MimeType = MimeType.GetMIMEType(filename);
            contentStream.Length   = content.Length;
            using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
                contentStream.Stream = memstream;
                emptyDoc.SetContentStream(contentStream, true, true);
            }

            Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength);
            emptyDoc.DeleteAllVersions();
        }
示例#28
0
 /// <summary>
 /// Create a document from a stream.
 /// </summary>
 /// <param name="stream">Document stream.</param>
 /// <param name="mime">Document mime-type.</param>
 /// <returns>New document instance.</returns>
 public static XDoc From(Stream stream, MimeType mime)
 {
     return(From(stream, mime, false));
 }
示例#29
0
        /// <summary>
        /// Loads the document in the provided context from the given response.
        /// </summary>
        /// <param name="context">The browsing context.</param>
        /// <param name="response">The response to consider.</param>
        /// <param name="contentType">The content type of the response.</param>
        /// <param name="source">The source to use.</param>
        /// <param name="cancelToken">Token for cancellation.</param>
        /// <returns>The task that builds the document.</returns>
        internal async static Task <SvgDocument> LoadAsync(IBrowsingContext context, IResponse response, MimeType contentType, TextSource source, CancellationToken cancelToken)
        {
            var document = new SvgDocument(context, source);
            var evt      = new HtmlParseStartEvent(document);
            var events   = context.Configuration.Events;
            var parser   = new XmlDomBuilder(document);

            document.ContentType = contentType.Content;
            document.Referrer    = response.Headers.GetOrDefault(HeaderNames.Referer, String.Empty);
            document.DocumentUri = response.Address.Href;
            document.Cookie      = response.Headers.GetOrDefault(HeaderNames.SetCookie, String.Empty);
            document.ReadyState  = DocumentReadyState.Loading;
            context.NavigateTo(document);

            if (events != null)
            {
                events.Publish(evt);
            }

            await parser.ParseAsync(default(XmlParserOptions), cancelToken).ConfigureAwait(false);

            evt.FireEnd();
            return(document);
        }
示例#30
0
 public static TagLink type(this TagLink tag, MimeType value)
 {
     tag.Type = value; return(tag);
 }
示例#31
0
 public static TagObject codetype(this TagObject tag, MimeType value) { tag.CodeType = value; return tag; }
示例#32
0
 public static MimeMessage CreateAttachment(Stream contentStream, MimeType mimeType)
 {
     return CreateAttachment(contentStream, mimeType, null, null, false);
 }
        private long message_serial_number = 0; // unique increasing integer number (unique per each msg for one particular response)
        public void send_event(MimeType mime_type, string body_key, string body_json)
        {
            string mime_type_str = "response/" + mime_type.ToString("f");
            string rabbit_routingKey = "responses." + response_guid + ".events." + mime_type_str;
            mongodb_channel.BasicPublish(exchange_name,
                            rabbit_routingKey,
                            mongodb_msg_props,
                            Encoding.UTF8.GetBytes("{" +
                                "\"mime_type\": \"" + mime_type_str + "\", " +
                                "\"response_guid\": \"" + response_guid + "\", " +
                                "\"sn\": " + (message_serial_number++) + ", " +
                                "\"time_epoch_s\": " + ConvertToUnixTimestamp(DateTime.Now).ToString() + ", " +
                                "\"" + body_key + "\": " + body_json +
                                "}"));

            // Encoding.UTF8.GetBytes("{ \"message\": \"" + i + ") hi from c# " + rabbit_message + "\", \"i_squared\": " + (i * i) + "}"));    // or Encoding.UTF8.GetBytes();  - we convert message into a byte array 

        }
示例#34
0
        private void PostRequestedStaticFileToClient()
        {
            string requestFilePath =
                string.Concat(
                    Configurations.Xeora.Application.Main.PhysicalRoot,
                    this.Context.Request.Header.URL.RelativePath
                    );

            requestFilePath = Path.GetFullPath(requestFilePath);

            if (!File.Exists(requestFilePath) ||
                (File.Exists(requestFilePath) && this.IsRequestedStaticFileBanned(requestFilePath)))
            {
                this.Context.Response.Header.Status.Code    = 404;
                this.Context.Response.Header.Status.Message = "Not Found";

                this.Context.AddOrUpdate("RedirectLocation", null);

                return;
            }

            string contentType =
                MimeType.GetMime(Path.GetExtension(requestFilePath));

            string range            = this.Context.Request.Header["Range"];
            bool   isPartialRequest = !string.IsNullOrEmpty(range);

            Stream requestFileStream = null;

            if (!isPartialRequest)
            {
                this.Context.Response.Header.AddOrUpdate("Accept-Ranges", "bytes");

                try
                {
                    requestFileStream = new FileStream(requestFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    this.Context.Response.Header.AddOrUpdate("Content-Length", requestFileStream.Length.ToString());

                    this.WriteOutput(contentType, ref requestFileStream, false);
                }
                catch (System.Exception)
                {
                    throw;
                }
                finally
                {
                    if (requestFileStream != null)
                    {
                        requestFileStream.Close();
                        GC.SuppressFinalize(requestFileStream);
                    }
                }

                this.Context.AddOrUpdate("RedirectLocation", null);

                return;
            }

            long beginRange = 0, endRange = -1;

            if (range.IndexOf("bytes=") == 0)
            {
                range = range.Remove(0, "bytes=".Length);
                try
                {
                    if (!long.TryParse(range.Split('-')[0], out beginRange))
                    {
                        beginRange = 0;
                    }
                    if (!long.TryParse(range.Split('-')[1], out endRange))
                    {
                        endRange = -1;
                    }
                }
                catch (System.Exception)
                {
                    this.Context.Response.Header.Status.Code    = 416;
                    this.Context.Response.Header.Status.Message = "Range Not Satisfiable";

                    this.Context.AddOrUpdate("RedirectLocation", null);

                    return;
                }
            }

            try
            {
                requestFileStream =
                    new FileStream(requestFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (endRange == -1)
                {
                    endRange = requestFileStream.Length - 1;
                }

                long requestingLength = endRange - beginRange + 1;

                if (endRange > requestFileStream.Length - 1 || beginRange > endRange)
                {
                    this.Context.Response.Header.Status.Code    = 416;
                    this.Context.Response.Header.Status.Message = "Range Not Satisfiable";

                    this.Context.AddOrUpdate("RedirectLocation", null);

                    return;
                }

                this.Context.Response.Header.Status.Code    = 206;
                this.Context.Response.Header.Status.Message = "Partial Content";
                this.Context.Response.Header.AddOrUpdate("Content-Type", contentType);
                this.Context.Response.Header.AddOrUpdate("Content-Encoding", "identity");
                this.Context.Response.Header.AddOrUpdate("Content-Range", string.Format("bytes {0}-{1}/{2}", beginRange, endRange, requestFileStream.Length));
                this.Context.Response.Header.AddOrUpdate("Content-Length", requestingLength.ToString());

                requestFileStream.Seek(beginRange, SeekOrigin.Begin);

                byte[] buffer = new byte[102400];
                int    bR     = 0;
                do
                {
                    bR = requestFileStream.Read(buffer, 0, buffer.Length);

                    if (requestingLength < bR)
                    {
                        bR = (int)requestingLength;
                    }

                    this.Context.Response.Write(buffer, 0, bR);

                    requestingLength -= bR;
                } while (requestingLength != 0 && bR != 0);
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if (requestFileStream != null)
                {
                    requestFileStream.Close();
                    GC.SuppressFinalize(requestFileStream);
                }
            }

            this.Context.AddOrUpdate("RedirectLocation", null);
        }
示例#35
0
 public static TagForm accept(this TagForm tag, MimeType[] value) { tag.Accept = value; return tag; }
示例#36
0
        public void Unsupported_charset_defaults_to_utf8_encoding()
        {
            var mimeType = new MimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=binary");

            Assert.AreEqual(Encoding.UTF8, mimeType.CharSet);
        }
示例#37
0
        // Calls the Run method on the app object.
        internal int Run(InitData initData)
        {
            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordHosting | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose, EventTrace.Event.WpfHost_AppProxyRunStart);

            // Keep in mind that Run() is called once in the default AppDomain and then in the XBAP's domain.
            // We want initialization of statics to happen in both AppDomains.

            if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // Since IHostBrowser was marshaled from the default AppDomain as a managed interface, we get
                // a Remoting transparent proxy here. Any calls on the interface would have to first be marshaled
                // to the default AppDomain, where the CLR will realize it's actually a COM interface. This is
                // wasteful since the object lives in the browser process. So, to shake off the Remoting layer,
                // we round-trip the IHostBrowser reference through IUknown/IntPtr.
                IntPtr pObj = Marshal.GetIUnknownForObject(initData.HostBrowser);
                try { initData.HostBrowser = (IHostBrowser)Marshal.GetObjectForIUnknown(pObj); }
                finally { Marshal.Release(pObj); }
            }
            BrowserInteropHelper.HostBrowser = initData.HostBrowser;

            MimeType mimeType = initData.MimeType.Value;

            _mimeType.Value = mimeType;
            Uri             = initData.ActivationUri.Value;
            WpfWebRequestHelper.DefaultUserAgent = initData.UserAgentString;
            BrowserInteropHelper.HostingFlags    = initData.HostingFlags;

            // These methods are asynchronous.
            // If the RootBrowserWindow is not created yet, only the size for it will be stored.
            Move(initData.WindowRect);
            Show(initData.ShowWindow);

            switch (mimeType)
            {
            case MimeType.Markup:
                // Make a dummy application (in lieu of the one provided by the defunct XamlViewer.xbap).
                Invariant.Assert(AppDomain.CurrentDomain.FriendlyName == "XamlViewer");
                Application app = new Application();
                app.StartupUri = Uri;
                // Any URL #fragment is appended to StartupUri in _RunDelegate().
                // For history navigation, ApplicationProxyInternal has already started navigation to the
                // last journal entry captured. (This journal entry may include a #fragment target and/or
                // a CustomContentState.)
                break;

            case MimeType.Application:
                //This is a browser app, the application object has already been created
                break;

            case MimeType.Document:
                throw new NotImplementedException();     // removed in v4

            case MimeType.Unknown:
            default:
                throw new InvalidOperationException();
            }

            // Set the Application.MimeType
            // Since loading containers causes the application to be constructed now,
            // the initial setting of the MimeType does not get passed to the application.
            Application.Current.MimeType = mimeType;
            ServiceProvider = initData.ServiceProvider; // also sets Application.ServiceProvider

            Application.Current.Dispatcher.Invoke(
                DispatcherPriority.Send,
                new DispatcherOperationCallback(_RunDelegate),
                initData);

            int exitCode = Application.Current.RunInternal(null);

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordHosting | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose, EventTrace.Event.WpfHost_AppProxyRunEnd);

            return(exitCode);
        }
示例#38
0
 public void determine_mime_type_from_name_for_js()
 {
     MimeType.MimeTypeByFileName("file.coffee.js")
     .ShouldEqual(MimeType.Javascript);
 }
示例#39
0
        public static HttpResponse ContentTypeShouldBe(this HttpResponse response, MimeType mimeType)
        {
            response.ContentType.ShouldEqual(mimeType.Value);

            return(response);
        }
示例#40
0
 public void determine_mime_type_from_name_for_css()
 {
     MimeType.MimeTypeByFileName("style.css")
     .ShouldEqual(MimeType.Css);
 }
示例#41
0
        // 패턴 체크 실행
        bool checkUrlType(HostCheck patternCheck, Session oSession)
        {
            if (oSession.HTTPMethodIs("CONNECT"))
            {
                oSession.hostname = patternCheck.afterHost();
            }
            else
            {
                if (patternCheck.isStatus())
                {
                    int status = patternCheck.getStatusCode();

                    sendResponse(oSession, status, "text/html", new byte[0]);

                    return(false);
                }

                if (patternCheck.isFolder() || patternCheck.isFile())
                {
                    string url = oSession.fullUrl;
                    int    idx = url.LastIndexOf(patternCheck.Before);

                    FileInfo file;
                    string   target;

                    if (patternCheck.isFolder())
                    {
                        string first  = url.Substring(0, idx);
                        string second = patternCheck.Before;
                        string last   = url.Replace(first, "").Replace(second, "");

                        log(first + " : " + second + " : " + last);

                        // 기본 디렉토리 지정
                        if (string.IsNullOrEmpty(last) || last.Equals("/"))
                        {
                            last = "/index.html";
                        }

                        if (last[0] != '/')
                        {
                            last = "/" + last;
                        }

                        target = patternCheck.After + last;
                    }
                    else
                    {
                        target = patternCheck.After;
                    }

                    file = new FileInfo(target);

                    if (file.Exists)
                    {
                        string content_type = MimeType.Get(file.Extension);
                        byte[] data         = File.ReadAllBytes(file.FullName);

                        sendResponse(oSession, 200, content_type, data);

                        return(false);
                    }
                }
                else
                {
                    oSession.fullUrl = patternCheck.afterUrl(oSession.fullUrl);
                }
            }

            return(true);
        }
示例#42
0
 public void determine_mime_type_from_name_for_truetype_font()
 {
     MimeType.MimeTypeByFileName("somefont.ttf")
     .ShouldEqual(MimeType.TrueTypeFont);
 }
示例#43
0
 public static void SaveBitmap(MimeType mineType, Stream BitmapStream, string savePath)
 {
     SaveBitmap(mineType, BitmapFrame.Create(BitmapStream), savePath);
 }
示例#44
0
 public static TagStyle type(this TagStyle tag, MimeType value) { tag.Type = value; return tag; }
示例#45
0
        /// <summary>
        /// Saves the edit model.
        /// </summary>
        public bool SaveAll(bool draft)
        {
            var context = HttpContext.Current;
            var hasfile = UploadedFile != null || ServerFile != null;

            byte[]    data = null;
            WebClient web  = new WebClient();

            // Check if the original URL has been updated, and if so
            if (!Content.IsNew && !String.IsNullOrEmpty(Content.OriginalUrl))
            {
                var old = Content.GetSingle(Content.Id);
                if (old != null)
                {
                    if (Content.OriginalUrl != old.OriginalUrl)
                    {
                        FileUrl = Content.OriginalUrl;
                    }
                }
            }

            // Download file from web
            if (!hasfile && !String.IsNullOrEmpty(FileUrl))
            {
                data = web.DownloadData(FileUrl);
                Content.OriginalUrl = FileUrl;
                Content.LastSynced  = Convert.ToDateTime(web.ResponseHeaders[HttpResponseHeader.LastModified]);
            }

            var media = new MediaFileContent();

            if (hasfile)
            {
                if (UploadedFile != null)
                {
                    media.Filename    = UploadedFile.FileName;
                    media.ContentType = UploadedFile.ContentType;
                    using (var reader = new BinaryReader(UploadedFile.InputStream)) {
                        media.Body = reader.ReadBytes(Convert.ToInt32(UploadedFile.InputStream.Length));
                    }
                }
                else
                {
                    media.Filename    = ServerFile.Name;
                    media.ContentType = MimeType.Get(ServerFile.Name);
                    using (var stream = ServerFile.OpenRead()) {
                        media.Body = new byte[ServerFile.Length];
                        stream.Read(media.Body, 0, media.Body.Length);
                    }
                }
            }
            else if (data != null)
            {
                media.Filename    = FileUrl.Substring(FileUrl.LastIndexOf('/') + 1);
                media.ContentType = web.ResponseHeaders["Content-Type"];
                media.Body        = data;
            }
            else
            {
                media = null;
            }

            var saved = false;

            if (draft)
            {
                saved = Content.Save(media);
            }
            else
            {
                saved = Content.SaveAndPublish(media);
            }

            if (saved)
            {
                // Save related information
                Relation.DeleteByDataId(Content.Id);
                List <Relation> relations = new List <Relation>();
                ContentCategories.ForEach(c => relations.Add(new Relation()
                {
                    DataId = Content.Id, RelatedId = c, IsDraft = false, Type = Relation.RelationType.CONTENTCATEGORY
                })
                                          );
                relations.ForEach(r => r.Save());

                // Save extensions
                foreach (var ext in Extensions)
                {
                    ext.ParentId = Content.Id;
                    ext.Save();
                    if (!draft)
                    {
                        if (Extension.GetScalar("SELECT COUNT(extension_id) FROM extension WHERE extension_id=@0 AND extension_draft=0", ext.Id) == 0)
                        {
                            ext.IsNew = true;
                        }
                        ext.IsDraft = false;
                        ext.Save();
                    }
                }
                // Reset file url
                FileUrl = "";

                return(true);
            }
            return(false);
        }
        public void SaveAssetDataFromCSV(List<Asset> assets)
        {
            // Insert the available country list
            Dictionary<string, int> countryList = assets.GroupBy(x => x.Country.CountryName).Select(x => new
            {
                Key = x.Key.ToString()
            }).ToDictionary(t => t.Key, t => 0);

            List<string> countryListKeys = countryList.Keys.ToList();

            foreach (var countryKey in countryListKeys)
            {
                Country country = _context.Countries.Where(x => x.CountryName == countryKey).FirstOrDefault();
                if (country == null)
                {
                    country = new Country
                    {
                        CountryName = countryKey
                    };
                    _context.Countries.Add(country);
                }
                _context.SaveChanges();
                countryList[countryKey] = country.CountryId;
            }

            // Insert the available mime-type list
            Dictionary<string, int> mimeTypeList = assets.GroupBy(x => x.MimeType.Type).Select(x => new
            {
                Key = x.Key.ToString()
            }).ToDictionary(t => t.Key, t => 0);

            List<string> mimeTypeListKeys = countryList.Keys.ToList();

            foreach (var typeKey in mimeTypeListKeys)
            {
                MimeType type = _context.MimeTypes.Where(x => x.Type == typeKey).FirstOrDefault();
                if (type == null)
                {
                    type = new MimeType
                    {
                        Type = typeKey
                    };
                    _context.MimeTypes.Add(type);
                }
                _context.SaveChanges();
                countryList[typeKey] = type.MimeTypeId;
            }

            // Insert the Asset
            int count = 1;
            int commitCount = 500;
            foreach (Asset asset in assets)
            {
                if (!_context.Assets.Any(x => x.AssetId == asset.AssetId))
                {
                    asset.CountryId = countryList[asset.Country.CountryName];
                    asset.MimeTypeId = mimeTypeList[asset.MimeType.Type];
                    asset.CreatedOn = DateTime.UtcNow;
                    _context.Assets.Add(asset);
                }
                else
                {
                    Console.WriteLine($"Asset with ID:{asset.AssetId} already exists!");
                }

                if (count % commitCount == 0)
                {
                    _context.SaveChanges();
                    _context.Dispose();
                    _context = new DataContext();
                    _context.Configuration.AutoDetectChangesEnabled = false;
                    Console.WriteLine($"Processing at Row# {count}");
                }
                count++;
            }
            _context.SaveChanges();
            Console.WriteLine($"Total Records processed = {assets.Count()}");
        }
示例#47
0
        public ResourceBE AddAttachment(ResourceBE existingRevision, Stream filestream, long filesize, MimeType mimeType, PageBE targetPage, string userDescription, string fileName, bool isMsWebDav)
        {
            if (_dekiContext.Instance.MaxFileSize < filesize)
            {
                throw new AttachmentMaxFileSizeAllowedInvalidArgumentException(_dekiContext.Instance.MaxFileSize);
            }
            var saveFileName = ValidateFileName(fileName);

            if (existingRevision != null)
            {
                if (!saveFileName.EqualsInvariant(existingRevision.Name))
                {
                    // An existing file is getting renamed. Make sure no file exists with the new name
                    var existingAttachment = GetPageAttachment(targetPage.ID, saveFileName);
                    if (existingAttachment != null)
                    {
                        throw new AttachmentExistsOnPageConflictException(saveFileName, targetPage.Title.AsUserFriendlyName());
                    }
                }
            }

            // If file is found but has been deleted, create a new file.
            if (existingRevision != null && existingRevision.ResourceIsDeleted)
            {
                existingRevision = null;
            }
            if (isMsWebDav)
            {
                _log.DebugFormat("Upload client is MD WebDAV, provided mimetype is: {0}", mimeType);
                var extensionFileType = MimeType.FromFileExtension(Path.GetExtension(saveFileName));
                if (!extensionFileType.Match(mimeType) || extensionFileType == MimeType.DefaultMimeType)
                {
                    mimeType = existingRevision == null ? extensionFileType : existingRevision.MimeType;
                    _log.DebugFormat("using mimetype '{0}' instead", mimeType);
                }
            }
            ResourceBE attachment;
            var        resourceContents = new ResourceContentBE((uint)filesize, mimeType);
            var        isUpdate         = false;

            if (existingRevision == null)
            {
                attachment = _resourceBL.BuildRevForNewResource((uint)targetPage.ID, ResourceBE.ParentType.PAGE, saveFileName, mimeType, (uint)filesize, null, ResourceBE.Type.FILE, _dekiContext.User.ID, resourceContents);
            }
            else
            {
                isUpdate   = true;
                attachment = BuildRevForContentUpdate(existingRevision, mimeType, (uint)filesize, null, saveFileName, resourceContents);
            }

            // rewrite mimetype to text/plain for certain extensions
            string extension = attachment.FilenameExtension;

            if (_dekiContext.Instance.FileExtensionForceAsTextList.Any(forcedExtensions => extension == forcedExtensions))
            {
                attachment.MimeType = MimeType.TEXT;
            }

            // Insert the attachment into the DB
            attachment = SaveResource(attachment);
            try {
                // Save file to storage provider
                _dekiContext.Instance.Storage.PutFile(attachment, SizeType.ORIGINAL, new StreamInfo(filestream, filesize, mimeType));
            } catch (Exception x) {
                _dekiContext.Instance.Log.WarnExceptionFormat(x, "Failed to save attachment to storage provider");

                // Upon save failure, delete the record from the db.
                _session.Resources_DeleteRevision(attachment.ResourceId, attachment.Revision);
                throw;
            }

            // Set description property
            if (!string.IsNullOrEmpty(userDescription))
            {
                attachment = SetDescription(attachment, userDescription);
            }

            // For images resolve width/height (if not in imagemagick's blacklist)
            attachment = IdentifyUnknownImage(attachment);

            // Pre render thumbnails of images
            AttachmentPreviewBL.PreSaveAllPreviews(attachment);
            PageBL.Touch(targetPage, DateTime.UtcNow);

            //TODO MaxM: Connect with transaction
            RecentChangeBL.AddFileRecentChange(targetPage.Touched, targetPage, _dekiContext.User, DekiResources.FILE_ADDED(attachment.Name), 0);
            if (isUpdate)
            {
                _dekiContext.Instance.EventSink.AttachmentUpdate(_dekiContext.Now, attachment, _dekiContext.User);
            }
            else
            {
                _dekiContext.Instance.EventSink.AttachmentCreate(_dekiContext.Now, attachment, _dekiContext.User);
            }
            return(attachment);
        }
示例#48
0
 public MediaSerializer(MimeType mimeType)
     : this(mimeType.GetName())
 {
 }
示例#49
0
 public static TagScript type(this TagScript tag, MimeType value)
 {
     tag.Type = value; return(tag);
 }
示例#50
0
            public Builder Type(MimeType type)
            {
                _type = type;

                return(this);
            }
示例#51
0
 public static string GetStringMimeType(MimeType mime)
 {
     string strMime = "";
     switch (mime)
     {
         case MimeType.text_html: strMime = "text/html; charset=utf-8"; break;
         case MimeType.text_javascript: strMime = "text/javascript"; break;
         case MimeType.multipart_xmixedreplace:
             strMime = "multipart/x-mixed-replace; boundary=rnA00A"; break;
         case MimeType.application_xml_charsetutf8:
             strMime = "application/xml; charset=utf-8";
             break;
         default:
             strMime = mime.ToString().Replace("_", "/");
             break;
     }
     return strMime;
 }
示例#52
0
 public AssetPlanKey(MimeType mimeType, IEnumerable <string> names)
 {
     _mimeType = mimeType;
     _names    = names;
 }
		public void SetResponseType(MimeType mime)
		{
			_controller.Response.ContentType = mime.MimeString;
		}
示例#54
0
 public static AssetPlanKey For(MimeType mimeType, params string[] names)
 {
     return(new AssetPlanKey(mimeType, names));
 }
示例#55
0
 public static TagInput accept(this TagInput tag, MimeType[] value) { tag.Accept = value; return tag; }
示例#56
0
 public static MimeType GetMimeType(this IWebElement element)
 {
     return(MimeType.MimeTypeByFileName(element.Href()));
 }
示例#57
0
 public static TagForm enctype(this TagForm tag, MimeType value) { tag.EncType = value; return tag; }
示例#58
0
 public static TagScript type(this TagScript tag, MimeType value) { tag.Type = value; return tag; }
示例#59
0
 public AcceptHeader(MimeType contentType)
     : base("Accept", contentType.ToString())
 {
 }
示例#60
0
        public static MimeMessage CreateAttachment(Stream contentStream, MimeType mimeType, string filename, string description, bool inline)
        {
            if (contentStream == null)
            throw new ArgumentNullException("contentStream");
              if (mimeType == null)
            throw new ArgumentNullException("mimeType");

              var disposition = inline ? MimeMessageDisposition.Inline : MimeMessageDisposition.Attachment;

              // TODO: Content-Type + name parameter
              var message = new MimeMessage(new[] {
            MimeHeader.CreateContentType(mimeType, null, null, filename),
            MimeHeader.CreateContentTransferEncoding(ContentTransferEncodingMethod.Base64),
            MimeHeader.CreateContentDisposition(disposition, filename),
            new MimeHeader("Content-Description", description, MimeEncodingMethod.Base64, Charsets.UTF8),
              });

              message.MimeType = mimeType;
              message.Disposition = disposition;

              message.WriteContent(ContentTransferEncodingMethod.Base64, delegate(BinaryWriter writer) {
            contentStream.CopyTo(writer);
              });

              return message;
        }