Is there a way to change command-line arguments in a signed RDP file? - rdp

I need to specify command line arguments for a RemoteApp using the remoteapplicationcmdline property of a signed RDP file.
However, after the RDP file is signed, I cannot change the value for remoteapplicationcmdline. If I remove remoteapplicationcmdline from the signscope, I can't specify any parameters.
This is the same question asked by Chupkb on Technet.
I might be able to do as Naraen suggested on this question, but before I do that I'm hoping there is a simpler way.

The route I eventually took was to gather the command line arguments from a previous page (perhaps a login page) and then on the next page I dynamically create an rdp file, sign it, and embed the contents into the javascript on the html page. The code below is ASP.NET and c# but it should be a good starting point for other languages as well.
First, the html (notice the <%= RdpFileContents %> in LaunchRemoteApp():
<html>
<head>
<title>RD Web Access</title>
<script type="text/javascript" language="javascript">
var g_workspace = null;
var workspaceID = "[RemoteAppMachineName]";
var domainUserName = "[RemoteAppMachineName]\\[RemoteAppUserName]";
// This is the certificate's thumbprint.
var rdpCertificates = "04b83503a710cad89f25d3e15a48245f490773c4";
var machineType = "public";
function onAutoDisconnect() {
var workspace = null;
if (workspaceID != null && workspaceID != "") {
try {
workspace = GetWorkspaceObject();
workspace.ClearWorkspaceCredential(workspaceID);
}
catch (objException) {
workspace = null;
}
}
}
function onUserDisconnect() {
var workspace = null;
try {
workspace = GetWorkspaceObject();
workspace.DisconnectWorkspace(workspaceID);
}
catch (objException) {
workspace = null;
}
}
function onAuthenticated() {
var workspace = null;
var isOnAuthenticatedCalled = false;
if (workspaceID != null && workspaceID != "") {
try {
workspace = GetWorkspaceObject();
workspace.StartWorkspace(workspaceID, domainUserName, password, rdpCertificates, 1200000, 0);
var countUnauthenticatedCredentials = true;
var isWorkspaceCredentialSpecified = workspace.IsWorkspaceCredentialSpecified(workspaceID, countUnauthenticatedCredentials);
if (isWorkspaceCredentialSpecified) {
isOnAuthenticatedCalled = true;
workspace.OnAuthenticated(workspaceID, domainUserName);
}
setTimeout("onAutoDisconnect()", 1200000);
}
catch (objException) {
workspace = null;
var errorCode = (objException.number & 0xFFFF);
if (isOnAuthenticatedCalled) {
if (errorCode == 183) {
// 183 = ERROR_ALREADY_EXISTS.
}
else if (errorCode == 1168) {
// 1168 = ERROR_NOT_FOUND.
}
}
}
}
}
function GetWorkspaceObject() {
var objClientShell = null;
if (g_workspace == null) {
objClientShell = new ActiveXObject("MsRdpWebAccess.MsRdpClientShell");
g_workspace = objClientShell.MsRdpWorkspace;
}
return g_workspace;
}
function LaunchRemoteApp() {
var msRdpClientShell = document.all.MsRdpClient;
msRdpClientShell.PublicMode = true;
msRdpClientShell.RdpFileContents = <%= RDPContents %>;
try {
msRdpClientShell.Launch();
}
catch (e) {
throw e;
}
}
</script>
</head>
<body onload="onAuthenticated();">
<form name="form1" method="post" action="default.aspx" id="form1">
<object name="MsRdpClient" width="0" height="0" id="MsRdpClient" classid="CLSID:6A5B0C7C-5CCB-4F10-A043-B8DE007E1952" type="application/x-oleobject"></object>
YourAppName
</form>
</body>
</html>
Then I created a template RDP file with all the correct content. Notice the remoteapplicationcmdline value has some dummy command line parameters (FirstName, LastName, CustomerID). You'll replace these as appropriate in your code.
redirectclipboard:i:0
redirectposdevices:i:0
redirectprinters:i:0
redirectcomports:i:0
redirectsmartcards:i:0
devicestoredirect:s:
drivestoredirect:s:
redirectdrives:i:0
session bpp:i:32
prompt for credentials:i:0
span monitors:i:0
use multimon:i:0
remoteapplicationmode:i:1
server port:i:3389
allow font smoothing:i:1
promptcredentialonce:i:1
authentication level:i:2
gatewayusagemethod:i:2
gatewayprofileusagemethod:i:0
gatewaycredentialssource:i:0
full address:s:[RemoteAppMachineName]
alternate shell:s:||[YourAppName]
remoteapplicationprogram:s:||[YourAppName]
gatewayhostname:s:
remoteapplicationname:s:[YourAppName]
remoteapplicationcmdline:s:/FirstName:{0} /LastName:{1} /CustomerID:{2}
Workspace Id:s:[RemoteAppMachineName]
Then in the code behind, I load the template rdp file, replace the command line arguments, write to a temp rdp file, sign the temp rdp file, and embed the resulting contents into the javascript at <%= RdpFileContents %>
private string GetRDPContents()
{
FileInfo fileInfo = new FileInfo(Path.Combine(Server.MapPath("~"), "Template.rdp"));
string[] unsignedRDPContents = File.ReadAllLines(fileInfo.FullName);
for (int i = 0; i < unsignedRDPContents.Length; i++)
{
if (unsignedRDPContents[i].IndexOf("remoteapplicationcmdline") != -1)
unsignedRDPContents[i] = String.Format(unsignedRDPContents[i], FirstName, LastName, CustomerID);
}
string tempFileName = Path.Combine(Server.MapPath("~"), Guid.NewGuid().ToString() + ".rdp");
File.WriteAllLines(tempFileName, unsignedRDPContents);
InvokeRDPSign(tempFileName, certificateThumbprint);
string[] signedRDPContents = File.ReadAllLines(tempFileName);
File.Delete(tempFileName);
// This escape function is identical to the javascript escape function.
return String.Format("unescape('{0}')", Microsoft.JScript.GlobalObject.escape(String.Join("\r\n", signedRDPContents)));
}
// This is the certificate's thumbprint.
private const string certificateThumbprint = "04a85503a810cad89f25d3f14c48245f499773c4";
private void InvokeRDPSign(string fileName, string certificateThumbPrint)
{
Process rdpSign = new Process();
rdpSign.StartInfo.FileName = "rdpsign.exe";
rdpSign.StartInfo.Arguments = String.Format("/sha1 {0} \"{1}\"", certificateThumbPrint, fileName);
rdpSign.StartInfo.UseShellExecute = false;
rdpSign.StartInfo.RedirectStandardOutput = true;
rdpSign.StartInfo.RedirectStandardInput = true;
rdpSign.StartInfo.RedirectStandardError = true;
rdpSign.StartInfo.WorkingDirectory = Server.MapPath("~");
rdpSign.Start();
string signingOutput = rdpSign.StandardOutput.ReadToEnd();
rdpSign.WaitForExit();
int exitCode = rdpSign.ExitCode;
}
The final javascript will look something like this:
function LaunchRemoteApp() {
var msRdpClientShell = document.all.MsRdpClient;
msRdpClientShell.PublicMode = true;
msRdpClientShell.RdpFileContents = unescape('redirectclipboard%3Ai%3A0%0D%0A%0D%0Aredirectposdevices%3Ai%3A0%0D%0A%0D%0Aredirectprinters%3Ai%3A0%0D%0A%0D%0Aredirectcomports%3Ai%3A0%0D%0A%0D%0Aredirectsmartcards%3Ai%3A0%0D%0A%0D%0Adevicestoredirect%3As%3A%0D%0A%0D%0Adrivestoredirect%3As%3A%0D%0A%0D%0Aredirectdrives%3Ai%3A0%0D%0A%0D%0Asession%20bpp%3Ai%3A32%0D%0A%0D%0Aprompt%20for%20credentials%3Ai%3A0%0D%0A%0D%0Aspan%20monitors%3Ai%3A0%0D%0A%0D%0Ause%20multimon%3Ai%3A0%0D%0A%0D%0Aremoteapplicationmode%3Ai%3A1%0D%0A%0D%0Aserver%20port%3Ai%3A3389%0D%0A%0D%0Aallow%20font%20smoothing%3Ai%3A1%0D%0A%0D%0Apromptcredentialonce%3Ai%3A1%0D%0A%0D%0Aauthentication%20level%3Ai%3A2%0D%0A%0D%0Agatewayusagemethod%3Ai%3A2%0D%0A%0D%0Agatewayprofileusagemethod%3Ai%3A0%0D%0A%0D%0Agatewaycredentialssource%3Ai%3A0%0D%0A%0D%0Afull%20address%3As%3A[YourMachineName]%0D%0A%0D%0Aalternate%20shell%3As%3A%7C%7C[YourAppName]%0D%0A%0D%0Aremoteapplicationprogram%3As%3A%7C%7C[YourAppName]%0D%0A%0D%0Agatewayhostname%3As%3A%0D%0A%0D%0Aremoteapplicationname%3As%3A[YourAppName]%0D%0A%0D%0Aremoteapplicationcmdline%3As%3A/FirstName%3AJon%20/LastName%3ADoe%20/CustomerID%3A7921385%0D%0A%0D%0Aworkspace%20id%3As%3A[YourMachineName]%0D%0A%0D%0Aalternate%20full%20address%3As%3A[YourMachineName]%0D%0A%0D%0Asignscope%3As%3AFull%20Address%2CAlternate%20Full%20Address%2CServer%20Port%2CGatewayHostname%2CGatewayUsageMethod%2CGatewayProfileUsageMethod%2CGatewayCredentialsSource%2CPromptCredentialOnce%2CAlternate%20Shell%2CRemoteApplicationProgram%2CRemoteApplicationMode%2CRemoteApplicationName%2CRemoteApplicationCmdLine%2CPrompt%20For%20Credentials%2CAuthentication%20Level%2CRedirectDrives%2CRedirectPrinters%2CRedirectCOMPorts%2CRedirectSmartCards%2CRedirectPOSDevices%2CRedirectClipboard%2CDevicesToRedirect%2CDrivesToRedirect%0D%0A%0D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pZ2ljZXJ0LmNvbTElMCMGA1UEAxMc%20%20RGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgQ0EtMwIQDyZO5SPrkaGllR9mdxiQpTAJ%20%20BgUrDgMCGgUAMA0GCSqGSIb3DQEBAQUABIIBAJGNkWq+QeMYRPJZG3+Kwen96uy3%20%208V+6iE5pnGAFzrBPuN1BhvmkhiSDKLcT4ZSI07PNAsuZFLFz7g8yAuVWyWkfCJkn%20%20TAzj7kFCZBUP82ousA+Pp0VMdmfKjKfqOlJKPMpNJ6AKSHT1aAw4N2ZuzhnddZ/I%20%20HzrOoIJ9McvrMzGQSmhA4MefBg1ppqbudo1QCvVfOdwWg5KijHKIkVOe9BI8Dyic%20%20+cLu3iJ1jF3IMwMQb2Q4JX/FgIFMy9Hf12uhx9HP0JnR2sp5AnwfAGqPj2RSCmoA%20%20Px1XJxuea7WjMBnfTCUuQjuD/hfYdyTmj95G2nuZZM2Za4438JWPMPMW5ro%3D%20%20%0D%0A');
try {
msRdpClientShell.Launch();
}
catch (e) {
throw e;
}
}
I tried to escape the rdp contents myself but could never get it to work. If you don't have access to Microsoft.JScript.GlobalObject.escape() function, you can try it yourself. Here are some of the character entity references I know of:
Replace : with %3A
Replace | with %7C
Replace \r\n with %0D%0A
Replace spaces with %20
No extra spaces after lines.

Related

ASP .Net Core file upload - getting form data when [DisableFormValueModelBinding] attribute is in place

I went ahead and implemented an ASP .Net Core file upload controller per the documentation and it requires using a [DisableFormValueModelBinding] attribute for streaming large files. I got that working fine. Unfortunately, when using that attribute it seems to block my JSON properties coming in from the form.
Is there any way to get both the file and the form data here? Here is my controller code (the request.form calls are where I am having issues):
[Route("{caseNbr:int}/Document")]
[ResponseType(typeof(CaseDocumentModel))]
[DisableFormValueModelBinding]
[HttpPost]
public async Task<IActionResult> PostDocument(int caseNbr)
{
string errorTrackingFileName = string.Empty;
try
{
UserSessionModel userSessionModel = SessionExtensions.CurrentUserSession;
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest("Bad Request");
}
var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
return BadRequest("Bad Request");
}
var fileName = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
errorTrackingFileName = fileName;
var trustedFileNameForFileStorage = fileName; //Path.GetRandomFileName();
var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit);
if (!ModelState.IsValid)
{
return BadRequest("Bad Request");
}
using (var targetStream = System.IO.File.Create(Path.Combine(_tempFilePath, trustedFileNameForFileStorage)))
{
await targetStream.WriteAsync(streamedFileContent);
**//This is where I am having trouble:**
string descrip = HttpContext.Request.Form["Description"].ToString();
string docType = HttpContext.Request.Form["DocType"].ToString() ?? "Document";
bool isGeneralFileUpload = false;
if (string.IsNullOrWhiteSpace(Request.Form["GeneralFileUpload"]) == false && AppHelper.IsBool(Request.Form["GeneralFileUpload"]))
isGeneralFileUpload = bool.Parse(Request.Form["GeneralFileUpload"]);
int transcriptionJobId = 0;
if (string.IsNullOrWhiteSpace(Request.Form["TranscriptionJobId"]) == false && AppHelper.IsNumeric(Request.Form["TranscriptionJobId"]))
transcriptionJobId = int.Parse(Request.Form["TranscriptionJobId"]);
CaseDocumentModel createdCaseDocumentModel;
if (docType.Equals("Dictation"))
createdCaseDocumentModel = DictationRepository.ProcessDictationFile(userSessionModel.DBID, caseNbr, _tempFilePath, fileName, userSessionModel);
else if (isGeneralFileUpload)
createdCaseDocumentModel = DashboardAdjusterRepository.CreateGeneralFileUploadDocument(_tempFilePath, fileName, userSessionModel, docType, descrip);
else if (docType.Equals("Transcription"))
createdCaseDocumentModel = TranscriptionRepository.UploadTranscriptionFile(userSessionModel.DBID, _tempFilePath, fileName, userSessionModel, transcriptionJobId);
else
createdCaseDocumentModel = CaseRepository.CreateCaseDocumentRecord(userSessionModel.DBID, caseNbr, descrip, docType, _tempFilePath, fileName, userSessionModel);
return Ok(createdCaseDocumentModel);
}
}
// Drain any remaining section body that hasn't been consumed and
// read the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
}
catch (Exception ex)
{
AppHelper.WriteErrorLog("CaseController PostDocument failed due to " + ex.Message + " case number was " + caseNbr + " file name was " + errorTrackingFileName);
return BadRequest("Bad Request");
}
return BadRequest("Bad Request");
}
Here is a sample call with Postman:
Screen shot of Postman

Get Array of Bytes from ASP.NET WEB API to be rendered in PDF using React/Redux

I have this action on my WEBAPI´s controller using .NET that returns bytes from SSRS report link:
public IHttpActionResult GetReport(int? Id)
{
if (Id == null)
{
return NotFound();
}
var reportServer = ConfigurationManager.AppSettings["Report"];
var reportPath = $"{reportServer}/myReport&Id={Id}&rs:Format=PDF";
WebClient Client = new WebClient();
Client.UseDefaultCredentials = true;
byte[] reportBytes = Client.DownloadData(reportPath);
var reportBase64 = Convert.ToBase64String(reportBytes);
return Ok(reportBase64);
}
When i try to generate the PDF from this return, using this react/redux code ( i am using axios)....
//...code
const reportBlob = new Blob([myReportData], { type: "application/pdf" });
const reportBlobUrl = URL.createObjectURL(reportBlob);
window.open(reportBlobUrl);
.....it oppened a new browser´s tab with PDF template BUT showing PDF Error as: 'FAILED TO LOAD PDF document'.
No anwsers anywhere help me resolving this problem. :(
Note: the 'axios' call it´s returning the same array of bytes as the WEBAPI return, so as the 'myReportData' variable.
So i figured out by my self after 4 days. Anyone that needed this functionality (render the SSRS report in PDF within c# code returning PDF bytes from a ASP.NET WEB API, here is the what you have to do within your webapi controller to generate the PDF bytes from report viewer namespace to be sent to your React app using Redux.
WEB API ASP.NET (.NET Framework 4.6 using VS 2019):
note: first option i´ts commented and works the same way the option 2 that i´d prefer.
// return type is Bytes
[HttpGet]
[Route("api/YourReport/{testId}")]
public async Task<IHttpActionResult> GetYourReportAsync(int? testId)
{
if (testId == null)
{
return NotFound();
}
try
{
// 1. Works in this way without '?' on the end of the URL
// URL should be like this: "http://-yourServerName-/reportserver/ReportExecution2005.asmx"
//ReportExecutionService rs = new ReportExecutionService();
//rs.Credentials = CredentialCache.DefaultCredentials;
//rs.Url = "http://-yourServerNamein here-/reportserver/ReportExecution2005.asmx";
//// Render arguments
//byte[] result = null;
//string reportPath = "/-yourReportsFolderName-/-yourReportName-";
//string format = "PDF";
//string historyID = null;
//string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
//// parameters
//ParameterValue[] parameters = new ParameterValue[1];
//parameters[0] = new ParameterValue();
//parameters[0].Name = "yourId";
//parameters[0].Value = testId.ToString();
//string encoding;
//string mimeType;
//string extension;
//Warning[] warnings = null;
//string[] streamIDs = null;
//ExecutionInfo execInfo = new ExecutionInfo();
//ExecutionHeader execHeader = new ExecutionHeader();
//rs.ExecutionHeaderValue = execHeader;
//execInfo = rs.LoadReport(reportPath, historyID);
//rs.SetExecutionParameters(parameters, "en-us");
//string SessionId = rs.ExecutionHeaderValue.ExecutionID;
//try
//{
//// result type is bytes
// result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
//}
//catch (SoapException)
//{
// throw;
//}
//// below, just in case that you want to save it locally in PDF format.
//try
//{
// FileStream stream = File.Create(#"c:\report.pdf", result.Length);
//
// stream.Write(result, 0, result.Length);
// Console.WriteLine("Result written to the file.");
// stream.Close();
//}
//catch (Exception)
//{
// throw;
//}
//return await Task.Run(() => Ok(result));
// 2. Works this way also with '?' on the end of the URL
// URL should be like this: "http://-yourServerName-/reportserver/ReportExecution2005.asmx?"
using (ReportViewer yourReportViewer = new ReportViewer())
{
yourReportViewer.ProcessingMode = ProcessingMode.Remote;
// get the values from your web.config.
yourReportViewer.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["youtReport"]);
yourReportViewer.ServerReport.ReportPath = $"/yourReportsFolder/yourReport";
;
ReportParameter testPlanIdParameter = new ReportParameter();
testPlanIdParameter.Name = "yourId";
testPlanIdParameter.Values.Add(testId.ToString());
yourReportViewer.ServerReport.SetParameters(new ReportParameter[] { testIdParameter });
byte[] yourReportBytes = yourReportViewer.ServerReport.Render("PDF");
return await Task.Run(() => Ok(yourReportBytes));
}
}
catch (SoapException)
{
throw;
}
catch (Exception)
{
throw ;
}
}
REACT/REDUX nstrong textote: you have to convert the stream of bytes returned from your WEB API Controller into BLOB format to render it in a new brownser tab in PDF format/type.
a. the button action/behavior
<div className="btn-group-vertical" role="group">
<button className="btn btn-sm btn-success ml-2 mb-2" style={{ width: '160px' }} onClick={(e) => openReport(e, testId)}>
<i className="fas fa-print"></i>
Report
</button>
</div>
b. the component ( i am omiting the redux part (reducers, actions, apiservice...)
openReport(event, item) {
event.preventDefault();
this.props.actions.loadReport(item);
this.setState({ Report: this.props.Report });
const ReportData = this.state.Report;
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
const ReportBlob = b64toBlob(ReportData, 'application/pdf');
const ReportBlobUrl = URL.createObjectURL(ReportBlob);
window.open(ReportBlobUrl);
}

Saving Files to SQL server using knockout js

I have a requirement on my web app to save multiple attachments to my SQL server. The attachments can be in any format. Is it possible to create a knockout viewmodel to encode the file type on client side to binary and transferring that binary info to my SQL server?
I currently have this method in my REST service:
[OperationContract, WebInvoke(ResponseFormat = WebMessageFormat.Json)]
public string PostAttachments (string FileName)
{
try
{
var MyAttachment = new Binary(File.ReadAllBytes(FileName));
return "Attachments Created";
}
catch (Exception ex)
{
return DefaultError + ex;
}
}
I know this is incorrect but I am really not sure how to do this file upload. I believe I am over complicating it. Any Assistance would be greatly appreciated.
You will have to transfer the buffer to the server not just the filename, since the file exists on the client.
I used the HTML5 FileReader in my last KO project
First a custom binding to read the file from the DOM element
(function () {
ko.bindingHandlers.file = {
init: function (element, valueAccessor, allBindingsAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
writeValueToProperty(valueAccessor(), allBindingsAccessor, "file", element.files[0]);
});
},
update: function (element, valueAccessor) {
if (ko.utils.unwrapObservable(valueAccessor()) == null) {
element.value = "";
}
}
};
var writeValueToProperty = function (property, allBindingsAccessor, key, value, checkIfDifferent) {
if (!property || !ko.isObservable(property)) {
var propWriters = allBindingsAccessor()['_ko_property_writers'];
if (propWriters && propWriters[key])
propWriters[key](value);
} else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
property(value);
}
};
} ());
FileReader usage (code specific for how I used it in my app). Check the FileReader part only.
Note if you have large files you need to stream instead
processFiles: function (viewModel, callback) {
var files = [];
ko.utils.arrayForEach(viewModel.files, function (file) {
if (file.fileUpload() == null) return;
var count = Enumerable.From(viewModel.files)
.Where(function(f) { return f.fileUpload() != null; })
.Count();
var reader = new FileReader();
reader.onload = function (e) {
var base64 = e.target.result.substr(e.target.result.indexOf(",") + 1);
files.push({ Type: file.type, Data: base64, Filename: file.fileUpload().name });
if (files.length == count) {
callback(files);
}
};
reader.readAsDataURL(file.fileUpload());
});
}
Update
Like said this is code for my use case, you will need to change it to fit your purpose
<div data-bind="foreach: files">
<p><label data-bind="text: typeName"></label><input data-bind="file: fileUpload" type="file" /></p>
</div>
Controller (I would use WebApi if I did this today)
public JsonResult UploadFiles(IEnumerable<FileUploadViewModel> uploads)
{
fileRepository.SaveUploadedFiles(Mapper.Map<IEnumerable<FileUploadViewModel>, IEnumerable <FileUpload>> (uploads));
return string.Empty.AsJson();
}
FileUploadViewModel
public class FileUploadViewModel
{
public FileType Type { get; set; }
public string Filename { get; set; }
public string Data { get; set; }
}
Automapper config
Mapper.CreateMap<FileUploadViewModel, FileUpload>()
.ForMember(to => to.Buffer, opt => opt.MapFrom(from => Convert.FromBase64String(from.Data)));

Create multiple sharepoint list items based multiple uploaded files SP2010

I would like to create sharepoint list items based on selected multiple files from local drive. After uploading selected multiple files list should contains new list items (title is file name) with attachments (one attachment/uploaded file).
Ok I extended my custom webpart (with dynatree) on that list using http://www.plupload.com/ and creating page for saving attachments.
public partial class ImportMultipleFilesAsListItems : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
//request form parameters comes from plupload
int parentFolderKey = int.Parse(Request.Form["key"]);
var file = Request.Files[0];
SPList list = SPContext.Current.Web.GetList(Request.Form["listUrl"]);
SPListItem folderItem = list.GetItemById(parentFolderKey);
if (folderItem != null)
{
string parentFolder = null;
if (folderItem.Folder != null)
{
parentFolder = folderItem.Folder.Url;
}
else
{
int slashIndx = folderItem.Url.LastIndexOf('/');
parentFolder = folderItem.Url.Substring(0, slashIndx);
}
SPListItem childFile = list.AddItem(parentFolder, SPFileSystemObjectType.File);
childFile["Title"] = file.FileName;
childFile["IsFolder"] = 0;
childFile["DocParentId"] = parentFolderKey;
childFile.UpdateOverwriteVersion();
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
childFile.Attachments.AddNow(file.FileName, data);
}
}
}
$(function () {
var listInfo = new Object();
listInfo.key = null;
listInfo.listUrl = ctx.listUrlDir;
listInfo.__REQUESTDIGEST = $('#__REQUESTDIGEST').val();
$("#uploader").pluploadQueue({
// General settings
runtimes: 'browserplus,html5,html4',
url: $('#uploadMultipleFilesUrl').val(),
max_file_size: '50mb',
chunk_size: '1mb',
multipart_params: listInfo,
rename: true
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
$("#uploader").hide();
});

How to programmatically set the task outcome (task response) of a Nintex Flexi Task?

Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}