I am using a groovy script to remove content from a Prop file in jenkins job. I am using groovy plugin in Build section. My code works fine when the value is hard coded. but when I am using a variable to pass the value,I am not getting desired result. I have tested my code in intelliji editor and is getting some result. Could you please help me understand what am I doing wrong?
This is working fine
InputStream input = new FileInputStream("C:\\AppianDeployment\\Application.properties")
Properties prop = new Properties()
String removeApps = "AP2"
prop.load(input)
def keyToRemove = "${removeApps}".toString()
*prop.remove("AP1")*
OutputStream output = new FileOutputStream("C:\\AppianDeployment\\Application.properties");
prop.store(output, null);
This is not working
InputStream input = new FileInputStream("C:\\AppianDeployment\\Application.properties")
Properties prop = new Properties()
String removeApps = "AP2"
prop.load(input)
def keyToRemove = "${removeApps}".toString()
*prop.remove(${keyToRemove})*
OutputStream output = new FileOutputStream("C:\\AppianDeployment\\Application.properties");
prop.store(output, null);
There's no such literal in Groovy
prop.remove(${keyToRemove})
Instead you should be using either
prop.remove keyToRemove
or for whatever reason
prop.remove "${keyToRemove}".toString()
Related
I'm able to copy most test cases with this code (trying to copy shared steps to be part of the test case itself) but this one will not copy but I can not see any error message as to why - could anyone suggest anything else to try. See output from Immediate windows. Thanks John.
?targetTestCase.Error
null
?targetTestCase.InvalidProperties
Count = 0
?targetTestCase.IsDirty
true
?targetTestCase.State
"Ready"
?targetTestCase.Reason
"New"
foreach (ITestAction step in testSteps)
{
if (step is ITestStep)
{
ITestStep sourceStep = (ITestStep)step;
ITestStep targetStep = targetTestCase.CreateTestStep();
targetStep.Title = sourceStep.Title;
targetStep.Description = sourceStep.Description;
targetStep.ExpectedResult = sourceStep.ExpectedResult;
//Copy Attachments
if (sourceStep.Attachments.Count > 0)
{
string attachmentRootFolder = _tfsServiceUtilities.GetAttachmentsFolderPath();
string testCaseFolder = _tfsServiceUtilities.CreateDirectory(attachmentRootFolder, "TestCase_" + targetTestCase.Id);
//Unique folder path for test step
string TestStepAttachementFolder = _tfsServiceUtilities.CreateDirectory(testCaseFolder, "TestStep_" + sourceStep.Id);
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
foreach (ITestAttachment attachment in sourceStep.Attachments)
{
string attachmentPath = TestStepAttachementFolder + "\\" + attachment.Name;
client.DownloadFile(attachment.Uri, attachmentPath);
ITestAttachment newAttachment = targetTestCase.CreateAttachment(attachmentPath);
newAttachment.Comment = attachment.Comment;
targetStep.Attachments.Add(newAttachment);
}
}
}
targetTestCase.Actions.Add(targetStep);
targetTestCase.Save();
}
Since this code works for most test cases, this issue may come from the particular test case. In order to narrow down the issue, please try the following items:
Run the code on another client machine to see whether it works.
Try to modify this particular test case using the account API uses, to see whether it can be saved successfully.
Try validate the WorkItem prior to save. The validate() method will return an arraylist of invalid fields.
I have the following code:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "~/files/";
htmlToPdf.GeneratePdf(template);
Which throws the following error:
Uri is not supported when saving pdf in server folder with nreco pdf generator.
You will need to set a regular path to your file system like e.g. "C:\temp\myfolder\". Or use a . instead of ~ and backslashes:
htmlToPdf.PdfToolPath = ".\\files\\";
If NReco is able to deliver you an byte-array or a stream you should prefer this instead of a file and return it directly.
UPDATE:
After takeing a look into the documentation of NReco all you need to do is following:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "<CORRECT_PATH_FOR_TOOL>";
var output = htmlToPdf.GeneratePdf(template);
System.IO.File.WriteAllBytes("<OUTPUT_PATH>", output);
This should create your pdf in the OUTPUT_PATH.
#OlaFW thanx for your effort.
I got my answer.
var pdfBytes = htmlToPdf.GeneratePdf(template);
string filePath = "/files/Myfile.pdf";
string Url = System.Web.Hosting.HostingEnvironment.MapPath(filePath);
System.IO.File.WriteAllBytes(Url, pdfBytes);
I am trying to pass arguments to MSBuild 2.0. After research it appears that I need to do this using variables, but I cannot figure out how to incorporate this into my queue request below. I have tried parameters but that does not seem to work. Here is what I am trying to tell MSBuild #" /p:OctoPackPackageVersion=" + releaseNumber. This worked with the XAML build using IBuildRequest.ProcessParameters.
var buildClient = new BuildHttpClient(new Uri(collectionURL), new
VssCredentials(true));
var res = await buildClient.QueueBuildAsync(new Build
{
Definition = new DefinitionReference
{
Id = targetBuild.Id
},
Project = targetBuild.Project,
SourceVersion = ChangeSetNumber,
Parameters = buildArg
});
return res.Id.ToString();
vNext build system is different with legacy XAML build system, you cannot pass variable to build tasks in the build definition directly when queue the build. The code you used updated the build definition before queue the build which means that the build definition may keep changing if the variable changed.
The workaround for this would be add a variable in your build definition for example "var1" and then use this variable as the arguments for MSBuild Task:
With this, you will be able to pass the value to "var1" variable when queue the build without updating the build definition.
Build build = new Build();
build.Parameters = "{\"var1\":\"/p:OctoPackPackageVersion=version2\"}";
// OR using Newtonsoft.Json.JsonConvert
var dict = new Dictionary<string, string>{{"var1", "/p:OctoPackPackageVersion=version2"}};
build.Parameters = JsonConvert.SerializeObject(dict)
I have found this solution and it works for me excellent. I set custom parameters for convenience in build definition without updating on server:
foreach (var variable in targetBuildDef.Variables.Where(p => p.Value.AllowOverride))
{
var customVar = variables.FirstOrDefault(p => p.Key == variable.Key);
if (customVar == null)
continue;
variable.Value.Value = customVar.Value.TrimEnd('\\');
}
And then set variables values in build parameters:
using (TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(tFSCollectionUri)))
{
using (BuildHttpClient buildServer = ttpc.GetClient<BuildHttpClient>())
{
var requestedBuild = new Build
{
Definition = targetBuildDef,
Project = targetBuildDef.Project
};
var dic = targetBuildDef.Variables.Where(z => z.Value.AllowOverride).Select(x => new KeyValuePair<string, string>(x.Key, x.Value.Value));
var paramString = $"{{{string.Join(",", dic.Select(p => $#"""{p.Key}"":""{p.Value}"""))}}}";
var jsonParams = HttpUtility.JavaScriptStringEncode(paramString).Replace(#"\""", #"""");
requestedBuild.Parameters = jsonParams;
var queuedBuild = buildServer.QueueBuildAsync(requestedBuild).Result;
First, the new build on TFS2015 which is called vNext build not MSbuild 2.0.
Which you are looking for should be Build variables. Variables give you a convenient way to get key bits of data into various parts of your build process. For the variable with Allow at queue time box checked you could be enable allow your team to modify the value when they manually queue a build.
Some tutorials may be helpful for using variables:
TFS Build 2015 (vNext) – Scripts and Variables
Passing Visual Studio Team Services build properties to MSBuild
Patrick, I was able to find a work around to my issue by updating the build definition. This is definitely not ideal but it works. As you can see below I am trying to add to the msbuild args already present. If you know a better way let me know. I really appreciate you taking the time to look at my question.
public static async Task<string> QueueNewBuild(string project, BuildDefinitionReference targetBuild, string collectionURL, string ChangeSetNumber, string ReleaseNumber, bool CreateRelease)
{
var buildClient = new BuildHttpClient(new Uri(collectionURL), new VssCredentials(true));
await Task.Delay(1000).ConfigureAwait(false);
var buildDef = await buildClient.GetDefinitionAsync(targetBuild.Project.Id, targetBuild.Id);
BuildDefinitionVariable OrigMSbuildvar = buildDef.Variables["MSBuildArgs"];
buildDef.Variables["MSBuildArgs"].Value = OrigMSbuildvar.Value + " /p:OctoPackPackageVersion=" + ReleaseNumber.ToString();
await Task.Delay(1000).ConfigureAwait(false);
buildDef = await buildClient.UpdateDefinitionAsync(buildDef);
await Task.Delay(1000).ConfigureAwait(false);
Build build = new Build
{
Definition = new DefinitionReference
{
Id = targetBuild.Id
},
Project = targetBuild.Project,
SourceVersion = ChangeSetNumber
};
await Task.Delay(1000).ConfigureAwait(false);
var res = await buildClient.QueueBuildAsync(build);
buildDef.Variables["MSBuildArgs"].Value = OrigMSbuildvar.Value;
await Task.Delay(1000).ConfigureAwait(false);
buildDef = await buildClient.UpdateDefinitionAsync(buildDef);
return res.Id.ToString();
}
thanks for reading, my doubt is the following, im trying to get data from an xls file but it has to be done locally, without uploading the file, i have done something similiar with txts files and works perfectly :
Function Send(ByVal file As HttpPostedFileBase) As ActionResult
Dim line As String
Dim textreader As System.IO.StreamReader = New StreamReader(file.InputStream)
While Not textreader.EndOfStream
line = textreader.ReadLine()
ViewBag.line = line
End While
Return View("Index")
End Function
but i cant do the same to the excel file, first of all, because i cant use the streamreader, so when using this code i dont know how to specify the dir of my xls file
Dim oApp As Excel.Application = New Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
oWB = oApp.Workbooks.Open(file.inputstream) <-- HERE IS WHERE I GET (AN OBVIOUS) ERROR
does anybody knows how to open the file locally? thanks for reading :)
There are several ways of doing it, one of them is accessing the file "database style"
...
...
string filePath = string.Format("C:\\TEST\\{0}.xlsx", Guid.NewGuid().ToString());
var fileStream = File.Create(filePath);
input.CopyTo(file.InputStream);
fileStream.Close();
string cn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
string query = "SELECT * FROM SHEET_NAME";
conn= new OleDbConnection(cn);
conn.Open();
OleDbCommand woOleCommand = new OleDbCommand(query, conn);
DbDataReader result = woOleCommand.ExecuteReader();
// Read the DataReader...
...
So basically you query Sheets like tables, if they are indeed tables, this code might be what you're looking for.
On the other hand, if you still need to use automation, try something like this instead:
...
object missing = System.Reflection.Missing.Value;
wBook = (Excel._Workbook)xl.Workbooks.Open(filePath, false, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
...
Reading InputStream
using (var fileStream = File.Create(filePath)) {
file.InputStream.CopyTo(fileStream);
}
// Now you got your stream on a file (filePath) so you can work with it.
I am trying to generate the OData Proxy for the service : http://services.odata.org/Northwind/Northwind.svc/$metadata
I am using System.Data.Services.Design.EntityClassGenerator for generating the OData proxy.
When I instantiate the EntityClassGenerator and call GenerateCode the output has no errors. But there is no code in the generated proxy code.
The same code works for my own service. But when I point it to any external service the EntityClassGenerator is not working.
Here is the code :
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(metadataEndpoint);
webRequest.Method = "GET";
webRequest.ContentType = "text/xml;encoding='utf-8";
webRequest.Proxy = (proxy != null) ? proxy : WebRequest.DefaultWebProxy;
using (WebResponse response = webRequest.GetResponse())
{
string xml = string.Empty;
XmlReaderSettings settings = new XmlReaderSettings();
using (TextReader reader = new StreamReader(response.GetResponseStream()))
{
xml = reader.ReadToEnd();
using (XmlTextReader sourceReader = new XmlTextReader(reader))
{
using (StringWriter targetWriter = new StringWriter())
{
// Generate the OData End point proxy.
EntityClassGenerator entityGenerator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode);
entityGenerator.OnPropertyGenerated += new EventHandler<PropertyGeneratedEventArgs>(entityGenerator_OnPropertyGenerated);
IList<System.Data.Metadata.Edm.EdmSchemaError> errors = entityGenerator.GenerateCode(sourceReader, targetWriter, namespacename);
entityGenerator.OnPropertyGenerated -= new EventHandler<PropertyGeneratedEventArgs>(entityGenerator_OnPropertyGenerated);
odataProxyCode = targetWriter.ToString();
}
}
}
}
I found the code in the question to be a useful starting point for doing exactly what the OP was asking. So even though the OP doesn't accept answers, I'll describe the changes I made to get it to work in case it is useful to someone else.
Removed the xml = reader.ReadToEnd(); call. I assume that was for debugging purposes to look at the response from the web request, but it had the result of "emptying" the reader object of the response. That meant that there was nothing left in the reader for the GenerateCode call.
The important one: Changed the use of EntityClassGenerator to System.Data.Services.Design.EntityClassGenerator. In the code below, I included the entire name space for clarity and specificity. Based on the code in the question, it appears the OP was probably using System.Data.Entity.Design.EntityClassGenerator. I used .NET Reflector to examine datasvcutil.exe, which is a command-line utility that can generate the proxy classes. I saw that it referenced the generator in that other name space.
For figuring out the problems, I dumped the errors from the GenerateCode call. One could examine them in the debugger, but some kind of automated checking of them would be needed regardless.
Here is what I ended up with:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.
Create("http://services.odata.org/Northwind/Northwind.svc/$metadata");
webRequest.Method = "GET";
webRequest.ContentType = "text/xml;encoding='utf-8";
webRequest.Proxy = WebRequest.DefaultWebProxy;
using (WebResponse response = webRequest.GetResponse())
{
using (TextReader reader = new StreamReader(response.GetResponseStream()))
{
using (XmlTextReader sourceReader = new XmlTextReader(reader))
{
using (StringWriter targetWriter = new StringWriter())
{
// Generate the OData End point proxy.
System.Data.Services.Design.EntityClassGenerator entityGenerator =
new System.Data.Services.Design.EntityClassGenerator(
System.Data.Services.Design.LanguageOption.GenerateCSharpCode);
IList<System.Data.Metadata.Edm.EdmSchemaError> errors =
entityGenerator.GenerateCode(sourceReader, targetWriter,
"My.Model.Entities");
foreach (System.Data.Metadata.Edm.EdmSchemaError error in errors)
Console.WriteLine("{0}: {1}", error.Severity.ToString(), error.Message);
string odataProxyCode = targetWriter.ToString();
}
}
}
}