Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement MultipartBody filename #213

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- `MultipartBody` now supports an optional `fileName` parameter to specify the file name of the part. (https://github.com/microsoft/kiota-abstractions-dotnet/issues/212)

## [1.8.0] - 2024-03-18

### Added
Expand Down
68 changes: 68 additions & 0 deletions Microsoft.Kiota.Abstractions.Tests/MultipartBodyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using Microsoft.Kiota.Abstractions.Serialization;
using Moq;
using Xunit;

namespace Microsoft.Kiota.Abstractions.Tests;

public class MultipartBodyTests
{
[Fact]
public void KeepsFilename()
{
var writerMock = new Mock<ISerializationWriter>();
var requestAdapterMock = new Mock<IRequestAdapter>();
var serializationFactoryMock = new Mock<ISerializationWriterFactory>();

var body = new MultipartBody();

requestAdapterMock
.Setup(r => r.SerializationWriterFactory)
.Returns(serializationFactoryMock.Object);

body.RequestAdapter = requestAdapterMock.Object;

writerMock.Setup(w => w.WriteStringValue("", "--" + body.Boundary));
writerMock.Setup(w => w.WriteStringValue("Content-Type", "application/json"));
writerMock.Setup(w => w.WriteStringValue("Content-Disposition", "form-data; name=\"file\"; filename=\"file.json\""));
writerMock.Setup(w => w.WriteStringValue("", "fileContent"));
writerMock.Setup(w => w.WriteStringValue("", ""));
writerMock.Setup(w => w.WriteStringValue("", "--" + body.Boundary + "--"));

body.AddOrReplacePart("file", "application/json", "fileContent", "file.json");
body.Serialize(writerMock.Object);

writerMock.VerifyAll();
requestAdapterMock.VerifyAll();
serializationFactoryMock.VerifyAll();
}

[Fact]
public void WorksWithoutFilename()
{
var writerMock = new Mock<ISerializationWriter>();
var requestAdapterMock = new Mock<IRequestAdapter>();
var serializationFactoryMock = new Mock<ISerializationWriterFactory>();

var body = new MultipartBody();

requestAdapterMock
.Setup(r => r.SerializationWriterFactory)
.Returns(serializationFactoryMock.Object);

body.RequestAdapter = requestAdapterMock.Object;

writerMock.Setup(w => w.WriteStringValue("", "--" + body.Boundary));
writerMock.Setup(w => w.WriteStringValue("Content-Type", "application/json"));
writerMock.Setup(w => w.WriteStringValue("Content-Disposition", "form-data; name=\"file\""));
writerMock.Setup(w => w.WriteStringValue("", "fileContent"));
writerMock.Setup(w => w.WriteStringValue("", ""));
writerMock.Setup(w => w.WriteStringValue("", "--" + body.Boundary + "--"));

body.AddOrReplacePart("file", "application/json", "fileContent");
body.Serialize(writerMock.Object);

writerMock.VerifyAll();
requestAdapterMock.VerifyAll();
serializationFactoryMock.VerifyAll();
}
}
2 changes: 1 addition & 1 deletion src/Microsoft.Kiota.Abstractions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<PackageProjectUrl>https://aka.ms/kiota/docs</PackageProjectUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<Deterministic>true</Deterministic>
<VersionPrefix>1.8.0</VersionPrefix>
<VersionPrefix>1.8.1</VersionPrefix>
<VersionSuffix></VersionSuffix>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<SignAssembly>false</SignAssembly>
Expand Down
69 changes: 53 additions & 16 deletions src/MultipartBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;

Expand All @@ -32,7 +33,8 @@ public class MultipartBody : IParsable
/// <param name="partName">The name of the part.</param>
/// <param name="contentType">The content type of the part.</param>
/// <param name="partValue">The value of the part.</param>
public void AddOrReplacePart<T>(string partName, string contentType, T partValue)
/// <param name="fileName">An optional file name for the part.</param>
public void AddOrReplacePart<T>(string partName, string contentType, T partValue, string? fileName = null)
{
if(string.IsNullOrEmpty(partName))
{
Expand All @@ -46,7 +48,7 @@ public void AddOrReplacePart<T>(string partName, string contentType, T partValue
{
throw new ArgumentNullException(nameof(partValue));
}
var value = new Tuple<string, object>(contentType, partValue);
var value = new Part(partName, partValue, contentType, fileName);
if(!_parts.TryAdd(partName, value))
{
_parts[partName] = value;
Expand All @@ -66,7 +68,10 @@ public void AddOrReplacePart<T>(string partName, string contentType, T partValue
}
if(_parts.TryGetValue(partName, out var value))
{
return (T)value.Item2;
if(value == null)
return default;

return (T)value.Content;
}
return default;
}
Expand All @@ -83,7 +88,8 @@ public bool RemovePart(string partName)
}
return _parts.Remove(partName);
}
private readonly Dictionary<string, Tuple<string, object>> _parts = new Dictionary<string, Tuple<string, object>>(StringComparer.OrdinalIgnoreCase);

private readonly Dictionary<string, Part> _parts = new Dictionary<string, Part>(StringComparer.OrdinalIgnoreCase);
/// <inheritdoc />
public IDictionary<string, Action<IParseNode>> GetFieldDeserializers() => throw new NotImplementedException();
/// <inheritdoc />
Expand All @@ -102,7 +108,8 @@ public void Serialize(ISerializationWriter writer)
throw new InvalidOperationException("No parts to serialize");
}
var first = true;
foreach(var part in _parts)
var contentDispositionBuilder = new StringBuilder();
foreach(var part in _parts.Values)
{
try
{
Expand All @@ -112,12 +119,26 @@ public void Serialize(ISerializationWriter writer)
AddNewLine(writer);

writer.WriteStringValue(string.Empty, $"--{Boundary}");
writer.WriteStringValue("Content-Type", $"{part.Value.Item1}");
writer.WriteStringValue("Content-Disposition", $"form-data; name=\"{part.Key}\"");
writer.WriteStringValue("Content-Type", part.ContentType);

contentDispositionBuilder.Clear();
contentDispositionBuilder.Append("form-data; name=\"");
contentDispositionBuilder.Append(part.Name);
contentDispositionBuilder.Append("\"");

if (part.FileName != null)
{
contentDispositionBuilder.Append("; filename=\"");
contentDispositionBuilder.Append(part.FileName);
contentDispositionBuilder.Append("\"");
}

writer.WriteStringValue("Content-Disposition", contentDispositionBuilder.ToString());

AddNewLine(writer);
if(part.Value.Item2 is IParsable parsable)
if(part.Content is IParsable parsable)
{
using var partWriter = RequestAdapter.SerializationWriterFactory.GetSerializationWriter(part.Value.Item1);
using var partWriter = RequestAdapter.SerializationWriterFactory.GetSerializationWriter(part.ContentType);
partWriter.WriteObjectValue(string.Empty, parsable);
using var partContent = partWriter.GetSerializedContent();
if(partContent.CanSeek)
Expand All @@ -126,34 +147,34 @@ public void Serialize(ISerializationWriter writer)
partContent.CopyTo(ms);
writer.WriteByteArrayValue(string.Empty, ms.ToArray());
}
else if(part.Value.Item2 is string currentString)
else if(part.Content is string currentString)
{
writer.WriteStringValue(string.Empty, currentString);
}
else if(part.Value.Item2 is MemoryStream originalMemoryStream)
else if(part.Content is MemoryStream originalMemoryStream)
{
writer.WriteByteArrayValue(string.Empty, originalMemoryStream.ToArray());
}
else if(part.Value.Item2 is Stream currentStream)
else if(part.Content is Stream currentStream)
{
if(currentStream.CanSeek)
currentStream.Seek(0, SeekOrigin.Begin);
using var ms = new MemoryStream();
currentStream.CopyTo(ms);
writer.WriteByteArrayValue(string.Empty, ms.ToArray());
}
else if(part.Value.Item2 is byte[] currentBinary)
else if(part.Content is byte[] currentBinary)
{
writer.WriteByteArrayValue(string.Empty, currentBinary);
}
else
{
throw new InvalidOperationException($"Unsupported type {part.Value.Item2.GetType().Name} for part {part.Key}");
throw new InvalidOperationException($"Unsupported type {part.Content.GetType().Name} for part {part.Name}");
}
}
catch(InvalidOperationException) when(part.Value.Item2 is byte[] currentBinary)
catch(InvalidOperationException) when(part?.Content is byte[] currentBinary)
{ // binary payload
writer.WriteByteArrayValue(part.Key, currentBinary);
writer.WriteByteArrayValue(part.Name, currentBinary);
}
}
AddNewLine(writer);
Expand All @@ -163,4 +184,20 @@ private void AddNewLine(ISerializationWriter writer)
{
writer.WriteStringValue(string.Empty, string.Empty);
}

private class Part
{
public Part(string name, object content, string contentType, string? fileName)
{
this.Name = name;
this.Content = content;
this.ContentType = contentType;
this.FileName = fileName;
}

public string Name { get; }
public object Content { get; }
public string ContentType { get; }
public string? FileName { get; }
}
}
Loading