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

I have followed this code to add attachment to a HierarchicalRequirement.
I get the following error:
validation error: Attachment.attachments[0] should not be null
How do I add an attachment to a Hierarchical Requirement?

Can you post a code excerpt that illustrates the problem? If you followed the approach in Rally SOAP API - How do I add an attachment to a TestCaseResult you're on the right track. Following is a quick code sample that works for me when adding an attachment to a story:
// issue query for target story
QueryResult queryResult = service.query(workspace, objectType, queryString, orderString, fetchFullObjects, start, pageSize);
// look at the object returned from query()
Console.WriteLine("Query returned " + queryResult.TotalResultCount + " objects");
// Grab the resulting story
DomainObject rallyObject = queryResult.Results.First();
HierarchicalRequirement queryStory = (HierarchicalRequirement)rallyObject;
// Read In Image Content
String imageFilePath = "C:\\Users\\username\\";
String imageFileName = "image1.png";
String fullImageFile = imageFilePath + imageFileName;
var imageFileLength = new FileInfo(fullImageFile).Length;
Image myImage = Image.FromFile(fullImageFile);
Console.WriteLine("Image File Length: " + imageFileLength);
// Convert Image to Byte Array format
byte[] imageByteArray = ImageToByteArray(myImage, System.Drawing.Imaging.ImageFormat.Png);
var imageNumberBytes = imageByteArray.Length;
// Create the Attachment Content
AttachmentContent attachmentContent = new AttachmentContent();
attachmentContent.Content = imageByteArray;
attachmentContent.Workspace = workspace;
CreateResult result = service.create(attachmentContent);
attachmentContent = (AttachmentContent)result.Object;
// Create the Attachment Container, wire it up to the AttachmentContent
Attachment myAttachment = new Attachment();
myAttachment.ContentType = "image/png";
myAttachment.Content = attachmentContent;
myAttachment.Name = "image1.png";
myAttachment.Size = imageNumberBytes ;
myAttachment.SizeSpecified = true;
myAttachment.User = user;
myAttachment.Artifact = queryStory;
myAttachment.Workspace = workspace;
// Create the attachment in Rally
result = service.create(myAttachment);
Console.WriteLine(result.Object);
}
public static byte[] ImageToByteArray (Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
return imageBytes;
}
}
}

Related

Generate PDF with arabic text inside grid cell

I need to generate a PDF that contains a table with data in both English and arabic languages in xamarin.forms. I've been searching a lot. I found the syncfusion documentation and tried to apply it. This one doesn't include a grid but it tells how to add a simple arabic text: https://blog.syncfusion.com/blogs/post/adding-rtl-support-to-your-pdf-in-xamarin.aspx this one worked. So I tried to use it and make modifications to add a grid. This is what I wrote in the main.xaml.cs:
private void btn_Clicked(object sender, EventArgs e)
{
PdfDocument doc = new PdfDocument();
//Add a page.
PdfPage page = doc.Pages.Add();
//Create a PdfGrid.
Syncfusion.Pdf.Grid.PdfGrid pdfGrid = new Syncfusion.Pdf.Grid.PdfGrid();
//Add values to list
List<object> data = new List<object>();
Object row1 = new { ID = "E01", Name = "رنا" };
Object row2 = new { ID = "E02", Name = "رامي" };
Object row3 = new { ID = "E03", Name = "Andrew" };
Object row4 = new { ID = "E04", Name = "Paul" };
Object row5 = new { ID = "E05", Name = "Gray" };
data.Add(row1);
data.Add(row2);
data.Add(row3);
data.Add(row4);
data.Add(row5);
//Add list to IEnumerable
IEnumerable<object> dataTable = data;
//Assign data source.
pdfGrid.DataSource = dataTable;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new PointF(10, 10));
//Save the PDF document to stream.
MemoryStream ms = new MemoryStream();
//Create a new PDF document.
//Add a new PDF page.
//Load font.
Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("RTLDemo.Assets.arial.ttf");
//Create PDF true type font.
PdfFont pdfFont = new PdfTrueTypeFont(fontStream, 12);
//String format
PdfStringFormat format = new PdfStringFormat();
//Set the format as right to left.
format.TextDirection = PdfTextDirection.RightToLeft;
//Set the alignment.
format.Alignment = PdfTextAlignment.Right;
SizeF pageSize = page.GetClientSize();
PdfGridCell pdfGridCell = new PdfGridCell();
PdfGridCellStyle style = new PdfGridCellStyle();
style.Font = pdfFont;
style.StringFormat.TextDirection = format.TextDirection;
//Set style to grid
pdfGridCell.Style = style;
//Save the document.
doc.Save(ms);
//Close the document
doc.Close(true);
ms.Position = 0;
if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("RTLText.pdf", "application/pdf", ms);
else
Xamarin.Forms.DependencyService.Get<ISave>().Save("RTLText.pdf", "application/pdf", ms);
}
I keep getting an exception: System.NullReferenceException:** 'Object reference not set to an instance of an object.' on the style.StringFormat.TextDirection = format.TextDirection; line. I followed the steps in this document: https://www.syncfusion.com/forums/135954/how-to-create-unicode-font-with-pdftruetypefont-or-the-proper-way-to-draw-a-unicode-string I tried a lot of things but nothing is wroking. What should I do?
Update:
i replaced the code above with a new code:
PdfDocument doc = new PdfDocument();
//Add a page.
PdfPage page = doc.Pages.Add();
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
//Create a DataTable.
DataTable dataTable = new DataTable();
//Add columns to the DataTable
dataTable.Columns.Add("ID");
dataTable.Columns.Add("Name");
//Add rows to the DataTable.
dataTable.Rows.Add(new object[] { "E01", "رنا" });
dataTable.Rows.Add(new object[] { "E02", "Thomas" });
//Assign data source.
pdfGrid.DataSource = dataTable;
//Using the Column collection
pdfGrid.Columns[0].Width = 100;
//Adding grid cell style
PdfGridCellStyle cellStyle = new PdfGridCellStyle();
//Create new PDF string format instance.
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
format.TextDirection = PdfTextDirection.RightToLeft;
//Set string format to grid cell.
cellStyle.StringFormat = format;
//Set borders.
PdfBorders borders = new PdfBorders();
borders.All = PdfPens.Red;
cellStyle.Borders = borders;
//Set background image.
Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("RTLDemo.Assets.arial.ttf");
PdfFont pdfFont = new PdfTrueTypeFont(fontStream, 12);
cellStyle.Font = pdfFont;
//Set cell paddings.
cellStyle.CellPadding = new PdfPaddings(5, 5, 5, 5);
//Applying style to grid
pdfGrid.Rows[0].Cells[0].Style = cellStyle;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new PointF(10, 10));
MemoryStream ms = new MemoryStream();
//Save the document.
doc.Save(ms);
//Close the document
doc.Close(true);
ms.Position = 0;
if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("RTLText.pdf", "application/pdf", ms);
else
Xamarin.Forms.DependencyService.Get<ISave>().Save("RTLText.pdf", "application/pdf", ms);
the previous exception didn't appear, the pdf was generated but the arabic text didn't appear, what am i missing?
We can draw RTL text in PDF grid with Syncfusion PDF library in Xamarin.Forms application. Please find the sample code below,
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a new PDF page.
PdfPage page = document.Pages.Add();
//Get the font file as stream.
Stream fontStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("UnicodeText.Assets.arial.ttf");
//Create a new PdfTrueTypeFont instance.
PdfTrueTypeFont font = new PdfTrueTypeFont(fontStream, 14);
//Create a new bold stylePdfTrueTypeFont instance.
PdfTrueTypeFont boldFont = new PdfTrueTypeFont(fontStream, 14, PdfFontStyle.Bold);
page.Graphics.DrawString("PdfGrid", boldFont, PdfBrushes.Black, PointF.Empty);
//Create PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
//Add values to list
List<object> data = new List<object>();
data.Add(new { ID = "E01", Name = "رنا" });
data.Add(new { ID = "E02", Name = "رامي" });
data.Add(new { ID = "E03", Name = "Andrew" });
data.Add(new { ID = "E04", Name = "Paul" });
data.Add(new { ID = "E05", Name = "Clay" });
//Add list to IEnumerable.
IEnumerable<object> dataTable = data;
//Assign data source.
pdfGrid.DataSource = dataTable;
//Assign bold font to pdfGrid header.
pdfGrid.Headers[0].Style.Font = boldFont;
//Assign font to PdfGrid.
pdfGrid.Style.Font = font;
//Create String format with RTL text direction and center text alignment.
PdfStringFormat format = new PdfStringFormat();
format.TextDirection = PdfTextDirection.RightToLeft;
format.Alignment = PdfTextAlignment.Center;
//Assign string format to draw RTL text with center alsignment
pdfGrid.Rows[0].Cells[1].StringFormat = format;
pdfGrid.Rows[1].Cells[1].StringFormat = format;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, 20));
MemoryStream stream = new MemoryStream();
//Save the document.
document.Save(stream);
//Close the document.
document.Close(true);
Please find the sample from https://www.syncfusion.com/downloads/support/directtrac/general/ze/UnicodeText1046384115. Please find the sample output PDF created from https://www.syncfusion.com/downloads/support/directtrac/general/ze/Output-609045962.
Note: String format assigned in your sample is not applied on corresponding PDF grid cell which having Arabic text. We have to provide cell index as 1 as per the sample code provided.
this is taken directly from the documentation
//Adding grid cell style
PdfGridCellStyle cellStyle = new PdfGridCellStyle();
//Create new PDF string format instance.
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
//Set string format to grid cell.
cellStyle.StringFormat = format;

I am trying to use microsoft cognitive search api for web results

final String accountKey = "***********************";
final String bingUrlPattern ="https://api.cognitive.microsoft.com/bing/v5.0/search?q=bill gates";
String query = URLEncoder.encode("'what is omonoia'", Charset.defaultCharset().name());
String bingUrl = String.format(bingUrlPattern, query);
String accountKeyEnc = Base64.getEncoder().encodeToString((accountKey + ":" + accountKey).getBytes());
URL url = new URL(bingUrl);
URLConnection connection = url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
JSONObject json = new JSONObject(response.toString());
JSONObject d = json.getJSONObject("d");
JSONArray results = d.getJSONArray("results");
int resultsLength = results.length();
for (int i = 0; i < resultsLength; i++) {
final JSONObject aResult = results.getJSONObject(i);
System.out.println(aResult.get("Url"));
}
}
}
Code returns 400 error code while execution.
It seems format of url pattern is wrong. Please suggest.
Also how can can specify format to be in JSON.
You are specifying your auth incorrectly. You'll want the following instead:
connection.setRequestProperty("Ocp-Apim-Subscription-Key", accountKey);
You'll also want to change how the URL is constructed, since you've hard-coded the query to 'bill gates'.
final String bingUrlPattern ="https://api.cognitive.microsoft.com/bing/v5.0/search?q=%s";
You may find the API console helpful.

How can I pass a notification to multiple users with GCM?

I am trying :
private void GcmPushNotification(string deviceId)
{
string message="New post from Admin";
string GoogleAppID = "AIzaSyCYesJ5dCK8-O-tf8ZxADELQx5e05P-l5I";
var SENDER_ID = "854837747831";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
// --- text
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
If you want to send the same notification to multiple devices (up to 1000 registration IDs), you have to use the JSON request format instead of the URL encoded you are currently using.
For example (taken from here):
Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
"data" : {
...
},
}

How to create a single-color Bitmap to display a given hue?

I have a requirement to create an image based on a certain color. The color will vary and so will the size of the output image. I want to create the Bitmap and save it to the app's temporary folder. How do I do this?
My initial requirement came from a list of colors, and providing a sample of the color in the UI. If the size of the image is variable then I can create them for certain scenarios like result suggestions in the search pane.
This isn't easy. But it's all wrapped in this single method for you to use. I hope it helps. ANyway, here's the code to create a Bitmap based on a given color & size:
private async System.Threading.Tasks.Task<Windows.Storage.StorageFile> CreateThumb(Windows.UI.Color color, Windows.Foundation.Size size)
{
// create colored bitmap
var _Bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)size.Width, (int)size.Height);
byte[] _Pixels = new byte[4 * _Bitmap.PixelWidth * _Bitmap.PixelHeight];
for (int i = 0; i < _Pixels.Length; i += 4)
{
_Pixels[i + 0] = color.B;
_Pixels[i + 1] = color.G;
_Pixels[i + 2] = color.R;
_Pixels[i + 3] = color.A;
}
// update bitmap data
// using System.Runtime.InteropServices.WindowsRuntime;
using (var _Stream = _Bitmap.PixelBuffer.AsStream())
{
_Stream.Seek(0, SeekOrigin.Begin);
_Stream.Write(_Pixels, 0, _Pixels.Length);
_Bitmap.Invalidate();
}
// determine destination
var _Folder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
var _Name = color.ToString().TrimStart('#') + ".png";
// use existing if already
Windows.Storage.StorageFile _File;
try { return await _Folder.GetFileAsync(_Name); }
catch { /* do nothing; not found */ }
_File = await _Folder.CreateFileAsync(_Name, Windows.Storage.CreationCollisionOption.ReplaceExisting);
// extract stream to write
// using System.Runtime.InteropServices.WindowsRuntime;
using (var _Stream = _Bitmap.PixelBuffer.AsStream())
{
_Pixels = new byte[(uint)_Stream.Length];
await _Stream.ReadAsync(_Pixels, 0, _Pixels.Length);
}
// write file
using (var _WriteStream = await _File.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var _Encoder = await Windows.Graphics.Imaging.BitmapEncoder
.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, _WriteStream);
_Encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied,
(uint)_Bitmap.PixelWidth, (uint)_Bitmap.PixelHeight, 96, 96, _Pixels);
await _Encoder.FlushAsync();
using (var outputStream = _WriteStream.GetOutputStreamAt(0))
await outputStream.FlushAsync();
}
return _File;
}
Best of luck!

How to get the list of unsubscribers emails from mailchimp

I want to get the emails of unsubscribers the code below returning the count that how many of it are there but how could i get the List of unsubscribers from output variable...
Here is my full code::
private List<campaignUnsubscribesResults.Unsubscribes> Unsubscribers = new List<campaignUnsubscribesResults.Unsubscribes>();
private void GetUnsubscribers(string apikey, string MailChimpCampaignID)
{
campaignUnsubscribesInput input = new campaignUnsubscribesInput();
input.api_AccessType = PerceptiveMCAPI.EnumValues.AccessType.Serial;
input.api_CustomErrorMessages = true;
input.api_MethodType = PerceptiveMCAPI.EnumValues.MethodType.POST;
input.api_Validate = true;
input.api_OutputType = PerceptiveMCAPI.EnumValues.OutputType.XML;
input.parms.apikey = apikey;
input.parms.cid = MailChimpCampaignID;
//input.parms.start = PageIndex;
//input.parms.limit = PageSize;
campaignUnsubscribes unsubscribe = new campaignUnsubscribes();
campaignUnsubscribesOutput output = unsubscribe.Execute(input);
Unsubscribers.AddRange(output.result.data);
string unsubscriber = "0";
//ArrayList a = new ArrayList();
//a[0] = output.result.data.ToString();
//List<MCItem> lst = new List<MCItem>();
// foreach (listBatchUnsubscribeResults order in myArrayList)
//{
// orders.add(order);
//}
string[] unsubs;
//ArrayList [] list = new ArrayList [0];
foreach (listMembers list1 in output.result)
{
unsubscriber = list1.ToString();
}
string unsubscribers = Unsubscribers.Count.ToString();
Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", "<script language=JavaScript>alert('Unsubscribers:: '+ ' " + unsubscribers + " ');</script>");
//Unsubscribers.Reverse();
//dlUnsubscribes.DataSource = Unsubscribers.Take(10);
//dlUnsubscribes.DataBind();
//dlUnsubscribes.Visible = (Unsubscribers.Count > 0);
}
I would use Mailchimp Webhooks. You setup a page/script on your website which will get called by Mailchimp every time a particular event occurs. When it's an unsubscribe event, you can log the info you want to store to a database, file, etc.