Dynamic FTP Folder pipeline - biztalk

I'm trying to set Dynamically the output folder of an FTP location.
Assignment, for each customer I need to create a separate folder to store an Excel file and / or XML file.
What I've tried
Created a Custom Pipeline Component to set all the required Properties into a FTP send port.
Tried the same pipeline into a Dynamic Send Port
For testing tried the code in an Orchestration.
What I've noticed:
When I send through the FTP Send Port the properties won't be overridden by the custom pipeline properties.
When I send through the Dynamic I always get the following error
A failure was encountered while transmiting the message
Even when I'm trying to set the properties into the Orchestration I get the same error.
Also when I'm trying to send through the Dynamic Send Port I notice that the pipeline component is not touched.
Execute code part of the custom pipeline component
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage inputMessage)
{
Guid callToken = TraceManager.PipelineComponent.TraceIn(CLASSNAME + ".Execute() - Start", pipelineContext.PipelineID, pipelineContext.PipelineName, pipelineContext.StageID);
if (!this.Active)
{
TraceManager.PipelineComponent.TraceOut(callToken, CLASSNAME + ".Execute() - Pipeline component is not active!");
return inputMessage;
}
try
{
string completeFTPUri = null;
string fileName = null;
string accountNumber = Convert.ToString(inputMessage.Context.Read(PROP_ACCOUNTNUMBER.Name.Name, PROP_ACCOUNTNUMBER.Name.Namespace));
if (!string.IsNullOrWhiteSpace(accountNumber))
this.Folder = string.Format("{0}/{1}", this.Folder, accountNumber);
if (!string.IsNullOrWhiteSpace(this.Folder))
completeFTPUri = string.Format("ftp://{0}:21/{1}", this.FTPUri, this.Folder);
else
completeFTPUri = this.FTPUri;
if (!UseDefaultFilename)
{
string receiveFilename = null;
receiveFilename = Convert.ToString(inputMessage.Context.Read(FTP_RECEIVED_FILENAME.Name.Name, FTP_RECEIVED_FILENAME.Name.Namespace));
if (!string.IsNullOrWhiteSpace(receiveFilename))
fileName = Path.GetFileName(receiveFilename);
}
if (string.IsNullOrWhiteSpace(fileName))
{
if (string.IsNullOrWhiteSpace(this.Filename))
fileName = DEFAULT_FILENAME;
else
fileName = this.Filename;
}
if (fileName.Contains("{0") || fileName.Contains("{1"))
{
fileName = string.Format(fileName, DateTime.Now, inputMessage.MessageID);
}
if (!string.IsNullOrWhiteSpace(this.Folder))
{
//inputMessage.Context.Write(FTP_BEFORE_PUT.Name.Name, FTP_BEFORE_PUT.Name.Namespace, string.Format("MKDIR {0}", string.Format("ftp://{0}:21/{1}", this.FTPUri, this.Folder)));
inputMessage.Context.Promote(FTP_BEFORE_PUT.Name.Name, FTP_BEFORE_PUT.Name.Namespace, string.Format("MKDIR {0}", completeFTPUri));
}
//inputMessage.Context.Write(OUTBOUND_TRANSPORT_LOCATION.Name.Name, OUTBOUND_TRANSPORT_LOCATION.Name.Namespace, completeFTPUri);
//inputMessage.Context.Write(FILE_RECEIVED_FILENAME.Name.Name, FILE_RECEIVED_FILENAME.Name.Namespace, fileName);
//inputMessage.Context.Write(FTP_USERNAME.Name.Name, FTP_USERNAME.Name.Namespace, _userName);
//inputMessage.Context.Write(FTP_PASSWORD.Name.Name, FTP_PASSWORD.Name.Namespace, _password);
inputMessage.Context.Promote(OUTBOUND_TRANSPORT_LOCATION.Name.Name, OUTBOUND_TRANSPORT_LOCATION.Name.Namespace, completeFTPUri);
inputMessage.Context.Promote(OUTBOUND_TRANSPORT_TYPE.Name.Name, OUTBOUND_TRANSPORT_TYPE.Name.Namespace, "FTP");
inputMessage.Context.Promote(FILE_RECEIVED_FILENAME.Name.Name, FILE_RECEIVED_FILENAME.Name.Namespace, fileName);
inputMessage.Context.Promote(FTP_USERNAME.Name.Name, FTP_USERNAME.Name.Namespace, this.UserName);
inputMessage.Context.Promote(FTP_PASSWORD.Name.Name, FTP_PASSWORD.Name.Namespace, this.Password);
}
catch (Exception ex)
{
TraceManager.PipelineComponent.TraceError(ex, false, callToken);
throw new Exception(CLASSNAME + ".Execute() - Failed to set the filename.", ex);
}
TraceManager.PipelineComponent.TraceOut(callToken, CLASSNAME + ".Execute() - Finished.");
return inputMessage;
}
EDIT:
After trying a lot this morging an update.
When I try to Send Dynamicly through the Static SendPort I keep the same issue.
When I try to Send Dynamicly through a Dynamic SendPort I'm getting different error:
Inner exception: The value assigned to property 'Microsoft.XLANGs.BaseTypes.Address' is not valid: 'FTP URI'.
I don't know what the best solution is to resolve this issue.
I can also write everything to a helper class en try to send through C# code. But I want to use the force of BizTalk and want to be able to enable en disable ports when necessary. That's the main reason.
I'm not afraid to write custom pipeline components or somthing else, so if someone could help. PLEASE
Code of the Message Assign of the Orchestration
MsgPublishArticleMessage = MsgFullArticleMessage;
MsgPublishArticleMessage(*) = MsgFullArticleMessage(*);
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Domain) = "ArticleMessage";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Service) = "PricatService";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Action) = "PublishPricatXLSX";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Version) = "1.0";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.AccountNumber) = articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportLocation) = "ftp://URI:21/Pricat/" + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportType) = "FTP";
MsgPublishArticleMessage(FTP.Password) = "********";
MsgPublishArticleMessage(FTP.UserName) = "UserName";
MsgPublishArticleMessage(FTP.BeforePut) = "MKDIR " + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(FTP.ReceivedFileName) = Destil.BizTalk.ArticleMessage.Components.OrchestrationHelper.CreateReceivedFileName(articleMessageRequest, ".xlsx");
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "FTPURI";
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.TransportType) = "FTP";
MsgPublishArticleMessage(BTS.IsDynamicSend) = true;
EDIT 2:
When I change the Message Assingment to below code I can send the file to a dynamic folder.
The only problem I'm running into now:
When the Folder already exist I'm getting a failure.
Does anyone know what FTP command I need to use to create a Folder only if it don't exist?
I've try'ed the following commands
MDK -p /Pricat/AccountNumber;
MDK /Pricat/AccountNumber;
if not exist "/Pricat/AccountNumber" MDK /Pricat/AccountNumber
Changed code of message assign in the orchestration
MsgPublishArticleMessage = MsgFullArticleMessage;
MsgPublishArticleMessage(*) = MsgFullArticleMessage(*);
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Domain) = "ArticleMessage";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Service) = "PricatService";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Action) = "PublishPricatXLSX";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Version) = "1.0";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.AccountNumber) = articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportLocation) = "ftp://URI:21/Pricat/" + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportType) = "FTP";
MsgPublishArticleMessage(FTP.Password) = "*********";
MsgPublishArticleMessage(FTP.UserName) = "username";
MsgPublishArticleMessage(FTP.BeforePut) = "MKD Pricat/" + articleMessageRequest.AccountNumber + "; CWD Pricat/" + articleMessageRequest.AccountNumber;
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "ftp://URI:21/" + DOMAIN.BizTalk.ArticleMessage.Components.OrchestrationHelper.CreateReceivedFileName(articleMessageRequest, ".xlsx");
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.TransportType) = "FTP";
MsgPublishArticleMessage(BTS.IsDynamicSend) = true;

From the code snippet you have provided, can you check the below line.
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "FTPURI";
You have declared FTPURI as a variable and assigning a constant string to the address. This might explain the error -
Inner exception: The value assigned to property 'Microsoft.XLANGs.BaseTypes.Address' is not valid: 'FTP URI'.

When overwriting static send port properties you have to give adapter know that it should use message properties instead of port properties.
Set IsDynamicSend property to true
inmsg.Context.Promote("IsDynamicSend", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);

Related

Empty file received using HTTP Post method

I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.

MSDeploy API - Deleting a remote file through code

I am looking to remotely fire a delete command using the MSDeploy API through c# code.
I want to achieve the following command:
msdeploy.exe -verb:delete -dest:contentPath="/folderName/filename.txt"
instead of through running an unmanaged external executable, I want to execute this using the MSDeploy .Net API.
Assuming you're trying to delete an absolute filepath (rather than a file in a website), you're looking for something like this:
DeploymentObject destObject = DeploymentManager.CreateObject(
DeploymentWellKnownProvider.FilePath, "/foldername/filename.txt");
DeploymentObject sourceObject = DeploymentManager.CreateObject("auto", "");
DeploymentBaseOptions baseOptions = new DeploymentBaseOptions();
DeploymentSyncOptions syncOptions = new DeploymentSyncOptions
{
DeleteDestination = true;
};
DeploymentChangeSummary results = sourceObject.SyncTo(
destObject, baseOptions, syncOptions);
// results.ObjectsDeleted == 1
I've found the answer thanks to Richard Szalay's leading and i've used the ContentPath provider as this is a common provider used by VS Publishing so the chances of having permissions is high:
var deployBaseOptions = new DeploymentBaseOptions
{
ComputerName = "https://mywebserver.com:8172/msdeploy.axd?sitename=yourIISWebsiteName",
UserName = "username",
Password = "password",
UseDelegation = true,
AuthenticationType = "Basic"
};
var syncOptions = new DeploymentSyncOptions
{
DeleteDestination = true
};
var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath,
"yourIISWebsiteName" + "/fileToDelete.txt",
destBaseOptions);
var results = deploymentObject.SyncTo(deployBaseOptions, syncOptions);
The weird thing is that results always shows 3 files deleted even when there is only one...?!

start workflow using alfresco java script api or through web script

I want to start a workflow programatically. So written a web script.
Execute Script :
function startWorkflow()
{
var workflow = actions.create("start-workflow");
workflow.parameters.workflowName = "activiti$alfGroupReview";
workflow.parameters["bpm:workflowDescription"] = "Please review ";
workflow.parameters["bpm:groupAssignee"] = people.getGroup( "GROUP_site_collaborators");;
var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7);
workflow.parameters["bpm:workflowDueDate"] = futureDate;
workflow.execute(document);
return ;
}
For the above script, I am getting error "document is not defined". I am referring https://forums.alfresco.com/en/viewtopic.php?f=34&t=42677 and http://livinginjava.blogspot.in/2008/10/starting-alfresco-workflow-using.html links.
So I update my script to :
function startWorkflow()
{
var nodeRef = "workspace://SpacesStore/25285e6c-2995-49fe-aa50-1270cefc806a";
var docNode = search.findNode(nodeRef);
var workflow = actions.create("start-workflow");
workflow.parameters.workflowName = "activiti$alfGroupReview";
workflow.parameters["bpm:workflowDescription"] = "Please review ";
workflow.parameters["bpm:groupAssignee"] = people.getGroup( "GROUP_aloha_collaborators");;
var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7);
workflow.parameters["bpm:workflowDueDate"] = futureDate;
workflow.execute(docNode);
return ;
}
Here, nodeRef : is ref of a document from document library.
Now new error is :
500 Description: An error inside the HTTP server which prevented it from fulfilling the request.
Message: 06270056 Wrapped Exception (with status template): 06270273 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/justransform/startWF.get.js': null
Exception: org.alfresco.scripts.ScriptException - 06270273 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/justransform/startWF.get.js': null
org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:195)
thanks in advance.
Using Alfresco Workflow API.
Note: wfDocs holds the array of doc nodes:
// 2 days from now
var dueDate2d = new Date((new Date()).getTime() + 2*(24*60*60*1000));
// Start workflow
var wfdef = workflow.getDefinitionByName("activiti$alfGroupReview");
if (wfdef) {
var wfparams = new Array();
wfparams["bpm:workflowDescription"] = "Please review";
wfparams["bpm:groupAssignee"] = people.getGroup( "GROUP_site_collaborators");
wfparams['bpm:workflowDueDate'] = dueDate2d;
wfparams['bpm:workflowPriority'] = 1;
wfparams['wf:notifyMe'] = true;
var wfpackage = workflow.createPackage();
for each (var n in wfDocs)
wfpackage.addNode(n);
var wfpath = wfdef.startWorkflow(wfpackage, wfparams);
var tasks = wfpath.getTasks();
for each (task in tasks)
task.endTask(null);
}
This code runs fine if:
docNode is not null. You should add a check for this.
Your group exists. Probably worth adding a check for this.
The workflow exists with the ID specified. Use the workflow console to confirm this. For example, the ID your provided is not an
out-of-the-box workflow. If it is custom, maybe you haven't deployed
the workflow successfully or you have the ID incorrect.
Also, do not use a variable called "workflow". Alfresco already defines a root-scoped object called "workflow". Speaking of that, feel free to use the workflow JavaScript API to invoke your workflow instead of an action. Either should work, though.
I ran your code successfully using the JavaScript console and a workflow id of "activiti$activitiParallelGroupReview" (and after changing your workflow variable to workflowAct).

A generic error occurred in GDI+, possible server.mappath issue

I've narrowed down the issue I'm having to this block of code, where I am resizing an uploaded image and saving it. This works fine on my local machine, but when I run the site on the server, I get a generic GDI+ error that's coming from the "thumbnail.Save" call.
if(fup_displayPicUpload.HasFile)
{
string imageDir = Server.MapPath("./images/");
if (!Directory.Exists(imageDir + username))
{
Directory.CreateDirectory(imageDir + username);
lbl_profileMessage.ForeColor = Color.Yellow;
lbl_profileMessage.Text = "Created User Folder";
}
String userFolder = imageDir + username + "/";
using (System.Drawing.Image originalPhoto = new Bitmap(new MemoryStream(fup_displayPicUpload.FileBytes)))
{
System.Drawing.Image thumbnail = originalPhoto.GetThumbnailImage(300, 300, Abort, IntPtr.Zero);
thumbnail.Save(userFolder + "displaypicture.jpg", ImageFormat.Jpeg);
}
displayPictureUrl = "/images/" + username + "/displaypicture.jpg";
}
The most common cause of this is an access denied error to the directory that you are trying to save the image to. Make sure that the user that the application is running as has write access to the destination directory.

Uploading an XML file, referencing an XSD, in ASP.Net

I have an XML file which is being uploaded to an ASP.Net page via the normal file upload control. When it gets up, I am attempting to validate and deserialize the XML. However, the code below is really very handy for validating an XML file which references it's XSD like this:
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
However, if I upload this XML file, only the XML file gets uploaded, so ..\localSchemaPath.xsd doesn't exist, so it can't validate.
Even if I stored the XSD locally, it still wouldn't be quite right as the XML file could be written with a schema location like:
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
or
xsi:schemaLocation="someurl localSchemaPath.xsd"
or
xsi:schemaLocation="someurl ..................\localSchemaPath.xsd"
if it so wished.
Dilemma!
(For the purposes of this question, I have pinched the code below from: Validating an XML against referenced XSD in C#)
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD
{
public static void Main()
{
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read()) ;
}
// Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
Here is a chunk of code I use to validate xml with a local schema:
string errors = string.Empty;
try
{
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(string.Empty, Page.MapPath("~/xml/Schema.xsd"));
XmlDocument doc = new XmlDocument();
doc.Schemas = schemas;
doc.Load(Page.MapPath("~/xml/sampleXML.xml"));
//use this line instead of the one above for a string in memory.
//doc.InnerXml = xmlToValidate;
ValidationEventHandler validator = delegate(object send, ValidationEventArgs ve)
{
errors += "\n" + ve.Severity + ": " + ve.Message;
};
doc.Validate(validator);
}
catch (XmlException xe)
{
errors += "\n" + xe.Message;
}
catch (XmlSchemaValidationException xe)
{
errors += "\n" + xe.Message;
}
I can't quite make out whether you are attempting a generic validate-against-any-referenced-schema, or if you have a specific schema that you validate against every time, and are just not sure how to handle the references.
If it's the latter, then make the schema public on the internet, and tell people to reference it by URI.
If it's the former, then I would suggest the following:
First the user uploads an XML file.
Parse the XML file for a schema reference. Tell them "References to yourSchema.xsd were found; please upload this file below" with a new upload box.
Then, validate the file against the uploaded schema. To do this, modify the Schemas property of your settings object, instead of modifying the ValidationFlags property.

Resources