Exemple #1
0
        protected async override Task <FormResult> ExecuteAsync(AsyncCodeActivityContext context)
        {
            var        xmlString = Form.Get(context);
            FormResult result    = null;
            string     json      = "";


            var           definition = FormBuilder.Default.GetDefinition(xmlString, freeze: false);
            List <string> fields     = GenericTools.MainWindow.Dispatcher.Invoke <List <string> >(() =>
            {
                List <string> _fields = new List <string>();
                foreach (DataFormField f in definition.GetElements().Where(x => x is DataFormField))
                {
                    _fields.Add(f.Key);
                }
                return(_fields);
            });
            var param = new Dictionary <string, object>();
            var vars  = context.DataContext.GetProperties();

            foreach (dynamic v in vars)
            {
                var value = v.GetValue(context.DataContext);
                if (value != null)
                {
                    //_payload.Add(v.DisplayName, value);
                    try
                    {
                        if (fields.Contains(v.DisplayName))
                        {
                            var test = new { value = value };
                            if (value.GetType() == typeof(System.Data.DataTable))
                            {
                                continue;
                            }
                            if (value.GetType() == typeof(System.Data.DataView))
                            {
                                continue;
                            }
                            if (value.GetType() == typeof(System.Data.DataRowView))
                            {
                                continue;
                            }
                            //
                            var asjson = JObject.FromObject(test);
                            param[v.DisplayName] = value;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    param[v.DisplayName] = value;
                }
            }

            Exception LastError = null;
            var       res       = GenericTools.MainWindow.Dispatcher.Invoke <FormResult>(() =>
            {
                var f      = new Form(xmlString);
                f.defaults = param;
                f.Topmost  = true;
                f.Owner    = GenericTools.MainWindow;
                if (f.ShowDialog() == false)
                {
                    if (f.LastError != null)
                    {
                        LastError = f.LastError;
                    }
                }
                var _res = new FormResult();
                if (f.actionContext != null && f.actionContext.Action != null)
                {
                    _res.Action = f.actionContext.Action.ToString();
                }
                _res.Model = f.CurrentModel;
                return(_res);
            });

            if (LastError != null)
            {
                throw LastError;
            }
            json   = JsonConvert.SerializeObject(res, Formatting.Indented);
            result = JsonConvert.DeserializeObject <FormResult>(json);
            if (result.Model != null)
            {
                foreach (var prop in result.Model)
                {
                    var myVar = context.DataContext.GetProperties().Find(prop.Key, true);
                    if (myVar != null)
                    {
                        if (myVar.PropertyType == typeof(int))
                        {
                            if (prop.Value != null)
                            {
                                myVar.SetValue(context.DataContext, int.Parse(prop.Value.ToString()));
                            }
                        }
                        else
                        {
                            if (prop.Value != null)
                            {
                                myVar.SetValue(context.DataContext, prop.Value);
                            }
                        }
                    }
                    else
                    {
                        Log.Debug("Recived property " + prop.Key + " but no variable exists to save the value in " + prop.Value);
                    }
                }
            }
            await Task.Delay(1);

            return(result);
        }
        protected async override Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            string                 connString       = null;
            SecureString           connSecureString = null;
            string                 provName         = null;
            string                 sql                = string.Empty;
            int                    commandTimeout     = TimeoutMS.Get(context);
            DatabaseConnection     existingConnection = null;
            DBExecuteCommandResult affectedRecords    = null;

            if (commandTimeout < 0)
            {
                throw new ArgumentException(Resources.TimeoutMSException, "TimeoutMS");
            }
            Dictionary <string, Tuple <object, ArgumentDirection> > parameters = null;
            var continueOnError = ContinueOnError.Get(context);

            try
            {
                sql = Sql.Get(context);
                existingConnection = DbConnection = ExistingDbConnection.Get(context);
                connString         = ConnectionString.Get(context);
                connSecureString   = ConnectionSecureString.Get(context);
                provName           = ProviderName.Get(context);

                if (Parameters != null)
                {
                    parameters = new Dictionary <string, Tuple <object, ArgumentDirection> >();
                    foreach (var param in Parameters)
                    {
                        parameters.Add(param.Key, new Tuple <object, ArgumentDirection>(param.Value.Get(context), param.Value.Direction));
                    }
                }
                ConnectionHelper.ConnectionValidation(existingConnection, connSecureString, connString, provName);
                // create the action for doing the actual work
                affectedRecords = await Task.Run(() =>
                {
                    DBExecuteCommandResult executeResult = new DBExecuteCommandResult();
                    if (DbConnection == null)
                    {
                        DbConnection = new DatabaseConnection().Initialize(connString ?? new NetworkCredential("", connSecureString).Password, provName);
                    }
                    if (DbConnection == null)
                    {
                        return(executeResult);
                    }
                    executeResult = new DBExecuteCommandResult(DbConnection.Execute(sql, parameters, commandTimeout, CommandType), parameters);
                    return(executeResult);
                });
            }
            catch (Exception ex)
            {
                HandleException(ex, continueOnError);
            }
            finally
            {
                if (existingConnection == null)
                {
                    DbConnection?.Dispose();
                }
            }

            return(asyncCodeActivityContext =>
            {
                AffectedRecords.Set(asyncCodeActivityContext, affectedRecords.Result);
                foreach (var param in affectedRecords.ParametersBind)
                {
                    var currentParam = Parameters[param.Key];
                    if (currentParam.Direction == ArgumentDirection.Out || currentParam.Direction == ArgumentDirection.InOut)
                    {
                        currentParam.Set(asyncCodeActivityContext, param.Value.Item1);
                    }
                }
            });
        }
Exemple #3
0
 protected override void OutputResult(AsyncCodeActivityContext context, List <PredictionExplanation> response)
 {
     Results.Set(context, response);
 }
Exemple #4
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            PropertyDescriptor property = context.DataContext.GetProperties()[ExcelCreate.GetExcelAppTag];
            Excel::Application excelApp = property.GetValue(context.DataContext) as Excel::Application;

            try
            {
                //string sheetName = SheetName.Get(context);
                //string cellName_Begin = CellName_Begin.Get(context);
                //string cellName_End = CellName_End.Get(context);
                //int cellRow_Begin = CellRow_Begin.Get(context);
                //int cellColumn_Begin = CellColumn_Begin.Get(context);
                //int cellRow_End = CellRow_End.Get(context);
                //int cellColumn_End = CellColumn_End.Get(context);

                //Excel::_Worksheet sheet;
                //if (sheetName != null)
                //    sheet = excelApp.ActiveWorkbook.Sheets[sheetName];
                //else
                //    sheet = excelApp.ActiveSheet;

                //Excel::Range range1, range2;
                //range1 = cellName_Begin == null ? sheet.Cells[cellRow_Begin, cellColumn_Begin] : sheet.Range[cellName_Begin];
                //range2 = cellName_End == null ? sheet.Cells[cellRow_End, cellColumn_End] : sheet.Range[cellName_End];
                Excel::_Worksheet sheet;
                Excel::Range      range1, range2;
                RangeFunction.GetRange(excelApp, context, SheetName, CellName_Begin, CellName_End,
                                       CellRow_Begin, CellColumn_Begin, CellRow_End, CellColumn_End,
                                       out sheet, out range1, out range2);
                Excel::Range range = sheet.Range[range1, range2];

                if (!ShiftCells)
                {
                    range.Clear();
                }
                else
                {
                    if (ShiftType == ShiftTypes.ShiftUp)
                    {
                        range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
                    }
                    else if (ShiftType == ShiftTypes.ShiftLeft)
                    {
                        range.Delete(Excel.XlDeleteShiftDirection.xlShiftToLeft);
                    }
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                sheet = null;
                range = null;
                GC.Collect();
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "EXCEL删除区域执行过程出错", e.Message);
                new CommonVariable().realaseProcessExit(excelApp);
            }
            m_Delegate = new runDelegate(Run);
            return(m_Delegate.BeginInvoke(callback, state));
        }
Exemple #5
0
 protected override void AfterExecute(AsyncCodeActivityContext context, object result)
 {
 }
            protected override IAsyncResult BeginMakeMethodCall(AsyncCodeActivityContext context, object target, AsyncCallback callback, object state)
            {
                InvokeMethodInstanceData instance = new InvokeMethodInstanceData
                {
                    TargetObject = target,
                    ActualParameters = EvaluateAndPackParameters(context, this.beginMethod, true),
                };

                int count = instance.ActualParameters.Length;

                instance.ActualParameters[count - 2] = callback;
                instance.ActualParameters[count - 1] = state;
                context.UserState = instance;

                return (IAsyncResult)this.InvokeAndUnwrapExceptions(this.beginFunc, target, instance.ActualParameters);
            }
 protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     return this.methodExecutor.BeginExecuteMethod(context, callback, state);
 }
Exemple #8
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope
            var objectContainer = context.GetFromContext <IObjectContainer>(TwilioApiScope.ParentContainerPropertyTag);

            // Inputs
            var limit = Limit.Get(context);

            var pricings =
                await PhoneNumberPricingWrappers.GetPhoneNumberPricingAsync(objectContainer.Get <ITwilioRestClient>(), limit);

            // Outputs
            return((ctx) => {
                CountryResources.Set(ctx, pricings);
            });
        }
        protected List <object> GetParameters(AsyncCodeActivityContext context)
        {
            List <object> parameters = ParametersList.Get(context) ?? Parameters.Select(arg => arg.Get(context)).ToList();

            return(parameters);
        }
Exemple #10
0
 protected abstract void EndMakeMethodCall(AsyncCodeActivityContext context, IAsyncResult result);
Exemple #11
0
 protected override Task <Func <Task> > ExecuteAsync(AsyncCodeActivityContext context) => this.ResultTaskFuncTask.Get(context);
Exemple #12
0
 protected abstract IAsyncResult BeginMakeMethodCall(AsyncCodeActivityContext context, object target, AsyncCallback callback, object state);
 protected abstract void EndMakeMethodCall(AsyncCodeActivityContext context, IAsyncResult result);
 protected abstract IAsyncResult BeginMakeMethodCall(AsyncCodeActivityContext context, object target, AsyncCallback callback, object state);
Exemple #15
0
 protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
 {
     this.methodExecutor.EndExecuteMethod(context, result);
 }
Exemple #16
0
 protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     throw new NotImplementedException();
 }
Exemple #17
0
            protected override IAsyncResult BeginMakeMethodCall(AsyncCodeActivityContext context, object target, AsyncCallback callback, object state)
            {
                object[] actualParameters = EvaluateAndPackParameters(context, this.syncMethod, false);

                object result = this.InvokeAndUnwrapExceptions(this.func, target, actualParameters);

                SetOutArgumentAndReturnValue(context, result, actualParameters);

                return new CompletedAsyncResult(callback, state);
            }
Exemple #18
0
 protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
 {
     throw new NotImplementedException();
 }
Exemple #19
0
 protected override IAsyncResult BeginMakeMethodCall(AsyncCodeActivityContext context, object target, AsyncCallback callback, object state)
 {
     InvokeMethodInstanceData instance = new InvokeMethodInstanceData
     {
         TargetObject = target,
         ActualParameters = EvaluateAndPackParameters(context, this.asyncMethod, false),
     };
     return new ExecuteAsyncResult(instance, this, callback, state);
 }
Exemple #20
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            PropertyDescriptor ftpSessionProperty = context.DataContext.GetProperties()[WithFtpSession.FtpSessionPropertyName];
            IFtpSession        ftpSession         = ftpSessionProperty?.GetValue(context.DataContext) as IFtpSession;

            if (ftpSession == null)
            {
                throw new InvalidOperationException(Resources.FTPSessionNotFoundException);
            }

            string localPath  = LocalPath.Get(context);
            string remotePath = RemotePath.Get(context);

            if (Directory.Exists(localPath))
            {
                if (string.IsNullOrWhiteSpace(Path.GetExtension(remotePath)))
                {
                    if (!(await ftpSession.DirectoryExistsAsync(remotePath, cancellationToken)))
                    {
                        if (Create)
                        {
                            await ftpSession.CreateDirectoryAsync(remotePath, cancellationToken);
                        }
                        else
                        {
                            throw new ArgumentException(string.Format(Resources.PathNotFoundException, remotePath));
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException(Resources.IncompatiblePathsException);
                }
            }
            else
            {
                if (File.Exists(localPath))
                {
                    if (string.IsNullOrWhiteSpace(Path.GetExtension(remotePath)))
                    {
                        remotePath = FtpConfiguration.CombinePaths(remotePath, Path.GetFileName(localPath));
                    }

                    string directoryPath = FtpConfiguration.GetDirectoryPath(remotePath);

                    if (!(await ftpSession.DirectoryExistsAsync(directoryPath, cancellationToken)))
                    {
                        if (Create)
                        {
                            await ftpSession.CreateDirectoryAsync(directoryPath, cancellationToken);
                        }
                        else
                        {
                            throw new InvalidOperationException(string.Format(Resources.PathNotFoundException, directoryPath));
                        }
                    }
                }
                else
                {
                    throw new ArgumentException(string.Format(Resources.PathNotFoundException, localPath));
                }
            }

            await ftpSession.UploadAsync(localPath, remotePath, Overwrite, Recursive, cancellationToken);

            return((asyncCodeActivityContext) =>
            {
            });
        }
 public void EndExecuteMethod(AsyncCodeActivityContext context, IAsyncResult result)
 {
     EndMakeMethodCall(context, result); // defer to concrete instance for [....]/async variations
 }
Exemple #22
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope
            var objectContainer = context.GetFromContext <IObjectContainer>(TwilioApiScope.ParentContainerPropertyTag);

            // Inputs
            var faxsid      = FaxSid.Get(context);
            var faxmediasid = FaxMediaSid.Get(context);

            var media = await FaxMediaWrappers.GetFaxMediaAsync(objectContainer.Get <ITwilioRestClient>(), faxsid,
                                                                faxmediasid);

            // Outputs
            return((ctx) => {
                FaxMedia.Set(ctx, media);
            });
        }
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var gridid   = GridID.Get(context);
            var rowindex = RowIndex.Get(context);
            var columnid = ColumnID.Get(context);

            ///////////////////////////
            // Add execution logic HERE
            SAPAuto objSAPAuto = new SAPAuto();

            context.SetValue(CellValue, objSAPAuto.Grid_GetCellValue(gridid, rowindex, columnid));
            ///////////////////////////

            // Outputs
            return((ctx) => {
                CellValue.Set(ctx, null);
            });
        }
Exemple #24
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            PropertyDescriptor property = context.DataContext.GetProperties()[ExcelCreate.GetExcelAppTag];
            Excel::Application excelApp = property.GetValue(context.DataContext) as Excel::Application;

            try
            {
                string sheetName        = SheetName.Get(context);
                string cellName_Begin   = CellName_Begin.Get(context);
                string cellName_End     = CellName_End.Get(context);
                int    cellRow_Begin    = CellRow_Begin.Get(context);
                int    cellColumn_Begin = CellColumn_Begin.Get(context);
                int    cellRow_End      = CellRow_End.Get(context);
                int    cellColumn_End   = CellColumn_End.Get(context);

                Excel::_Worksheet sheet;
                if (sheetName != null)
                {
                    sheet = excelApp.ActiveWorkbook.Sheets[sheetName];
                }
                else
                {
                    sheet = excelApp.ActiveSheet;
                }

                Excel::Range range1, range2;
                range1 = cellName_Begin == null ? sheet.Cells[cellRow_Begin, cellColumn_Begin] : sheet.Range[cellName_Begin];
                range2 = cellName_End == null ? sheet.Cells[cellRow_End, cellColumn_End] : sheet.Range[cellName_End];
                Excel::Range range3 = sheet.Range[range1, range2];

                System.Data.DataTable dt = new System.Data.DataTable();
                int iRowCount            = range3.Rows.Count;
                int iColCount            = range3.Columns.Count;
                int rowBegin             = range3.Row;
                int colBegin             = range3.Column;

                //生成列头
                for (int i = 0; i < iColCount; i++)
                {
                    var name = "column" + i;
                    if (isTitle)
                    {
                        var txt = ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[rowBegin, i + colBegin]).Text.ToString();
                        if (!string.IsNullOrEmpty(txt))
                        {
                            name = txt;
                        }
                    }
                    while (dt.Columns.Contains(name))
                    {
                        name = name + "_1";//重复行名称会报错。
                    }
                    dt.Columns.Add(new System.Data.DataColumn(name, typeof(string)));
                }
                //生成行数据
                Microsoft.Office.Interop.Excel.Range range;
                int rowIdx = isTitle ? 2 : 1;
                for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
                {
                    System.Data.DataRow dr = dt.NewRow();
                    for (int iCol = 1; iCol <= iColCount; iCol++)
                    {
                        range        = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[iRow + rowBegin - 1, iCol + colBegin - 1];
                        dr[iCol - 1] = (range.Value2 == null) ? "" : range.Value2;
                    }
                    dt.Rows.Add(dr);
                }
                DataTable.Set(context, dt);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                sheet = null;
                GC.Collect();
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "EXCEL读取区域执行过程出错", e.Message);
                new CommonVariable().realaseProcessExit(excelApp);
            }
            m_Delegate = new runDelegate(Run);
            return(m_Delegate.BeginInvoke(callback, state));
        }
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            PropertyDescriptor ftpSessionProperty = context.DataContext.GetProperties()[WithFtpSession.FtpSessionPropertyName];
            IFtpSession        ftpSession         = ftpSessionProperty?.GetValue(context.DataContext) as IFtpSession;

            if (ftpSession == null)
            {
                throw new InvalidOperationException("FTPSessionNotFoundException");
            }

            string remotePath = RemotePath.Get(context);
            string localPath  = LocalPath.Get(context);

            FtpObjectType objectType = await ftpSession.GetObjectTypeAsync(remotePath, cancellationToken);

            if (objectType == FtpObjectType.Directory)
            {
                if (string.IsNullOrWhiteSpace(Path.GetExtension(localPath)))
                {
                    if (!Directory.Exists(localPath))
                    {
                        if (Create)
                        {
                            Directory.CreateDirectory(localPath);
                        }
                        else
                        {
                            throw new ArgumentException("PathNotFoundException", localPath);
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException("IncompatiblePathsException");
                }
            }
            else
            {
                if (objectType == FtpObjectType.File)
                {
                    if (string.IsNullOrWhiteSpace(Path.GetExtension(localPath)))
                    {
                        localPath = Path.Combine(localPath, Path.GetFileName(remotePath));
                    }

                    string directoryPath = Path.GetDirectoryName(localPath);

                    if (!Directory.Exists(directoryPath))
                    {
                        if (Create)
                        {
                            Directory.CreateDirectory(directoryPath);
                        }
                        else
                        {
                            throw new InvalidOperationException("PathNotFoundException");
                        }
                    }
                }
                else
                {
                    throw new NotImplementedException("UnsupportedObjectTypeException");
                }
            }

            if (Overwrite)
            {
                await ftpSession.DownloadAsync(remotePath, localPath, FtpLocalExists.Overwrite, Recursive, cancellationToken);
            }
            else
            {
                await ftpSession.DownloadAsync(remotePath, localPath, FtpLocalExists.Append, Recursive, cancellationToken);
            }

            return((asyncCodeActivityContext) =>
            {
            });
        }
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            var FFMPEGPath      = ffmpegPath.Get(context);
            var FFMPEGDirectory = FFMPEGPath.Substring(0, FFMPEGPath.LastIndexOf('\\'));

            FFMPEGPath = '"' + FFMPEGPath + '"';
            var inputFile       = InputFile.Get(context);
            var outputFolder    = OutputFolder.Get(context);
            var command         = Command.Get(context);
            var outputContainer = OutputContainer.Get(context);
            var debuggingMode   = DebuggingMode.Get(context);


            var startInfo = new ProcessStartInfo(FFMPEGPath);

            startInfo.WindowStyle      = ProcessWindowStyle.Normal;
            startInfo.WorkingDirectory = FFMPEGDirectory;

            string inputContainer = inputFile.Substring(inputFile.LastIndexOf('.'));

            if (outputContainer == "")
            {
                outputContainer = inputContainer;
            }

            string fileNameWithoutExtensions = inputFile.Replace(inputContainer, "");
            var    fileName = fileNameWithoutExtensions.Substring(fileNameWithoutExtensions.LastIndexOf(@"\"));

            fileName = fileName.Replace(@"\", "");


            var uniqueId = (DateTime.Now.Ticks - new DateTime(2016, 1, 1).Ticks).ToString("x");

            startInfo.Arguments = "-i " + '"' + inputFile + '"' + " " + command + " " + '"' + outputFolder + @"\" + uniqueId + "." + outputContainer + '"';

            if (debuggingMode)
            {
                var processn = new Process();
                processn.StartInfo           = startInfo;
                processn.EnableRaisingEvents = true;
                processn.StartInfo.FileName  = "CMD.EXE";
                processn.StartInfo.Arguments = "/K " + '"' + @FFMPEGPath + " " + startInfo.Arguments + '"';
                processn.Start();
                processn.WaitForExit();
            }
            else
            {
                var processn = Process.Start(startInfo);
                processn.EnableRaisingEvents = true;

                processn.WaitForExit();
            }

            // Outputs
            return((ctx) => {
            });
        }
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var menuid = MenuID.Get(context);

            ///////////////////////////
            // Add execution logic HERE
            SAPAuto objSAPAuto = new SAPAuto();

            objSAPAuto.MenuSelectionByID(menuid);
            ///////////////////////////

            // Outputs
            return((ctx) => {
            });
        }
Exemple #28
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            var FFMPEGPath      = ffmpegPath.Get(context);
            var FFMPEGDirectory = FFMPEGPath.Substring(0, FFMPEGPath.LastIndexOf('\\'));

            FFMPEGPath = '"' + FFMPEGPath + '"';
            var inputFile       = InputFile.Get(context);
            var outputFolder    = OutputFolder.Get(context);
            var outputContainer = OutputContainer.Get(context);
            var command         = Command.Get(context);
            var fontFile        = FontFile.Get(context);
            var debuggingMode   = DebuggingMode.Get(context);
            var text            = Text.Get(context);


            string tempPath     = Path.GetTempPath();
            var    fontFileName = fontFile.Substring(fontFile.LastIndexOf(@"\"));

            fontFileName = fontFileName.Replace(@"\", "");

            String fontFilePath = Path.Combine(tempPath, fontFileName);

            if (!System.IO.File.Exists(fontFilePath))
            {
                System.IO.File.Copy(fontFile, fontFilePath, true);
            }

            var startInfo = new ProcessStartInfo(FFMPEGPath);

            startInfo.WindowStyle      = ProcessWindowStyle.Normal;
            startInfo.WorkingDirectory = tempPath;

            string inputContainer = inputFile.Substring(inputFile.LastIndexOf('.'));

            if (outputContainer == "")
            {
                outputContainer = inputContainer;
            }

            string fileNameWithoutExtensions = inputFile.Replace(inputContainer, "");
            var    fileName = fileNameWithoutExtensions.Substring(fileNameWithoutExtensions.LastIndexOf(@"\"));

            fileName = fileName.Replace(@"\", "");

            var uniqueId = (DateTime.Now.Ticks - new DateTime(2016, 1, 1).Ticks).ToString("x");

            startInfo.Arguments = "-i " + '"' + inputFile + '"' + " " + "-vf drawtext=enable='between(t,2,8)':\"fontfile = " + fontFileName + '"' + ":text=\"" + text + "\":fontcolor=white:fontsize=124:x=(w-text_w)/2:y=(h-text_h)/2 " + command + " " + '"' + outputFolder + @"\" + uniqueId + "." + outputContainer + '"';

            if (debuggingMode)
            {
                var processn = new Process();
                processn.StartInfo           = startInfo;
                processn.EnableRaisingEvents = true;
                processn.StartInfo.FileName  = "CMD.EXE";
                processn.StartInfo.Arguments = "/K " + '"' + @FFMPEGPath + " " + startInfo.Arguments + '"';
                processn.Start();
                processn.WaitForExit();
            }
            else
            {
                var processn = Process.Start(startInfo);
                processn.EnableRaisingEvents = true;

                processn.WaitForExit();
            }

            // Outputs
            return((ctx) => {
            });
        }
Exemple #29
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            PropertyDescriptor dropboxSessionFactory = context.DataContext.GetProperties()[WithDropboxSession.DropboxSessionPropertyName];
            IDropboxSession    dropboxSession        = dropboxSessionFactory?.GetValue(context.DataContext) as IDropboxSession;

            if (dropboxSession == null)
            {
                throw new InvalidOperationException(Resources.DropboxSessionNotFoundException);
            }

            var fileContent = FileContent.Get(context);

            if (string.IsNullOrEmpty(fileContent))
            {
                await dropboxSession.CreateEmptyFileAsync(FilePath.Get(context), cancellationToken);
            }
            else
            {
                await dropboxSession.CreateFileWithContentAsync(FilePath.Get(context), fileContent, cancellationToken);
            }

            return((asyncCodeActivityContext) => { });
        }
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var timeout    = TimeoutMS.Get(context);
            var inputImage = InputImage.Get(context);
            var positionX  = PositionX.Get(context);
            var positionY  = PositionY.Get(context);
            var width      = Width.Get(context);
            var height     = Height.Get(context);
            var blur       = Blur.Get(context);
            var blurAmount = BlurAmount.Get(context);

            // Set a timeout on the execution
            var task = ExecuteWithTimeout(context, cancellationToken);

            if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) != task)
            {
                throw new TimeoutException(Resources.Timeout_Error);
            }

            Image returnImage;

            // Check if activity should blur or hide part of the image

            if (blur)
            {
                // Convert image to bytestream
                ImageConverter _imageConverter = new ImageConverter();
                byte[]         imageByteStream = (byte[])_imageConverter.ConvertTo(inputImage, typeof(byte[]));

                // Create image from bytestream for MagickImage use
                var magickimage = new MagickImage(imageByteStream);

                // Blur part of image
                magickimage.RegionMask(new MagickGeometry(positionX, positionY, width, height));
                magickimage.GaussianBlur(blurAmount, 25);
                magickimage.RemoveRegionMask();

                // Convert MagickInmage to Bytestream
                var          imageBytesOut = magickimage.ToByteArray();
                MemoryStream ms            = new MemoryStream(imageBytesOut);

                // Create return image from bytestream
                returnImage = Image.FromStream(ms);
            }
            else
            {
                // Create graphics context with returnImage
                returnImage = inputImage;

                using (Graphics g = Graphics.FromImage(returnImage))
                {
                    // Define brush and rectangle
                    SolidBrush blackBrush = new SolidBrush(Color.Black);
                    Rectangle  rect       = new Rectangle(positionX, positionY, width, height);

                    // Fill rectangle
                    g.FillRectangle(blackBrush, rect);

                    // Cleanup
                    g.Dispose();
                }
            }

            // Outputs
            return((ctx) => {
                OutputImage.Set(ctx, returnImage);
            });
        }
Exemple #31
0
 protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     return(this.methodExecutor.BeginExecuteMethod(context, callback, state));
 }
 private async Task ExecuteWithTimeout(AsyncCodeActivityContext context, CancellationToken cancellationToken = default)
 {
     ///////////////////////////
     // Add execution logic HERE
     ///////////////////////////
 }
Exemple #33
0
 protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
 {
 }
Exemple #34
0
 protected override void Cancel(AsyncCodeActivityContext context)
 {
     ((WitGetWorkItemsForArtifactsAsyncState)context.UserState).Canceled = true;
 }
Exemple #35
0
 protected override void EndMakeMethodCall(AsyncCodeActivityContext context, IAsyncResult result)
 {
     CompletedAsyncResult.End(result);
 }
Exemple #36
0
 protected override IList <int> EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
 {
     return(((WitGetWorkItemsForArtifactsAsyncState)context.UserState).Action.EndInvoke(result));
 }
Exemple #37
0
 protected override void EndMakeMethodCall(AsyncCodeActivityContext context, IAsyncResult result)
 {
     InvokeMethodInstanceData instance = (InvokeMethodInstanceData)context.UserState;
     instance.ReturnValue = InvokeAndUnwrapExceptions(this.endFunc, instance.TargetObject, new object[] { result });
     this.SetOutArgumentAndReturnValue(context, instance.ReturnValue, instance.ActualParameters);
 }
Exemple #38
0
        protected async override Task <FormResult> ExecuteAsync(AsyncCodeActivityContext context)
        {
            var        xmlString  = Form.Get(context);
            FormResult result     = null;
            string     json       = "";
            var        enableSkin = EnableSkin.Get(context);
            // var enableSkin = false;

            var           definition = FormBuilder.Default.GetDefinition(xmlString, freeze: false);
            List <string> fields     = GenericTools.MainWindow.Dispatcher.Invoke <List <string> >(() =>
            {
                List <string> _fields = new List <string>();
                foreach (DataFormField f in definition.GetElements().Where(x => x is DataFormField))
                {
                    _fields.Add(f.Key);
                }
                return(_fields);
            });
            var param = new Dictionary <string, object>();

            var vars = context.DataContext.GetProperties();

            if (Arguments == null || Arguments.Count == 0)
            {
                foreach (dynamic v in vars)
                {
                    var value = v.GetValue(context.DataContext);
                    if (value != null)
                    {
                        //_payload.Add(v.DisplayName, value);
                        try
                        {
                            try
                            {
                                //if(fields.Contains(v.DisplayName))
                                if (value.GetType() == typeof(System.Data.DataTable))
                                {
                                    continue;
                                }
                                if (value.GetType() == typeof(System.Data.DataView))
                                {
                                    continue;
                                }
                                if (value.GetType() == typeof(System.Data.DataRowView))
                                {
                                    continue;
                                }
                                param[v.DisplayName] = value;
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        param[v.DisplayName] = value;
                    }
                }
            }
            else
            {
                Dictionary <string, object> arguments = (from argument in Arguments
                                                         where argument.Value.Direction != ArgumentDirection.Out
                                                         select argument).ToDictionary((KeyValuePair <string, Argument> argument) => argument.Key, (KeyValuePair <string, Argument> argument) => argument.Value.Get(context));
                foreach (var a in arguments)
                {
                    var value = a.Value;
                    if (value != null)
                    {
                        if (value.GetType() == typeof(System.Data.DataView))
                        {
                            continue;
                        }
                        if (value.GetType() == typeof(System.Data.DataRowView))
                        {
                            continue;
                        }

                        if (value.GetType() == typeof(System.Data.DataTable))
                        {
                            if (value != null)
                            {
                                param[a.Key] = ((System.Data.DataTable)value).ToJArray();
                            }
                        }
                        else
                        {
                            param[a.Key] = a.Value;
                        }
                    }
                    else
                    {
                        param[a.Key] = null;
                    }
                }
            }


            Exception LastError = null;
            var       res       = GenericTools.MainWindow.Dispatcher.Invoke <FormResult>(() =>
            {
                var f      = new Form(xmlString, enableSkin);
                f.defaults = param;
                f.Topmost  = true;
                f.Owner    = GenericTools.MainWindow;
                if (f.ShowDialog() == false)
                {
                    if (f.LastError != null)
                    {
                        LastError = f.LastError;
                    }
                }
                var _res = new FormResult();
                if (f.actionContext != null && f.actionContext.Action != null)
                {
                    _res.Action = f.actionContext.Action.ToString();
                }
                _res.Model = f.CurrentModel;
                return(_res);
            });

            if (LastError != null)
            {
                throw LastError;
            }
            json   = JsonConvert.SerializeObject(res, Formatting.Indented);
            result = JsonConvert.DeserializeObject <FormResult>(json);
            if (result.Model != null)
            {
                if (Arguments == null || Arguments.Count == 0)
                {
                    foreach (var prop in result.Model)
                    {
                        var myVar = context.DataContext.GetProperties().Find(prop.Key, true);
                        if (myVar != null)
                        {
                            try
                            {
                                if (myVar.PropertyType == typeof(int))
                                {
                                    if (prop.Value != null)
                                    {
                                        myVar.SetValue(context.DataContext, int.Parse(prop.Value.ToString()));
                                    }
                                }
                                else
                                {
                                    if (prop.Value != null)
                                    {
                                        myVar.SetValue(context.DataContext, prop.Value);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex.ToString());
                            }
                        }
                        else
                        {
                            Log.Debug("Recived property " + prop.Key + " but no variable exists to save the value in " + prop.Value);
                        }
                    }
                }
                else
                {
                    Dictionary <string, object> arguments = (from argument in Arguments
                                                             where argument.Value.Direction != ArgumentDirection.In
                                                             select argument).ToDictionary((KeyValuePair <string, Argument> argument) => argument.Key, (KeyValuePair <string, Argument> argument) => argument.Value.Get(context));
                    foreach (var a in arguments)
                    {
                        var prop = result.Model[a.Key];
                        if (prop != null)
                        {
                            var myVar = context.DataContext.GetProperties().Find(a.Key, true);
                            if (Arguments[a.Key].ArgumentType == typeof(System.Data.DataTable))
                            {
                                try
                                {
                                    var json2 = result.Model[a.Key].ToString();
                                    if (!string.IsNullOrEmpty(json2))
                                    {
                                        var jarray = JArray.Parse(json2);
                                        Arguments[a.Key].Set(context, jarray.ToDataTable());
                                    }
                                    else
                                    {
                                        Arguments[a.Key].Set(context, null);
                                    }
                                }
                                catch (Exception)
                                {
                                    throw;
                                }
                            }
                            else
                            {
                                if (result.Model[a.Key] is JToken t)
                                {
                                    System.Reflection.MethodInfo method  = typeof(JToken).GetMethod(nameof(JToken.Value)); // typeof(JToken).GetMethod(nameof(JToken.Value));
                                    System.Reflection.MethodInfo generic = method.MakeGenericMethod(Arguments[a.Key].ArgumentType);
                                    var value = generic.Invoke(t, new object[] { });
                                    Arguments[a.Key].Set(context, value);
                                }
                                else if (result.Model[a.Key] is JArray _a)
                                {
                                }
                                else
                                {
                                    Arguments[a.Key].Set(context, result.Model[a.Key]);
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                if (Arguments[a.Key].ArgumentType.IsValueType)
                                {
                                    Arguments[a.Key].Set(context, Activator.CreateInstance(Arguments[a.Key].ArgumentType));
                                }
                                else
                                {
                                    Arguments[a.Key].Set(context, null);
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Error setting " + a.Key + ": " + ex.Message);
                            }
                        }
                    }
                }
            }
            await Task.Delay(1);

            return(result);
        }
Exemple #39
0
 protected override void EndMakeMethodCall(AsyncCodeActivityContext context, IAsyncResult result)
 {
     InvokeMethodInstanceData instance = ExecuteAsyncResult.End(result);
     if (instance.ExceptionWasThrown)
     {
         throw FxTrace.Exception.AsError(instance.Exception);
     }
     else
     {
         this.SetOutArgumentAndReturnValue(context, instance.ReturnValue, instance.ActualParameters);
     }
 }
Exemple #40
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope
            var objectContainer = context.GetFromContext <IObjectContainer>(TwilioApiScope.ParentContainerPropertyTag);

            // Inputs
            var friendlyname = FriendlyName.Get(context);

            var account =
                await AccountWrappers.CreateAccountAsync(objectContainer.Get <ITwilioRestClient>(), friendlyname);

            // Outputs
            return((ctx) => {
                Account.Set(ctx, account);
            });
        }
 protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
 {
     this.methodExecutor.EndExecuteMethod(context, result);
 }
        public IAsyncResult BeginExecuteMethod(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            object targetInstance = null;

            if (!this.MethodIsStatic)
            {
                targetInstance = this.targetObject.Get(context);
                if (targetInstance == null)
                {
                    throw FxTrace.Exception.ArgumentNull("TargetObject");
                }
            }

            return BeginMakeMethodCall(context, targetInstance, callback, state); // defer to concrete instance for [....]/async variations
        }