How to Add an Attachment to a User Story using Rally REST .NET

Posted by user1373451 on Stack Overflow See other posts from Stack Overflow or by user1373451
Published on 2012-07-09T03:04:28Z Indexed on 2012/07/09 3:15 UTC
Read the original article Hit count: 363

Filed under:
|
|

We're in the process of porting our .NET Rally code from SOAP to the REST .NET API. One thing I'm looking to replicate is the ability to upload attachments. I'm following a very similar procedure as to the one outlined in this posting:

Rally SOAP API - How do I add an attachment to a Hierarchical Requirement

Whereby the image is read into a System.Drawing.Image. We use the ImageToBase64 function to convert the image to a byte array which then gets assigned to the AttachmentContent, which is created first.

Then, the Attachment gets created, and wired up to both AttachmentContent, and the HierarchicalRequirement.

All of the creation events work great. A new attachment called "Image.png" gets created on the Story. However, when I download the resulting attachment from Rally, Image.png has zero bytes! I've tried this with different images, JPEG's, PNG's, etc. all with the same results.

An excerpt of the code showing the process is included below. Is there something obvious that I'm missing? Thanks in advance.

    // .... Read content into a System.Drawing.Image....

    // Convert Image to Base64 format
    byte[] imageBase64Format = ImageToBase64(imageObject, System.Drawing.Imaging.ImageFormat.Png);
    var imageLength = imageBase64Format.Length;

    // AttachmentContent
    DynamicJsonObject attachmentContent = new DynamicJsonObject();
    attachmentContent["Content"] = imageBase64Format;

    CreateResult cr = restApi.Create("AttachmentContent", myAttachmentContent);
    String contentRef = cr.Reference;
    Console.WriteLine("Created: " + contentRef);

    // Tee up attachment
    DynamicJsonObject newAttachment = new DynamicJsonObject();
    newAttachment["Artifact"] = story;
    newAttachment["Content"] = attachmentContent;
    newAttachment["Name"] = "Image.png";
    newAttachment["ContentType"] = "image/png";
    newAttachment["Size"] = imageLength;
    newAttachment["User"] = user;

    cr = restApi.Create("Attachment", newAttachment);

    String attachRef = attachRef.Reference;
    Console.WriteLine("Created: " + attachRef);

}

public static byte[] ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
    using (MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, format);

        // Convert Image to byte[]                
        byte[] imageBytes = ms.ToArray();
        return imageBytes;
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about rest