示例#1
0
        public static void ImportDataToTempTable(string databaseName, string sqlServerInstance, string folder, TableType type, string connString)
        {
            ExecuteSqlQuery(connString, "Truncate Table " + tempTable);

            var filePath = Path.Combine(folder, FileName.Get(type) + ".txt.processed");

            var command = $"bcp {tempTable} in {filePath} -c -t, -S {sqlServerInstance} -d {databaseName} -T";

            ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);

            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute        = false;
            procStartInfo.CreateNoWindow         = true;

            // wrap IDisposable into using (in order to release Process)
            using (Process process = new Process())
            {
                process.StartInfo = procStartInfo;
                process.Start();

                // Add this: wait until process does its work
                process.WaitForExit();

                // and only then read the result
                string result = process.StandardOutput.ReadToEnd();
                Console.WriteLine(result);
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            string filePath     = FileName.Get(context);
            string fileContent  = Text.Get(context);
            string EncodingName = Encoding.Get(context);

            if (string.IsNullOrWhiteSpace(EncodingName))
            {
                EncodingName = "UTF-8";
            }
            try
            {
                //  byte[] contentByte = System.Text.Encoding.UTF8.GetBytes(fileContent);
                using (FileStream fsWrite = new FileStream(filePath, FileMode.OpenOrCreate))
                {
                    StreamWriter sw = new StreamWriter(fsWrite, System.Text.Encoding.GetEncoding(EncodingName));
                    sw.Write(fileContent);
                    sw.Flush();
                    sw.Close();
                    fsWrite.Close();
                };
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
示例#3
0
        public void CreateFile(List <Erp.Internal.EI.Payment_Def.TmpElec> TmpElecRows, int EFTHeadUID, string OutputFile)
        {
            Erp.Internal.EI.Payment_Def.TmpElec tmpElec = (from ttTmpElec_Row in TmpElecRows select ttTmpElec_Row).FirstOrDefault();
            bool storeBankBatchID = PayMethodGrouping(tmpElec != null ? tmpElec.SEPMUID : -1);

            this.buildInfo(TmpElecRows);
            OutputFile = FileName.Get(OutputFile, Ice.Lib.FileName.ServerFileType.Custom, false);
            //output stream outStream to value (OutputFile) unbuffered

            #region >>===== ABL Source ================================>>
            //
            //for each OutFileLine:
            //
            //
            #endregion == ABL Source =================================<<

            using (var fileWriter = new Ice.Lib.writeFileLib(OutputFile, true))
            {
                foreach (var _OutFileLine in (from OutFileLine_Row in SFCommon.ttOutFileLineRows
                                              select OutFileLine_Row))
                {
                    fileWriter.FileWriteLine(SFCommon.SpecialCaps(_OutFileLine.Line_out.Substring(0, Math.Min(lineLen, _OutFileLine.Line_out.Length - 1))));
                    if (storeBankBatchID)
                    {
                        SavePaymentBankBatchID(_OutFileLine.HeadNum, GetPaymentBankBatchID(string.Empty), tmpElec.ProcessDate);
                    }
                }
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            string path       = FileName.Get(context);
            string API_KEY    = APIKey.Get(context);
            string SECRET_KEY = SecretKey.Get(context);

            img = image.Get(context);
            try
            {
                if (path != null)
                {
                    by = SaveImage(path);
                }
                else
                {
                    by = ConvertImageToByte(img);
                }
                var client = new Ocr(API_KEY, SECRET_KEY);
                //修改超时时间
                client.Timeout = 60000;
                //参数设置
                var options = new Dictionary <string, object>
                {
                    { "detect_direction", detect_direction.ToString().ToLower() },
                    { "probability", probability.ToString().ToLower() }
                };
                //带参数调用通用文字识别(高精度版)
                string result = client.AccurateBasic(by, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, Localize.LocalizedResources.GetString("msgErrorOccurred"), e.Message);
            }
        }
示例#5
0
        protected override void Execute(CodeActivityContext context)
        {
            string path       = FileName.Get(context);
            string API_KEY    = APIKey.Get(context);
            string SECRET_KEY = SecretKey.Get(context);

            img = image.Get(context);
            try
            {
                if (path != null)
                {
                    by = SaveImage(path);
                }
                else
                {
                    by = ConvertImageToByte(img);
                }
                var client = new Ocr(API_KEY, SECRET_KEY);
                //修改超时时间
                client.Timeout = 60000;
                //参数设置
                var options = new Dictionary <string, object>
                {
                    { "detect_direction", detect_direction.ToString().ToLower() },
                    { "detect_language", detect_language.ToString().ToLower() }
                };
                //带参数调用网络图片文字识别
                string result = client.WebImage(by, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
示例#6
0
        /// <inheritdoc />
        protected override void Execute(Context context)
        {
            var query    = @"<fetch top='1' no-lock='true' >
  <entity name='annotation' >
    <attribute name='mimetype' />
    <attribute name='documentbody' />
    <filter>
      <condition attribute='filename' operator='eq' value='" + FileName.Get(context) + @"' />
      <condition attribute='objectid' operator='eq' value='" + EntityIdString.Get(context) + @"' />
    </filter>
    <order attribute='createdon' descending='true' />
  </entity>
</fetch>";
            var service  = ExecureAsSystem.Get(context) ? context.SystemService : context.Service;
            var response = service.RetrieveMultiple(new FetchExpression(query));

            if (response.Entities.Count < 1)
            {
                return;
            }
            var annotation = response.Entities.First();

            FileMimeType.Set(context, annotation.GetAttributeValue <string>("mimetype"));
            FileBase64Content.Set(context, annotation.GetAttributeValue <string>("documentbody"));
        }
示例#7
0
        protected override void Execute(CodeActivityContext context)
        {
            var fName = FileName.Get(context);

            if (!System.IO.File.Exists(fName))
            {
                throw new FileNotFoundException();
            }

            if (IntervalMS.Get(context) <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            long     lastFileSize = 0;
            DateTime timeLimit    = TimeOutSeconds.Get(context) > 0 ? DateTime.Now.AddSeconds(TimeOutSeconds.Get(context)) : DateTime.MaxValue;

            do
            {
                lastFileSize = new FileInfo(fName).Length;
                System.Threading.Thread.Sleep(IntervalMS.Get(context));
                if (timeLimit.Ticks < DateTime.Now.Ticks)
                {
                    throw new TimeoutException();
                }
            } while (lastFileSize != new FileInfo(fName).Length);

            FinalFileSize.Set(context, new FileInfo(fName).Length);
        }
示例#8
0
        /// <summary>
        /// See http://taskscheduler.codeplex.com/ for help on using the TaskService wrapper library.
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                using (TaskService ts = new TaskService())
                {
                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = TaskDescription.Get(context);
                    var triggers = Triggers.Get(context);
                    if (triggers != null)
                    {
                        triggers.ToList().ForEach(t => td.Triggers.Add(t));
                    }
                    td.Actions.Add(new ExecAction(FileName.Get(context), Arguments.Get(context), WorkingDirectory.Get(context)));

                    string username = Username.Get(context);
                    string password = Password.Get(context);
                    if (string.IsNullOrEmpty(username))
                    {
                        username = WindowsIdentity.GetCurrent().Name;
                    }

                    ts.RootFolder.RegisterTaskDefinition(
                        TaskName.Get(context),
                        td,
                        TaskCreation.CreateOrUpdate,
                        username,
                        password);
                }
            }
            catch
            {
                throw;
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            string _arguments        = Arguments.Get(context);
            string _fileName         = FileName.Get(context);
            string _workingDirectory = WorkingDirectory.Get(context);

            try
            {
                Process p = new System.Diagnostics.Process();
                if (_arguments != null)
                {
                    p.StartInfo.Arguments = _arguments;
                }
                if (_workingDirectory != null)
                {
                    p.StartInfo.WorkingDirectory = _workingDirectory;
                }
                p.StartInfo.UseShellExecute = Default;
                p.StartInfo.Verb            = "Open";
                p.StartInfo.FileName        = _fileName;
                p.Start();
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
                if (!ContinueOnError.Get(context))
                {
                    throw new NotImplementedException(e.Message);
                }
            }
        }
示例#10
0
        private IFileTransfer CreateTransporter(ActivityContext context)
        {
            var transporter = CreateFileTransferInstance(context);

            return(SetCredentials(context, transporter)
                   .SetServerRootUrl(Location.Get(context))
                   .SetFileName(FileName.Get(context)));
        }
        protected override void Execute(CodeActivityContext context)
        {
            var scriptFilename = FileName.Get(context);

            FileName.Set(context, "cscript.exe");
            Arguments.Set(context, "//Nologo " + "\"" + scriptFilename + "\"" + " " + Arguments.Get(context));

            base.Execute(context);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService             tracer         = executionContext.GetExtension <ITracingService>();
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                EntityReference emailWithAttachments = EmailWithAttachments.Get(executionContext);
                string          fileName             = FileName.Get(executionContext);
                bool            appendNotice         = AppendNotice.Get(executionContext);

                EntityCollection attachments = GetAttachments(service, emailWithAttachments.Id);
                if (attachments.Entities.Count == 0)
                {
                    return;
                }

                StringBuilder notice = new StringBuilder();
                int           numberOfAttachmentsDeleted = 0;

                foreach (Entity activityMineAttachment in attachments.Entities)
                {
                    if (!String.Equals(activityMineAttachment.GetAttributeValue <string>("filename"), fileName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }

                    DeleteEmailAttachment(service, activityMineAttachment.Id);
                    numberOfAttachmentsDeleted++;

                    if (appendNotice)
                    {
                        notice.AppendLine("Deleted Attachment: " + activityMineAttachment.GetAttributeValue <string>("filename") + " " +
                                          DateTime.Now.ToShortDateString() + "\r\n");
                    }
                }

                if (appendNotice && notice.Length > 0)
                {
                    UpdateEmail(service, emailWithAttachments.Id, notice.ToString());
                }

                NumberOfAttachmentsDeleted.Set(executionContext, numberOfAttachmentsDeleted);
            }
            catch (Exception ex)
            {
                tracer.Trace("Exception: {0}", ex.ToString());
            }
        }
示例#13
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var fileName          = FileName.Get(context);
            var jsonConfiguration = JsonConfiguration.Get(context);
            var apiKey            = APIKey.Get(context);
            var extractorHelper   = new ExtractorHelper();
            var dtResult          = extractorHelper.DoExtraction(apiKey, fileName, jsonConfiguration);

            // Outputs
            return((ctx) => {
                Results.Set(ctx, dtResult);
            });
        }
        /// <inheritdoc />
        protected override void Execute(Context context)
        {
            var entityId = new Guid(EntityIdString.Get(context));

            context.Service.Create(new Entity(Metadata.Annotation.LogicalName)
            {
                ["objectid"]     = new EntityReference(EntityLogicalName.Get(context), entityId),
                ["subject"]      = Subject.Get(context),
                ["notetext"]     = Content.Get(context),
                ["filename"]     = FileName.Get(context),
                ["mimetype"]     = FileMimeType.Get(context),
                ["documentbody"] = FileBase64Content.Get(context)
            });
        }
示例#15
0
        protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (localContext == null)
            {
                throw new ArgumentNullException(nameof(localContext));
            }

            EntityReference emailWithAttachments = EmailWithAttachments.Get(context);
            string          fileName             = FileName.Get(context);
            bool            appendNotice         = AppendNotice.Get(context);

            EntityCollection attachments = GetAttachments(localContext.OrganizationService, emailWithAttachments.Id);

            if (attachments.Entities.Count == 0)
            {
                return;
            }

            StringBuilder notice = new StringBuilder();
            int           numberOfAttachmentsDeleted = 0;

            foreach (Entity activityMineAttachment in attachments.Entities)
            {
                if (!string.Equals(activityMineAttachment.GetAttributeValue <string>("filename"), fileName, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                DeleteEmailAttachment(localContext.OrganizationService, activityMineAttachment.Id);
                numberOfAttachmentsDeleted++;

                if (appendNotice)
                {
                    notice.AppendLine("Deleted Attachment: " + activityMineAttachment.GetAttributeValue <string>("filename") + " " +
                                      DateTime.Now.ToShortDateString() + "\r\n");
                }
            }

            if (appendNotice && notice.Length > 0)
            {
                UpdateEmail(localContext.OrganizationService, emailWithAttachments.Id, notice.ToString());
            }

            NumberOfAttachmentsDeleted.Set(context, numberOfAttachmentsDeleted);
        }
        protected override void Execute(CodeActivityContext context)
        {
            //======= Variables =======

            var strFileName     = FileName.Get(context);
            var xmlWorkflowData = new XDocument();


            //======= Read XAML File =======

            // To be implemented


            //======= Set Output =======

            WorkflowData.Set(context, xmlWorkflowData);
        }
        protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (localContext == null)
            {
                throw new ArgumentNullException(nameof(localContext));
            }

            EntityReference noteWithAttachment = NoteWithAttachment.Get(context);

            if (noteWithAttachment == null)
            {
                throw new ArgumentNullException("Note cannot be null");
            }

            string fileName     = FileName.Get(context);
            bool   appendNotice = AppendNotice.Get(context);

            Entity note = GetNote(localContext.OrganizationService, noteWithAttachment.Id);

            if (!CheckForAttachment(note))
            {
                return;
            }

            StringBuilder notice = new StringBuilder();
            int           numberOfAttachmentsDeleted = 0;

            if (String.Equals(note.GetAttributeValue <string>("filename"), fileName, StringComparison.CurrentCultureIgnoreCase))
            {
                numberOfAttachmentsDeleted++;

                if (appendNotice)
                {
                    notice.AppendLine("Deleted Attachment: " + note.GetAttributeValue <string>("filename") + " " +
                                      DateTime.Now.ToShortDateString());
                }

                UpdateNote(localContext.OrganizationService, note, notice.ToString());
            }

            NumberOfAttachmentsDeleted.Set(context, numberOfAttachmentsDeleted);
        }
示例#18
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var fileName    = FileName.Get(context);
            var Strencoding = Encoding.Get(context);
            var displayLog  = DisplayLog;

            ///////////////////////////
            // Add execution logic HERE
            String OutputString = Utils.ReadTextFileEncoding(fileName, Strencoding, displayLog);

            ///////////////////////////

            // Outputs
            return((ctx) => {
                Content.Set(ctx, OutputString);
            });
        }
示例#19
0
        protected override void Execute(CodeActivityContext context)
        {
            string fileName = FileName.Get(context);

            System.Drawing.Image _image = image.Get(context);
            if (fileName != null)
            {
                img = new Bitmap(fileName);
            }
            else
            {
                img = (Bitmap)_image;
            }
            var    ocr  = new TesseractEngine("tessdata", _languagetype.ToString(), (EngineMode)_engineMode);
            var    page = ocr.Process(img);
            string text = page.GetText();

            Result.Set(context, text);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService             tracer         = executionContext.GetExtension <ITracingService>();
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                EntityReference noteWithAttachment = NoteWithAttachment.Get(executionContext);
                string          fileName           = FileName.Get(executionContext);
                bool            appendNotice       = AppendNotice.Get(executionContext);

                Entity note = GetNote(service, noteWithAttachment.Id);
                if (!CheckForAttachment(note))
                {
                    return;
                }

                StringBuilder notice = new StringBuilder();
                int           numberOfAttachmentsDeleted = 0;

                if (String.Equals(note.GetAttributeValue <string>("filename"), fileName, StringComparison.CurrentCultureIgnoreCase))
                {
                    numberOfAttachmentsDeleted++;

                    if (appendNotice)
                    {
                        notice.AppendLine("Deleted Attachment: " + note.GetAttributeValue <string>("filename") + " " +
                                          DateTime.Now.ToShortDateString());
                    }

                    UpdateNote(service, note, notice.ToString());
                }

                NumberOfAttachmentsDeleted.Set(executionContext, numberOfAttachmentsDeleted);
            }
            catch (Exception ex)
            {
                tracer.Trace("Exception: {0}", ex.ToString());
            }
        }
示例#21
0
        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                var userName = UserName.Get(context).Trim();
                var password = new NetworkCredential(string.Empty, Password.Get(context)).Password;
                var local    = LocalFolderPath.Get(context).Trim();
                var remote   = DestinationFolderPath.Get(context).Trim();
                remote = remote.EndsWith("\\") ? remote.Remove(remote.Length - 1) : remote;
                var  fileName  = FileName.Get(context).Trim();
                bool overWrite = OverwriteFile.Get(context);

                local = Path.Combine(local, fileName);
                if (!File.Exists(local))
                {
                    throw new Exception("File absent at path: " + local);
                }

                NetworkCredential writeCredentials = new NetworkCredential(userName, password);
                using (new NetworkConnection(remote, writeCredentials))
                {
                    File.Copy(local, Path.Combine(remote, fileName), overWrite);
                }

                var deleteLocal = DeleteLocalFile.Get(context);
                if (deleteLocal)
                {
                    if (File.Exists(local))
                    {
                        File.Delete(local);
                    }
                }
            }
            catch
            {
                bool ignoreError = ContinueOnError.Get(context);
                if (!ignoreError)
                {
                    throw;
                }
            }
        }
 protected override void Execute(CodeActivityContext context)
 {
     try
     {
         string fileName            = FileName.Get(context);
         System.Drawing.Image image = Image.Get(context);
         image.Save(fileName);
     }
     catch (Exception e)
     {
         SharedObject.Instance.Output(SharedObject.enOutputType.Error, "保存图片失败", e.Message);
         if (ContinueOnError.Get(context))
         {
         }
         else
         {
             throw e;
         }
     }
 }
示例#23
0
        protected override void Execute(CodeActivityContext context)
        {
            ValidateInputArguments(context);

            var processInvokeWrapper = new RunProcessWrapper(FileName.Get(context),
                                                             Arguments.Get(context),
                                                             WorkingDirectory.Get(context),
                                                             CaptureOutput.Get(context),
                                                             WaitForExit.Get(context),
                                                             WaitForExitTimeout.Get(context),
                                                             KillAtTimeout.Get(context));

            processInvokeWrapper.StartProcess();

            ProcessId.Set(context, processInvokeWrapper.ProcessId);
            Finished.Set(context, processInvokeWrapper.Finished);
            Output.Set(context, processInvokeWrapper.StandardOutput);
            Error.Set(context, processInvokeWrapper.StandardError);
            ExitCode.Set(context, processInvokeWrapper.ExitCode);
        }
        /// <inheritdoc />
        protected override void Execute(Context context)
        {
            var entityId = new Guid(EntityIdString.Get(context));
            var entity   = new Entity(Metadata.Annotation.LogicalName)
            {
                ["objectid"] = new EntityReference(EntityLogicalName.Get(context), entityId),
                ["subject"]  = Subject.Get(context),
                ["notetext"] = Content.Get(context)
            };
            var fileName = FileName.Get(context);

            if (!string.IsNullOrWhiteSpace(fileName))
            {
                entity["filename"]     = fileName;
                entity["mimetype"]     = FileMimeType.Get(context);
                entity["documentbody"] = FileBase64Content.Get(context);
            }
            var service = ExecureAsSystem.Get(context) ? context.SystemService : context.Service;

            service.Create(entity);
        }
        protected override void Execute(CodeActivityContext context)
        {
            string Imagefilename = FileName.Get(context);

            try
            {
                Bitmap       bmp = new Bitmap(Imagefilename);
                MemoryStream ms  = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                string strbaser64 = Convert.ToBase64String(arr);
                Content.Set(context, strbaser64);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region "Load CRM Service from context"

            Common objCommon = new Common(executionContext);
            objCommon.tracingService.Trace("Load CRM Service from context --- OK");

            #endregion

            #region "Read Parameters"

            // Get parameters
            string          mainRecordURL = MainRecordURL.Get(executionContext);
            string          fileName      = FileName.Get(executionContext);
            EntityReference email         = Email.Get(executionContext);
            bool            retrieveActivityMimeAttachment = RetrieveActivityMimeAttachment.Get(executionContext);
            bool            mostRecent = MostRecent.Get(executionContext);
            int?            topRecords = TopRecords.Get(executionContext);


            // Extract values from URL
            string[] urlParts             = mainRecordURL.Split("?".ToArray());
            string[] urlParams            = urlParts[1].Split("&".ToCharArray());
            string   ParentObjectTypeCode = urlParams[0].Replace("etc=", "");
            string   ParentId             = urlParams[1].Replace("id=", "");
            objCommon.tracingService.Trace("ParentObjectTypeCode=" + ParentObjectTypeCode + "--ParentId=" + ParentId);

            // Treat file name
            if (fileName == "*")
            {
                fileName = "";
            }
            fileName = fileName.Replace("*", "%");

            #endregion

            msdyncrmWorkflowTools_Class commonClass = new msdyncrmWorkflowTools_Class(objCommon.service, objCommon.tracingService);
            commonClass.EntityAttachmentToEmail(fileName, ParentId, email, retrieveActivityMimeAttachment, mostRecent, topRecords);
        }
        protected override void Execute(CodeActivityContext context)
        {
            string filePath     = FileName.Get(context);
            string EncodingName = Encoding.Get(context);

            if (string.IsNullOrWhiteSpace(EncodingName))
            {
                EncodingName = "UTF-8";
            }
            try
            {
                using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.GetEncoding(EncodingName)))
                {
                    string fileContent = sr.ReadToEnd();
                    Content.Set(context, fileContent);
                }
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            string path       = FileName.Get(context);
            string API_KEY    = APIKey.Get(context);
            string SECRET_KEY = SecretKey.Get(context);

            img = image.Get(context);
            try
            {
                if (path != null)
                {
                    by = SaveImage(path);
                }
                else
                {
                    by = ConvertImageToByte(img);
                }
                var client = new Ocr(API_KEY, SECRET_KEY);
                //修改超时时间
                client.Timeout = 60000;
                //参数设置
                var options = new Dictionary <string, object>
                {
                    { "detect_direction", detect_direction.ToString().ToLower() },
                    { "probability", probability.ToString().ToLower() }
                };
                //带参数调用通用文字识别(高精度版)
                var json = client.AccurateBasic(by, options).ToString();
                Console.WriteLine(json);
                var result = JsonConvert.DeserializeObject <BaiDuOCRHighPrecisionResult>(json);
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
示例#29
0
        // Module defining this command


        // Additional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (UICulture.Expression != null)
            {
                targetCommand.AddParameter("UICulture", UICulture.Get(context));
            }

            if (BaseDirectory.Expression != null)
            {
                targetCommand.AddParameter("BaseDirectory", BaseDirectory.Get(context));
            }
            //If BaseDirectory is not specified, try to use the workflow base directory.
            else
            {
                throw new ArgumentException(GeneratedActivitiesResources.ImportLocalizedDataWithEmptyEmptyorNullBaseDirectory);
            }

            if (FileName.Expression != null)
            {
                targetCommand.AddParameter("FileName", FileName.Get(context));
            }

            if (SupportedCommand.Expression != null)
            {
                targetCommand.AddParameter("SupportedCommand", SupportedCommand.Get(context));
            }

            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
示例#30
0
        protected virtual void ValidateFilename(CodeActivityContext context, bool lookForFilesInPATH)
        {
            var workingDirectory = WorkingDirectory.Get(context);

            if (string.IsNullOrEmpty(workingDirectory))
            {
                workingDirectory = Directory.GetCurrentDirectory();
            }

            var filename = FileName.Get(context);

            if (Path.IsPathRooted(filename) && !File.Exists(filename))
            {
                throw new ArgumentException("Filename with absolute path could not be found.");
            }
            else
            {
                if (Path.GetFileName(filename) == filename)
                {
                    if (lookForFilesInPATH && !Environment.GetEnvironmentVariable("PATH").Split(';').
                        Any(dir => (string.IsNullOrEmpty(Path.GetExtension(filename)) && // The given filename does not have an extension but matches one file from the directories in PATH
                                    Directory.GetFiles(dir).Any(file => Path.GetFileNameWithoutExtension(file) == filename)) ||
                            File.Exists(Path.Combine(dir, filename))))                   // Filename is present in one of the directories from PATH
                    {
                        throw new ArgumentException("Filename could not be found in the working directory or in any directory from the PATH Environment Variable.");
                    }
                }
                else
                {
                    if (!File.Exists(Path.Combine(workingDirectory, filename)))
                    {
                        throw new ArgumentException("Filename with relative path could not be found in the current working directory.");
                    }
                }
            }
        }