Add an attachment to Bugzilla using XML-RPC in VBA - c#

I am currently developing an Excel macro which allows creating Bugs in a Bugzilla instance.
After some trial and error this now turns out to work fine.
I wanted to enhance the client so that it's also possible to add screenshots to the newly created bug.
The environment I'm using is a little bit tricky:
I have to use MS Excel for my task.
As Excel does not understand XML-RPC, I downloaded an interface DLL (CookComputing.XmlRpcV2.dll from xml-rpc.net) which makes the XML-RPC interface accessible from .NET.
Then I created an additional DLL which can be called from Excel macros (using COM interop).
As already mentioned, this is working fine for tasks like browsing or adding new bugs.
But when adding an attachment to the bug, the image must be converted into a base64 data type. Although this seems to work fine and although the creation of the screenshot seems to succeed, the image seems to be corrupted and cannot be displayed.
Here's what I do to add the image:
The Bugzilla add_attachment method accepts a struct as input:
http://www.bugzilla.org/docs/4.0/en/html/api/Bugzilla/WebService/Bug.html#add_attachment.
This type was defined in C# and is visible also in VBA.
This is the struct definition:
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TAttachmentInputData
{
public string[] ids;
public string data; // base64-encoded data
public string file_name;
public string summary;
public string content_type;
public string comment;
public bool is_patch;
public bool is_private;
public void addId(int id)
{
ids = new string[1];
ids[0] = id.ToString();
}
public void addData(string strData)
{
try
{
byte[] encData_byte = new byte[strData.Length];
encData_byte = System.Text.Encoding.ASCII.GetBytes(strData);
string encodedData = Convert.ToBase64String(encData_byte);
data = new Byte[System.Text.Encoding.ASCII.GetBytes(encodedData).Length];
data = System.Text.Encoding.ASCII.GetBytes(encodedData);
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}
This is the part in my macro where I would like to add the attachment:
Dim attachmentsStruct As New TAttachmentInputData
fname = attachmentFileName
attachmentsStruct.file_name = GetFilenameFromPath(fname)
attachmentsStruct.is_patch = False
attachmentsStruct.is_private = False
'multiple other definitions
Open fname For Binary As #1
attachmentsStruct.addData (Input(LOF(1), #1))
Close #1
attachmentsStruct.file_name = GetFilenameFromPath(fname)
Call BugzillaClass.add_attachment(attachmentsStruct)
Where BugzillaClass it the interface exposed from my DLL to Excel VBA.
The method add_attachment refers to the XML-RPC method add_attachment.
I assume that my problem is the conversion from the binary file into base64.
This is done using the addData method in my C# DLL.
Is the conversion done correctly there?
Any idea why the images are corrupted?

I think the issue is that you are reading in binary data in the macro, but the addData method is expecting a string. Try declaring the parameter in addData as byte[].

Related

Sparx EA .feap projects images saved as blank

In addin for Sparx EA I use this code to get pictures and assign to entity. Then I use images from entities, to, as example, save at some folders or insert in word report etc (from this answer)
/// <summary>
/// Access to diagram image without using clipboard
/// </summary>
/// <param name="projectInterface">Ea Sparx interface</param>
/// <param name="eaDiagramGuid">Guid of the diagramm</param>
/// <returns></returns>
public static Image GetDiagramImage(this Project projectInterface, Guid eaDiagramGuid, ApplicationLogger _logger)
{
Image diagramImage;
try
{
var diagramByGuid = projectInterface.GUIDtoXML(eaDiagramGuid.ToString("B"));
string tempFilename = string.Format("{0}{1}{2}", Path.GetTempPath(), Guid.NewGuid().ToString(), ".png");
bool imageToFileSuccess = projectInterface.PutDiagramImageToFile(diagramByGuid, tempFilename, FileExtensionByName);
if (imageToFileSuccess)
{
using (var imageStream = new MemoryStream(File.ReadAllBytes(tempFilename)))
{
diagramImage = Image.FromStream(imageStream);
}
File.Delete(tempFilename);
}
else
{
throw new Exception(string.Format("Image to file exprot fail {0}", projectInterface.GetLastError()));
}
}
catch (Exception e)
{
throw;
}
return diagramImage;
}
The problem is - it works if project I work with saved as .eap file.
If it's .feap file, which, as I believe means that it works with Firebird database (instead of Access), all saved/exproted to report images are blank, like this down below
Why does it happens and is there workaround?
UPD
It works if I use projectInterface.PutDiagramImageOnClipboard instead but I don't wont to use clipboard at all
UPD 2
After some experiments today at the morning (at my timezone, gmt+3, it's still morning) I found out that the problem was with GUIDs register!
After I decided to apply .toUpper() here
var diagramByGuid = projectInterface.GUIDtoXML(eaDiagramGuid.ToString("B").ToUpper());
it started work fine!
Strange thing thou that if project is *.EAP type everything works even when guid is not in upper register!
UPD3
Well, unfortunately, I was wrong. Some pictures are still blank. But somehow that changes got impact on diagrams, I keep testing this stuff.
And some of the pictures are appeared twice or in wrong place.
But it's kinda interesting (if I could say so) behaviour.
UPD 4
I was wrong in my UPD2 part! GUID can contain down register symbols as well as upper ones.
So, first I removed that part.
What I done next - I started to pass GUID directly from diagram, so signature changed like that
public static Image GetDiagramImage(this Project projectInterface, string eaDiagramGuid, ApplicationLogger _logger)
and eaDiagramGuid should be passed right from EA.Diagram object.
When we parse it as Guid by Guid.Parse(eaDiagramGuid) it convert everything in lowercase like here
so, thats why I got the problem.
But for some reason it was not appeared in *.EAP type of projects!
Also it strange that register matters in that case, really. Seems like GUID in common and GUID in sparx ea are different things!
Okay, as I founded out here, the thing is, in case of *.FEAP all items GUIDs are surprisingly case sensetive.
So, my mistake was to store item GUID as Guid type - when we use Guid.Parse(myGuidString) function and then we converting it back to string - all symbols are appers to be in lowercase.
Also, I got my answer from support (they were surprisingly fast, I really like that)
Hello Danil,
Running over the Stack Overflow - it sounds like it's effectively
answered. The core point is that the Feap files are case sensitive.
To be technical, the collation used for our Firebird databases is case
sensitive.
So, in the Automation script you do need to adhere to the case.
So, I just change things to work directly with GUID string from project item like
Image diagramImage = _eaProjectInterface.GetDiagramImage(diagram.DiagramGUID, _logger);
and function now look like this
public static Image GetDiagramImage(this Project projectInterface, string eaDiagramGuid, ApplicationLogger _logger)
{
Image diagramImage;
try
{
var diagramByGuid = projectInterface.GUIDtoXML(eaDiagramGuid);
string tempFilename = string.Format("{0}{1}{2}", Path.GetTempPath(), Guid.NewGuid().ToString(), ".png");
bool imageToFileSuccess = projectInterface.PutDiagramImageToFile(diagramByGuid, tempFilename, FileExtensionByName);
if (imageToFileSuccess)
{
using (var imageStream = new MemoryStream(File.ReadAllBytes(tempFilename)))
{
diagramImage = Image.FromStream(imageStream);
}
File.Delete(tempFilename);
}
else
{
throw new Exception(string.Format("Image to file exprot fail {0}", projectInterface.GetLastError()));
}
}
catch (Exception e)
{
throw;
}
return diagramImage;
}
So, this means that Sparx EA *.FEAP project GUIDs are NOT really GUIDs but just string-keys (as I assume).
Be careful when your work with them :-)

How to create transform for .msi file using c#

I'm trying to create a transform for .msi file in C#. Here is my code:
public static void CreateTransforms(string original_MSI, string backup_MSI, string MSTpath, string query)
{
File.Copy(original_MSI, backup_MSI, true);
using (var origDatabase = new Microsoft.Deployment.WindowsInstaller.Database(original_MSI, DatabaseOpenMode.ReadOnly))
{
using (var database = new Microsoft.Deployment.WindowsInstaller.Database(backup_MSI, DatabaseOpenMode.Direct))
{
//database.Execute("Update `Property` Set `Property`.`Value` = 'Test' WHERE `Property`.`Property` = 'ProductName'");
database.Execute(query);
database.GenerateTransform(origDatabase, MSTpath);
database.CreateTransformSummaryInfo(origDatabase, MSTpath, TransformErrors.None, TransformValidations.None);
}
}
}
I got the following error : "This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package." in the step create transform summary info. I used "Microsoft.Deployment.WindowsInstaller.dll" library. Any help would be great.
A quick read of this static method looked correct so I created a console app out of it. It works fine for me on my machine. I would look at your calling method and make sure the data being passed is correct. I get really nervous any time I have a method that takes 4 strings as arguments as that leaves a lot to desire in terms of type safety.
when CreateTransforms start, it open database and it does not close it ...
you must commit and close the database before apply a new transform!
database.GenerateTransform(origDatabase, TRANSFORM);
database.CreateTransformSummaryInfo(origDatabase, TRANSFORM, TransformErrors.None, TransformValidations.None);
database.Commit();
database.Close();

Update Data Source and DataSet reference for SSRS 2012 Deployment from C#

EDIT: I think I can simplify this question a bit to ask for only what is needed to know:
I am working with C# using the SSRS 2010 Web Service:
'ReportService2010.asmx' http://technet.microsoft.com/en-us/library/ee640743.aspx
I can use the method 'CreateDataSource' to create a Datasource on an instance of an SSRS Server http:// (servername)/ReportServer.
I can also use the method 'CreateCatalogItem' to create a report on a server from referencing a project's RDL local file to serialize it to a byte array and then pass that as a 'Definition' to the method to create it on the server.
Now everything I do works with a caveat, and a major one. I can only deploy everything to the same folder. If I deploy a Data Source to say the 'Data Sources' folder and then a report to say: 'Test Reports', the report does not know it has a shared data source to reference at a different location. So I dug a little at the technet articles and have tried to 'GetItemDataSources' method but it only gives a name and a type for the ReportingService2010.DataSource return type. Does anyone know the method to link up a 'Report' or 'Dataset's CatalogItem property of 'DataSource', so it points to a reference in a different folder on the SSRS Server when deploying? There has to be a way to do it as I know I can deploy from Business Intelligence Development Studio and it can do this.
I've had similar issues when deploying report files; when deploying through rs.exe or code you run into these issues where reports lose their link to a Data Source.
We solved this by explicitly pointing the report to the server-side Data Source immediately after being deployed by our application; is this similar to what you're trying to do?
Anyway, here's the slightly adapted code we use in our report deployment application:
static void SetReportDataSource(string reportPath)
{
string dsPath = CombinePath(DataSourcePath, DataSourceFolder, DataSourceName);
DataSourceReference dsRef = new DataSourceReference()
{
Reference = dsPath
};
DataSource ds = new DataSource();
ds.Item = dsRef as DataSourceDefinitionOrReference;
ds.Name = DataSourceName;
var rptDataSources = Server.GetItemDataSources(reportPath);
foreach (var rptDs in rptDataSources)
{
Server.SetItemDataSources(filePath, new DataSource[] { ds });
}
}
So, basically we have variables that define information like the Data Source name, Data Source location on server, and the same for a report. They can be in different folders.
Based on this, we create a new reference to a Data Source and then repoint the report to this using SetItemDataSources.
This sorted out the Data Source issue for me, anyway. Not sure about Shared Datasets and how they handle all of this, but hopefully this will be of some help.
Also, just thought that this would be using the ReportService2005 endpoint, but it's probably not too different for ReportService2010.
Edit:
For the paths mentioned here, these are relative to the server, e.g. /Reports/. You don't need the fully qualified name as you define the Url property of the ReportService2010 object which contains the destination.
Maybe this might be some help. I used it to reset the DataSource for all the reports in a given Parent Folder, and it's subfolders:
using System;
using GetPropertiesSample.ReportService2010;
using System.Diagnostics;
using System.Collections.Generic; //<== required for LISTS
using System.Reflection;
namespace GetPropertiesSample
{
class Program
{
static void Main(string[] args)
{
GetListOfObjectsInGivenFolder_and_ResetTheReportDataSource("0_Contacts"); //<=== This is the parent folder
}
private static void GetListOfObjectsInGivenFolder_and_ResetTheReportDataSource(string sParentFolder)
{
// Create a Web service proxy object and set credentials
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
CatalogItem[] reportList = rs.ListChildren(#"/" + sParentFolder, true);
int iCounter = 0;
foreach (CatalogItem item in reportList)
{
iCounter += 1;
Debug.Print(iCounter.ToString() + "]#########################################");
if (item.TypeName == "Report")
{
Debug.Print("Report: " + item.Name);
ResetTheDataSource_for_a_Report(item.Path, "/DataSources/Shared_New"); //<=== This is the DataSource that I want them to use
}
}
}
private static void ResetTheDataSource_for_a_Report(string sPathAndFileNameOfTheReport, string sPathAndFileNameForDataSource)
{
//from: http://stackoverflow.com/questions/13144604/ssrs-reportingservice2010-change-embedded-datasource-to-shared-datasource
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
string reportPathAndName = sPathAndFileNameOfTheReport;
//example of sPathAndFileNameOfTheReport "/0_Contacts/207_Practices_County_CareManager_Role_ContactInfo";
List<ReportService2010.ItemReference> itemRefs = new List<ReportService2010.ItemReference>();
ReportService2010.DataSource[] itemDataSources = rs.GetItemDataSources(reportPathAndName);
foreach (ReportService2010.DataSource itemDataSource in itemDataSources)
{
ReportService2010.ItemReference itemRef = new ReportService2010.ItemReference();
itemRef.Name = itemDataSource.Name;
//example of DataSource i.e. 'itemRef.Reference': "/DataSources/SharedDataSource_DB2_CRM";
itemRef.Reference = sPathAndFileNameForDataSource;
itemRefs.Add(itemRef);
}
rs.SetItemReferences(reportPathAndName, itemRefs.ToArray());
}
}
}

Lists.AddAttachment throws object reference error

I'm trying to add an attachment to a list item I just created on a sharepoint server using CAML. The code below is simplified (for example the path is normally a variable and the 2nd field (the item id, here 16847) is normally the id I get back from my insert statement in CAML).
This is my code:
String desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
String savePath = desktopPath + #"\" + "tutorials.txt";
byte[] data = GetData(savePath);
lists.AddAttachment("Tasks", "16847", "tutorials.txt", data);
I'm getting this error:
Unable to update the security according your changes. The following exception occurred during ItemUpdating: Object reference not set to an instance of an object.
See Event Viewer for more information.0x81020089
getdata is a method which converts the file on my desktop to a byte[]. data is not empty and it looks okay.
Other than that Tasks is the List needed and 16847 is the task id in which to add the attachment.
Most of the info I can find is about a different error: the index out of range exception (like on the msdn page: http://msdn.microsoft.com/en-us/library/lists.lists.addattachment(v=office.12).aspx).
I've also tried a http put (unauthorized access, obviously) and the copy service (I can post this code if we can't find the solution to the simpler way above).
Can anyone tell me what is wrong?
EDIT 1:
private dcp.Lists lists = new dcp.Lists();
lists.Credentials = System.Net.CredentialCache.DefaultCredentials;
lists.Url = Values.SERVERADDRESS + "/_vti_bin/lists.asmx";
This initializes the connection to our web service. It works perfectly fine for updates, inserts...
GetData code:
private byte[] GetData(String savePath)
{
byte[] contents;
using (FileStream fStream = File.OpenRead(savePath))
{
contents = new byte[fStream.Length];
sFileName = fStream.Name;
fStream.Read(contents, 0, Convert.ToInt32(fStream.Length));
}
return contents;
}
EDIT 2:
Note that the following does work (I get a correct list of existing attachments from the task):
XmlNode ndAttach = lists.GetAttachmentCollection("Tasks", "16847");
MessageBox.Show(ndAttach.OuterXml);
And the following doesn't (same error as for the AddAttachment method):
lists.DeleteAttachment("Tasks", "16847", ndAttach.ChildNodes[0].InnerText);
Whereas I'm quite certain this should work since it does exactly the same as the example code on msdn: http://msdn.microsoft.com/en-us/library/lists.lists.deleteattachment(v=office.12).aspx
The code above is fine, the error occured on our server. When adding an attachment, no contenttype is given in the xml. This was programmed to throw an error because we've always used this method to update and add new items. So we removed the contenttype out of the underlying code and it works like a charm.

Paint.net filetype plugins

Can't find any info on how to write a filetype plugin for Paint.net. I have found only visual studio template at http://forums.getpaint.net/index.php?/topic/7984-filetype-plugin-template-v20/page__p__121651&#entry121651
and small description at codeproject, but I don't understand all of the parameters of OnSave event handler, what is PaintDotNet.Surface and how to work with data stored there.
I've written a plug-in like this once.
Forget about the template for a minute, you can do this from scratch.
Start by adding references to PaintDotnet.Base, PaintDotNet.Core and PaintDotNet.Data.
Next you'll need a class which inherits from the FileType class:
For example:
public class SampleFileType : FileType
{
public SampleFileType() : base ("Sample file type", FileTypeFlags.SupportsSaving |
FileTypeFlags.SupportsLoading,
new string[] { ".sample" })
{
}
protected override void OnSave(Document input, System.IO.Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
{
//Here you get the image from Paint.NET and you'll have to convert it
//and write the resulting bytes to the output stream (this will save it to the specified file)
using (RenderArgs ra = new RenderArgs(new Surface(input.Size)))
{
//You must call this to prepare the bitmap
input.Render(ra);
//Now you can access the bitmap and perform some logic on it
//In this case I'm converting the bitmap to something else (byte[])
var sampleData = ConvertBitmapToSampleFormat(ra.Bitmap);
output.Write(sampleData, 0, sampleData.Length);
}
}
protected override Document OnLoad(System.IO.Stream input)
{
//Input is the binary data from the file
//What you need to do here is convert that date to a valid instance of System.Drawing.Bitmap
//In the end you need to return it by Document.FromImage(bitmap)
//The ConvertFromFileToBitmap, just like the ConvertBitmapSampleFormat,
//is simply a function which takes the binary data and converts it to a valid instance of System.Drawing.Bitmap
//You will have to define a function like this which does whatever you want to the data
using(var bitmap = ConvertFromFileToBitmap(input))
{
return Document.FromImage(bitmap);
}
}
}
So, you inherit from FileType. In the constructor you specify what operations are supported (Loading/Saving) and which file extensions should be registered. Then you provide logic for both the Save and Load operations.
Basically that is all you need.
Finally you'll have to tell Pain.Net which FileType classes you want to load, in this case a single instance, but you could have more then one in a single library.
public class SampleFileTypeFactory : IFileTypeFactory
{
public FileType[] GetFileTypeInstances()
{
return new FileType[] { new SampleFileType() };
}
I hope this helps, let me know if you have questions.
}

Categories