示例#1
0
        void UpdateContentDisposition(HttpResponseMessage responseMessage)
        {
            var contentLength = Encoding.UTF8.GetByteCount(_text);
            if(contentLength > WebServerStartup.SizeCapForDownload && _enforceSizeCap)
            {
                string extension = null;
                if(ContentTypes.Json.Equals(_contentType))
                {
                    extension = "json";
                }
                else if(ContentTypes.Xml.Equals(_contentType))
                {
                    extension = "xml";
                }
                if(extension != null)
                {
                    var contentDisposition = new ContentDispositionHeaderValue("attachment");
                    contentDisposition.Parameters.Add(new NameValueHeaderValue("filename", "Output." + extension));

                    responseMessage.Content.Headers.ContentType = ContentTypes.ForceDownload;
                    responseMessage.Content.Headers.ContentDisposition = contentDisposition;
                    responseMessage.Headers.Add("Server", "Dev2 Server");
                }
            }
        }
        public void ContentDisposition_SetAndGetContentDisposition_MatchExpectations()
        {
            ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");
            Assert.Equal("inline", contentDisposition.DispositionType);

            contentDisposition.DispositionType = "attachment";
            Assert.Equal("attachment", contentDisposition.DispositionType);
        }
示例#3
0
 public static bool HasFileContentDisposition(System.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
     return(contentDisposition != null &&
            contentDisposition.DispositionType.Equals("form-data") &&
            (!string.IsNullOrEmpty(contentDisposition.FileName) ||
             !string.IsNullOrEmpty(contentDisposition.FileNameStar)));
 }
示例#4
0
 public static bool HasFormDataContentDisposition(System.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="key";
     return(contentDisposition != null &&
            contentDisposition.DispositionType.Equals("form-data") &&
            string.IsNullOrEmpty(contentDisposition.FileName) &&
            string.IsNullOrEmpty(contentDisposition.FileNameStar));
 }
		protected ContentDispositionHeaderValue (ContentDispositionHeaderValue source)
		{
			if (source == null)
				throw new ArgumentNullException ("source");

			dispositionType = source.dispositionType;
			if (source.parameters != null) {
				foreach (var item in source.parameters)
					Parameters.Add (new NameValueHeaderValue (item));
			}
		}
 public void Ctor_ContentDispositionValidFormat_SuccessfullyCreated()
 {
     ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");
     Assert.Equal("inline", contentDisposition.DispositionType);
     Assert.Equal(0, contentDisposition.Parameters.Count);
     Assert.Null(contentDisposition.Name);
     Assert.Null(contentDisposition.FileName);
     Assert.Null(contentDisposition.CreationDate);
     Assert.Null(contentDisposition.ModificationDate);
     Assert.Null(contentDisposition.ReadDate);
     Assert.Null(contentDisposition.Size);
 }
        public void Name_SetNameAndValidateObject_ParametersEntryForNameAdded()
        {
            ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");
            contentDisposition.Name = "myname";
            Assert.Equal("myname", contentDisposition.Name);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("name", contentDisposition.Parameters.First().Name);

            contentDisposition.Name = null;
            Assert.Null(contentDisposition.Name);
            Assert.Equal(0, contentDisposition.Parameters.Count);
            contentDisposition.Name = null; // It's OK to set it again to null; no exception.
        }
示例#8
0
 public FileActionResult(
     HttpRequestMessage request,
     MemoryStream content,
     MediaTypeHeaderValue contentType,
     long? contentLength,
     ContentDispositionHeaderValue contentDisposition)
 {
     this.request = request;
     this.content = content;
     this.contentType = contentType;
     this.contentLength = contentLength;
     this.contentDisposition = contentDisposition;
 }
        private void AddInternal(HttpContent content, string name, string fileName)
        {
            if (content.Headers.ContentDisposition == null)
            {
                ContentDispositionHeaderValue header = new ContentDispositionHeaderValue(formData);
                header.Name = name;
                header.FileName = fileName;
                header.FileNameStar = fileName;

                content.Headers.ContentDisposition = header;
            }
            base.Add(content);
        }
		public void Equals ()
		{
			var value = new ContentDispositionHeaderValue ("x");
			Assert.AreEqual (value, new ContentDispositionHeaderValue ("x"), "#1");
			Assert.AreNotEqual (value, new ContentDispositionHeaderValue ("y"), "#2");

			value = new ContentDispositionHeaderValue ("attachment");
			value.Parameters.Add (new NameValueHeaderValue ("size", "66"));

			Assert.AreEqual (value, new ContentDispositionHeaderValue ("attachment") { Size = 66 }, "#3");
			Assert.AreNotEqual (value, new ContentDispositionHeaderValue ("attachment"), "#4");
			Assert.AreNotEqual (value, new ContentDispositionHeaderValue ("attachment") { FileName="g" }, "#5");
		}
        private static void Add(this MultipartFormDataContent form, HttpContent content, object formValues, string name = null, string fileName = null)
        {
            var header = new ContentDispositionHeaderValue("form-data");
            header.Name = name;
            header.FileName = fileName;
            header.FileNameStar = fileName;

            var headerParameters = new HttpRouteValueDictionary(formValues);
            foreach (var parameter in headerParameters)
            {
                header.Parameters.Add(new NameValueHeaderValue(parameter.Key, parameter.Value.ToString()));
            }

            content.Headers.ContentDisposition = header;
            form.Add(content);
        }
    public FileContentResult Download(int attachmentId)
    {
        TaskAttachment taskFile = null;

        if (attachmentId > 0)
        {
            // taskFile = <your code to get the file>
            // which assumes it's an object with relevant properties as required below
            if (taskFile != null)
            {
                var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileNameStar = taskFile.Filename
                };
                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
            }
        }
        return(new FileContentResult(taskFile?.FileData, taskFile?.FileContentType));
    }
示例#13
0
        public ActionResult Download(int fileId, string pdfType, string fileName)
        {
            //TODO: Fixa fråga vid download
            var connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new SqlConnection(connectionString))
            {
                var file = _fileRepository.GetFileToDownload(fileId, pdfType);
                var cd   = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileNameStar = fileName + ".pdf"
                                   //FileNameStar = "download.pdf"
                };

                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());

                return(File(file, "application/pdf"));
            }
        }
        public void ToString_UseDifferentContentDispositions_AllSerializedCorrectly()
        {
            ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");
            Assert.Equal("inline", contentDisposition.ToString());

            contentDisposition.Name = "myname";
            Assert.Equal("inline; name=myname", contentDisposition.ToString());

            contentDisposition.FileName = "my File Name";
            Assert.Equal("inline; name=myname; filename=\"my File Name\"", contentDisposition.ToString());

            contentDisposition.CreationDate = new DateTimeOffset(new DateTime(2011, 2, 15, 8, 0, 0, DateTimeKind.Utc));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"", contentDisposition.ToString());

            contentDisposition.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\""));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString());

            contentDisposition.Name = null;
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString());

            contentDisposition.FileNameStar = "File%Name";
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"; filename*=utf-8\'\'File%25Name",
                contentDisposition.ToString());

            contentDisposition.FileName = null;
            Assert.Equal("inline; creation-date=\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\";"
                + " filename*=utf-8\'\'File%25Name", contentDisposition.ToString());

            contentDisposition.CreationDate = null;
            Assert.Equal("inline; custom=\"custom value\"; filename*=utf-8\'\'File%25Name",
                contentDisposition.ToString());
        }
示例#15
0
        public HttpResponseMessage DownloadByDay([FromUri] DateTimeInfo dateTime)
        {
            try
            {
                DateTime temp = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
                IEnumerable<ChatMessage> q = GlobalStaticVars.StaticCore.GetMessagesFromDate(temp);
                const string messageFmt = @"[{0}] [{1}] {2}:  {3}";
                MemoryStream stream = new MemoryStream();
                StreamWriter writer = new StreamWriter(stream);

                foreach (var message in q)
                {
                    message.MessageType = message.MessageType.ToUpperInvariant();
                    foreach (var teamPair in Teams)
                    {
                        message.MessageType = message.MessageType.Replace(teamPair.Key, teamPair.Value);
                    }

                    foreach (var squadPair in Squads)
                    {
                        message.MessageType = message.MessageType.Replace(squadPair.Key, squadPair.Value);
                    }

                    writer.Write(String.Format(messageFmt, message.MessageTimeStamp, message.MessageType,
                                               message.Speaker,
                                               message.Text) + "\n");
                }
                writer.Flush();
                stream.Position = 0;

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
                var disposition = new ContentDispositionHeaderValue("attachment");
                disposition.FileName = string.Format("{0}.txt", temp.ToString("yyyyMMdd"));

                result.Content.Headers.ContentDisposition = disposition;

                return result;
            }
            catch (Exception e)
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }
        internal static int GetDispositionTypeLength(string input, int startIndex, out object parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return 0;
            }

            // Caller must remove leading whitespaces. If not, we'll return 0.
            string dispositionType = null;
            int dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out dispositionType);

            if (dispositionTypeLength == 0)
            {
                return 0;
            }

            int current = startIndex + dispositionTypeLength;
            current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            ContentDispositionHeaderValue contentDispositionHeader = new ContentDispositionHeaderValue();
            contentDispositionHeader._dispositionType = dispositionType;

            // If we're not done and we have a parameter delimiter, then we have a list of parameters.
            if ((current < input.Length) && (input[current] == ';'))
            {
                current++; // Skip delimiter.
                int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
                    contentDispositionHeader.Parameters);

                if (parameterLength == 0)
                {
                    return 0;
                }

                parsedValue = contentDispositionHeader;
                return current + parameterLength - startIndex;
            }

            // We have a ContentDisposition header without parameters.
            parsedValue = contentDispositionHeader;
            return current - startIndex;
        }
        public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
        {
            ContentDispositionHeaderValue expected = new ContentDispositionHeaderValue("inline");
            CheckValidTryParse("\r\n inline  ", expected);
            CheckValidTryParse("inline", expected);

            // We don't have to test all possible input strings, since most of the pieces are handled by other parsers.
            // The purpose of this test is to verify that these other parsers are combined correctly to build a 
            // Content-Disposition parser.
            expected.Name = "myName";
            CheckValidTryParse("\r\n inline  ;  name =   myName ", expected);
            CheckValidTryParse("  inline;name=myName", expected);
        }
		public void Properties_Invalid ()
		{
			var value = new ContentDispositionHeaderValue ("a");
			try {
				value.Size = -9;
				Assert.Fail ("#1");
			} catch (ArgumentOutOfRangeException) {
			}
		}
		public void Properties_FileNameStar ()
		{
			var value = new ContentDispositionHeaderValue ("a");

			value.FileNameStar = "aa";
			Assert.AreEqual ("aa", value.FileNameStar, "#1");
			Assert.AreEqual (new NameValueHeaderValue ("filename*", "utf-8''aa"), value.Parameters.First (), "#2");

			value.FileNameStar = "č";
			Assert.AreEqual ("č", value.FileNameStar, "#11");
			Assert.AreEqual (new NameValueHeaderValue ("filename*", "utf-8''%C4%8D"), value.Parameters.First (), "#12");
		}
		public void Properties ()
		{
			var value = new ContentDispositionHeaderValue ("ttt");
			Assert.IsNull (value.CreationDate, "#1");
			Assert.AreEqual ("ttt", value.DispositionType, "#2");
			Assert.IsNull (value.FileName, "#3");
			Assert.IsNull (value.FileNameStar, "#4");
			Assert.IsNull (value.ModificationDate, "#5");
			Assert.IsNull (value.Name, "#6");
			Assert.AreEqual (0, value.Parameters.Count, "#7");
			Assert.IsNull (value.ReadDate, "#8");
			Assert.IsNull (value.Size, "#9");

			value.Parameters.Add (new NameValueHeaderValue ("creation-date", "\"20 Jun 82 11:34:11\""));
			value.Parameters.Add (new NameValueHeaderValue ("filename", "g*"));
			value.Parameters.Add (new NameValueHeaderValue ("filename*", "ag*"));
			value.Parameters.Add (new NameValueHeaderValue ("modification-date", "\"20 Jun 22 4:6:22\""));
			value.Parameters.Add (new NameValueHeaderValue ("name", "nnn"));
			value.Parameters.Add (new NameValueHeaderValue ("read-date", "\"1 Jun 01 1:1:1\""));
			value.Parameters.Add (new NameValueHeaderValue ("size", "5"));

			Assert.AreEqual (new DateTimeOffset (1982, 6, 20, 11, 34, 11, TimeSpan.Zero), value.CreationDate, "#11");
			Assert.AreEqual ("g*", value.FileName, "#12");
			Assert.IsNull (value.FileNameStar, "#13");
			Assert.AreEqual (new DateTimeOffset (2022, 6, 20, 4, 6, 22, TimeSpan.Zero), value.ModificationDate, "#14");
			Assert.AreEqual ("nnn", value.Name, "#15");
			Assert.AreEqual (new DateTimeOffset (2001, 6, 1, 1, 1, 1, TimeSpan.Zero), value.ReadDate, "#16");
			Assert.AreEqual (5, value.Size, "#17");
		}
		// Summary:
		//     Initializes a new instance of the System.Net.Http.Headers.ContentDispositionHeaderValue
		//     class.
		//
		// Parameters:
		//   source:
		//     A System.Net.Http.Headers.ContentDispositionHeaderValue.
		protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
		{
		}
        public void GetHashCode_UseContentDispositionWithAndWithoutParameters_SameOrDifferentHashCodes()
        {
            ContentDispositionHeaderValue contentDisposition1 = new ContentDispositionHeaderValue("inline");
            ContentDispositionHeaderValue contentDisposition2 = new ContentDispositionHeaderValue("inline");
            contentDisposition2.Name = "myname";
            ContentDispositionHeaderValue contentDisposition3 = new ContentDispositionHeaderValue("inline");
            contentDisposition3.Parameters.Add(new NameValueHeaderValue("name", "value"));
            ContentDispositionHeaderValue contentDisposition4 = new ContentDispositionHeaderValue("INLINE");
            ContentDispositionHeaderValue contentDisposition5 = new ContentDispositionHeaderValue("INLINE");
            contentDisposition5.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME"));

            Assert.NotEqual(contentDisposition1.GetHashCode(), contentDisposition2.GetHashCode()); // "No params vs. name."
            Assert.NotEqual(contentDisposition1.GetHashCode(), contentDisposition3.GetHashCode()); // "No params vs. custom param."
            Assert.NotEqual(contentDisposition2.GetHashCode(), contentDisposition3.GetHashCode()); // "name vs. custom param."
            Assert.Equal(contentDisposition1.GetHashCode(), contentDisposition4.GetHashCode()); // "Different casing."
            Assert.Equal(contentDisposition2.GetHashCode(), contentDisposition5.GetHashCode()); // "Different casing in name."
        }
示例#23
0
 // Summary:
 //     Initializes a new instance of the System.Net.Http.Headers.ContentDispositionHeaderValue
 //     class.
 //
 // Parameters:
 //   source:
 //     A System.Net.Http.Headers.ContentDispositionHeaderValue.
 protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
 {
 }
        public void Name_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten()
        {
            ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            NameValueHeaderValue name = new NameValueHeaderValue("NAME", "old_name");
            contentDisposition.Parameters.Add(name);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("NAME", contentDisposition.Parameters.First().Name);

            contentDisposition.Name = "new_name";
            Assert.Equal("new_name", contentDisposition.Name);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("NAME", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(name);
            Assert.Null(contentDisposition.Name);
        }
        public void Equals_UseContentDispositionWithAndWithoutParameters_EqualOrNotEqualNoExceptions()
        {
            ContentDispositionHeaderValue contentDisposition1 = new ContentDispositionHeaderValue("inline");
            ContentDispositionHeaderValue contentDisposition2 = new ContentDispositionHeaderValue("inline");
            contentDisposition2.Name = "myName";
            ContentDispositionHeaderValue contentDisposition3 = new ContentDispositionHeaderValue("inline");
            contentDisposition3.Parameters.Add(new NameValueHeaderValue("name", "value"));
            ContentDispositionHeaderValue contentDisposition4 = new ContentDispositionHeaderValue("INLINE");
            ContentDispositionHeaderValue contentDisposition5 = new ContentDispositionHeaderValue("INLINE");
            contentDisposition5.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME"));
            ContentDispositionHeaderValue contentDisposition6 = new ContentDispositionHeaderValue("INLINE");
            contentDisposition6.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME"));
            contentDisposition6.Parameters.Add(new NameValueHeaderValue("custom", "value"));
            ContentDispositionHeaderValue contentDisposition7 = new ContentDispositionHeaderValue("attachment");

            Assert.False(contentDisposition1.Equals(contentDisposition2)); // "No params vs. name."
            Assert.False(contentDisposition2.Equals(contentDisposition1)); // "name vs. no params."
            Assert.False(contentDisposition1.Equals(null)); // "No params vs. <null>."
            Assert.False(contentDisposition1.Equals(contentDisposition3)); // "No params vs. custom param."
            Assert.False(contentDisposition2.Equals(contentDisposition3)); // "name vs. custom param."
            Assert.True(contentDisposition1.Equals(contentDisposition4)); // "Different casing."
            Assert.True(contentDisposition2.Equals(contentDisposition5)); // "Different casing in name."
            Assert.False(contentDisposition5.Equals(contentDisposition6)); // "name vs. custom param."
            Assert.False(contentDisposition1.Equals(contentDisposition7)); // "inline vs. text/other."
        }
        public void Clone_Call_CloneFieldsMatchSourceFields()
        {
            ContentDispositionHeaderValue source = new ContentDispositionHeaderValue("attachment");
            ContentDispositionHeaderValue clone = (ContentDispositionHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.DispositionType, clone.DispositionType);
            Assert.Equal(0, clone.Parameters.Count);

            source.Name = "myName";
            clone = (ContentDispositionHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.DispositionType, clone.DispositionType);
            Assert.Equal("myName", clone.Name);
            Assert.Equal(1, clone.Parameters.Count);

            source.Parameters.Add(new NameValueHeaderValue("custom", "customValue"));
            clone = (ContentDispositionHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.DispositionType, clone.DispositionType);
            Assert.Equal("myName", clone.Name);
            Assert.Equal(2, clone.Parameters.Count);
            Assert.Equal("custom", clone.Parameters.ElementAt(1).Name);
            Assert.Equal("customValue", clone.Parameters.ElementAt(1).Value);
        }
 public void Parameters_AddNull_Throw()
 {
     ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");
     Assert.Throws<ArgumentNullException>(() => { contentDisposition.Parameters.Add(null); });
 }
		public static bool TryParse (string input, out ContentDispositionHeaderValue parsedValue)
		{
			parsedValue = null;

			var lexer = new Lexer (input);
			var t = lexer.Scan ();
			if (t.Kind != Token.Type.Token)
				return false;

			List<NameValueHeaderValue> parameters = null;
			var type = lexer.GetStringValue (t);

			t = lexer.Scan ();

			switch (t.Kind) {
			case Token.Type.SeparatorSemicolon:
				if (!NameValueHeaderValue.TryParseParameters (lexer, out parameters, out t) || t != Token.Type.End)
					return false;
				break;
			case Token.Type.End:
				break;
			default:
				return false;
			}

			parsedValue = new ContentDispositionHeaderValue () {
				dispositionType = type,
				parameters = parameters
			};

			return true;
		}
        public void Size_InvalidSizes_PropertyFails()
        {
            ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            NameValueHeaderValue sizeParameter = new NameValueHeaderValue("SIZE", "-279172874239");
            contentDisposition.Parameters.Add(sizeParameter);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
            Assert.Null(contentDisposition.Size);

            // Negatives not allowed
            Assert.Throws<ArgumentOutOfRangeException>(() => { contentDisposition.Size = -279172874240; });
            
            Assert.Null(contentDisposition.Size);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(sizeParameter);
            Assert.Null(contentDisposition.Size);
        }
示例#30
0
        /// <summary>
        /// Upload file
        /// </summary>
        /// <param name='fileContent'>
        /// File to upload.
        /// </param>
        /// <param name='fileName'>
        /// File name to upload. Name has to be spelled exactly as written here.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <Stream> > UploadFileWithHttpMessagesAsync(Stream fileContent, string fileName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (fileContent == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "fileContent");
            }
            if (fileName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "fileName");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("fileContent", fileContent);
                tracingParameters.Add("fileName", fileName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();
            // Create HTTP transport objects
            var _httpRequest = new System.Net.Http.HttpRequestMessage();

            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent();
            if (fileContent != null)
            {
                System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent);
                _fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                FileStream _fileContentAsFileStream = fileContent as FileStream;
                if (_fileContentAsFileStream != null)
                {
                    System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                    _contentDispositionHeaderValue.Name     = "fileContent";
                    _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name;
                    _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue;
                }
                _multiPartContent.Add(_fileContent, "fileContent");
            }
            if (fileName != null)
            {
                System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_fileName, "fileName");
            }
            _httpRequest.Content = _multiPartContent;
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <Stream>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
		public void Properties_FileName ()
		{
			var value = new ContentDispositionHeaderValue ("a");

			value.FileName = "aa";
			Assert.AreEqual ("aa", value.FileName, "#1");
			Assert.AreEqual (new NameValueHeaderValue ("filename", "aa"), value.Parameters.First (), "#2");

			value.FileName = "č";
			Assert.AreEqual ("č", value.FileName, "#11");
			Assert.AreEqual (new NameValueHeaderValue ("filename", "\"=?utf-8?B?xI0=?=\""), value.Parameters.First (), "#12");

			value.FileName = "(@)";
			Assert.AreEqual ("\"(@)\"", value.FileName, "#21");
			Assert.AreEqual (new NameValueHeaderValue ("filename", "\"(@)\""), value.Parameters.First (), "#22");
		}
        protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
        {
            Contract.Requires(source != null);

            _dispositionType = source._dispositionType;

            if (source._parameters != null)
            {
                foreach (var parameter in source._parameters)
                {
                    this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
                }
            }
        }
		public void Properties_ModificationDate ()
		{
			var value = new ContentDispositionHeaderValue ("a");

			value.ModificationDate = new DateTimeOffset (2010, 12, 30, 22, 34, 2, TimeSpan.Zero); //.FromHours (-3));
			Assert.AreEqual (new DateTimeOffset (2010, 12, 30, 22, 34, 2, TimeSpan.Zero), value.ModificationDate, "#1");
			Assert.AreEqual (new NameValueHeaderValue ("modification-date", "\"Thu, 30 Dec 2010 22:34:02 GMT\""), value.Parameters.First (), "#2");
		}
        public static bool TryParse(string input, out ContentDispositionHeaderValue parsedValue)
        {
            int index = 0;
            object output;
            parsedValue = null;

            if (GenericHeaderParser.ContentDispositionParser.TryParseValue(input, null, ref index, out output))
            {
                parsedValue = (ContentDispositionHeaderValue)output;
                return true;
            }
            return false;
        }
示例#35
0
        public HttpResponseMessage DownloadByDay(DateTimeInfo dateTime)
        {
            var Teams = TeamNameConverter.Teams;
            var Squads = SquadNameConverter.Squads;
            try
            {
                var temp = UnixTimeStampToDateTime(dateTime.DateTimeUnix);
                var q = core.GetMessagesFromDate(temp);
                const string messageFmt = @"[{0}] [{1}] {2}:  {3}";
                var stream = new MemoryStream();
                var writer = new StreamWriter(stream);

                foreach (var message in q)
                {
                    message.MessageType = message.MessageType.ToUpperInvariant();
                    foreach (var teamPair in Teams)
                    {
                        message.MessageType = message.MessageType.Replace(teamPair.Key, teamPair.Value);
                    }

                    foreach (var squadPair in Squads)
                    {
                        message.MessageType = message.MessageType.Replace(squadPair.Key, squadPair.Value);
                    }

                    writer.Write(String.Format(messageFmt, message.MessageTimeStamp, message.MessageType,
                                               message.Speaker,
                                               message.Text) + "\n");
                }
                writer.Flush();
                stream.Position = 0;

                var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) };
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
                var disposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName =
                        string.Format("{0}.txt",
                                      temp.ToString(
                                          "yyyyMMdd"))
                };

                result.Content.Headers.ContentDisposition = disposition;

                return result;
            }
            catch (Exception)
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }
        public void Parse_SetOfValidValueStrings_ParsedCorrectly()
        {
            ContentDispositionHeaderValue expected = new ContentDispositionHeaderValue("inline");
            CheckValidParse("\r\n inline  ", expected);
            CheckValidParse("inline", expected);

            // We don't have to test all possible input strings, since most of the pieces are handled by other parsers.
            // The purpose of this test is to verify that these other parsers are combined correctly to build a 
            // Content-Disposition parser.
            expected.Name = "myName";
            CheckValidParse("\r\n inline  ;  name =   myName ", expected);
            CheckValidParse("  inline;name=myName", expected);

            expected.Name = null;
            expected.DispositionType = "attachment";
            expected.FileName = "foo-ae.html";
            expected.Parameters.Add(new NameValueHeaderValue("filename*", "UTF-8''foo-%c3%a4.html"));
            CheckValidParse(@"attachment; filename*=UTF-8''foo-%c3%a4.html; filename=foo-ae.html", expected);
        }