2017-01-09 11 views
1

Я ссылаюсь на другие примеры на этом сайте, но обнаружил существенное различие в моем методе. (Пожалуйста, будьте терпеливы)Rally C#: Как загрузить коллекцию вложений и связать с историей пользователя?

Я пытаюсь выполнить итерацию по каталогу файлов и загрузить каждый файл в качестве вложения и связать историю пользователей. Я могу только прикрепить 1 файл для истории пользователя. Я вижу, что каждое вложение должно быть закодировано до базовой строки 64 и должно иметь размер в байтах.

Вот мой код до сих пор:

public void createUsWithAttachmentList(string workspace, string project, string userStoryName, string userStoryDescription) 
    { 

     //authentication 
     this.EnsureRallyIsAuthenticated(); 

     //DynamicJSONObject for AttachmentContent 
     DynamicJsonObject myAttachmentContent = new DynamicJsonObject(); 

     //Length calculated from Base64String converted back 
     int imageNumberBytes = 0; 

     //Userstory setup 
     DynamicJsonObject toCreate = new DynamicJsonObject(); 
     toCreate["Workspace"] = workspace; 
     toCreate["Project"] = project; 
     toCreate["Name"] = userStoryName; 
     toCreate["Description"] = userStoryDescription; 

     //Trying to get a list of all the file paths within a given directory, this directory would contain .png files that need to be associated to a user story. 
     string[] attachmentPath = Directory.GetFiles("C:\\Users\\user\\Desktop\\RallyAttachments"); 

Это Еогеасп петля сбивает с толку. Я пытаюсь перебрать каждый файл в каталоге, чтобы преобразовать его в строку base64 и в то же время получить количество байтов для каждого файла в виде int.

 foreach (string fileName in attachmentPath) 
     { 
      Image myImage = Image.FromFile(fileName); 
      string imageBase64String = imageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Png); 
      imageNumberBytes = Convert.FromBase64String(imageBase64String).Length; 

      //I am stuck here to be exact because there are multiple imageBase64Strings due to the collection of files located inside the directory. AND the below line is wrong because I have a list of imageBase64Strings that were generated from iterating through the string[] attachmentPath. 
      myAttachmentContent[RallyField.content] = imageBase64String; 
     } 

     try 
     { 
      //create user story 
      CreateResult createUserStory = _api.Create(RallyField.attachmentContent, myAttachmentContent); 
      //create attachment 
      CreateResult myAttachmentContentCreateResult = _api.Create(RallyField.attachmentContent, myAttachmentContent); 
      String myAttachmentContentRef = myAttachmentContentCreateResult.Reference; 

      //DynamicJSONObject for Attachment Container 
      //I assume I would need a separate container for each file in my directory containing the attachments. 
      DynamicJsonObject myAttachment = new DynamicJsonObject(); 
      myAttachment["Artifact"] = createUserStory.Reference; 
      myAttachment["Content"] = myAttachmentContentRef; 
      myAttachment["Name"] = "AttachmentFromREST.png"; 
      myAttachment["Description"] = "Email Attachment"; 
      myAttachment["ContentType"] = "image/png"; 
      myAttachment["Size"] = imageNumberBytes; 

      //create & associate the attachment 
      CreateResult myAttachmentCreateResult = _api.Create(RallyField.attachment, myAttachment); 
      Console.WriteLine("Created User Story: " + createUserStory.Reference); 
     } 
     catch (WebException e) 
     { 
      Console.WriteLine(e.Message); 
     } 
    } 

Примечание: Я планирую расширить этот метод для поддержки нескольких типов файлов, и я, что я должен был бы получить тип каждого файла в каталоге и действовать соответствующим образом. Любые идеи о том, как это сделать?

ответ

1

У вас есть все реализованные детали - нам просто нужно немного переместить его. Создайте историю один раз в начале, а затем каждый раз через цикл создайте новый AttachmentContent и новое вложение для каждого файла.

public void createUsWithAttachmentList(string workspace, string project, string userStoryName, string userStoryDescription) 
{ 

    //authentication 
    this.EnsureRallyIsAuthenticated(); 

    //Userstory setup 
    DynamicJsonObject toCreate = new DynamicJsonObject(); 
    toCreate["Workspace"] = workspace; 
    toCreate["Project"] = project; 
    toCreate["Name"] = userStoryName; 
    toCreate["Description"] = userStoryDescription; 

    //Create the story first 
    try 
    { 
     //create user story 
     CreateResult createUserStory = _api.Create(RallyField.userStory, toCreate); 


     //now loop over each file 
     string[] attachmentPath = Directory.GetFiles("C:\\Users\\user\\Desktop\\RallyAttachments"); 

     foreach (string fileName in attachmentPath) 
     { 
      //DynamicJSONObject for AttachmentContent 
      DynamicJsonObject myAttachmentContent = new DynamicJsonObject(); 
      Image myImage = Image.FromFile(fileName); 
      string imageBase64String = imageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Png); 
      int imageNumberBytes = Convert.FromBase64String(imageBase64String).Length; 
      myAttachmentContent[RallyField.content] = imageBase64String; 

      //create the AttachmentConent 
      CreateResult myAttachmentContentCreateResult = _api.Create(RallyField.attachmentContent, myAttachmentContent); 
      String myAttachmentContentRef = myAttachmentContentCreateResult.Reference; 

      //create an Attachment to associate to story 
      DynamicJsonObject myAttachment = new DynamicJsonObject(); 
      myAttachment["Artifact"] = createUserStory.Reference; 
      myAttachment["Content"] = myAttachmentContentRef; 
      myAttachment["Name"] = "AttachmentFromREST.png"; 
      myAttachment["Description"] = "Email Attachment"; 
      myAttachment["ContentType"] = "image/png"; 
      myAttachment["Size"] = imageNumberBytes; 

      //create & associate the attachment 
      CreateResult myAttachmentCreateResult = _api.Create(RallyField.attachment, myAttachment); 
     }  
    } 
    catch (WebException e) 
    { 
     Console.WriteLine(e.Message); 
    } 
} 
+0

Можно ли нажимать zipped-каталог в Rally в качестве приложения. Если это так, вы можете указать любые указатели. Я начинаю думать, что он должен быть закодирован int base 64 string. –

+0

Почтовый файл является допустимым типом вложения. Вы правильно - контент должен быть закодирован в base4. –