Example #1
0
        public static void Main(string[] args)
        {
            Camunda = new CamundaEngineClient();
            Camunda.Startup();

            BuildWebHost(args).Run();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Starting !");

            byte[] bytes = System.IO.File.ReadAllBytes("calculation.bpmn");
            IDictionary <string, byte[]> filesToUpload = new Dictionary <string, byte[]>();

            filesToUpload.Add("calculator.bpmn", bytes);

            ICamundaEngineClient camundaEngineClient = new CamundaEngineClient();

            camundaEngineClient.DeploymentService().Deploy("testDeployment", filesToUpload);

            var subscriptionWorker    = new ChargeCardSubscriptionWorker();
            var topicSubscriptionInfo = new TopicSubscriptionInfo()
            {
                TopicName = "calculate",
                PollingIntervalInMilliseconds = 2000
            };

            using var topicSubscription = camundaEngineClient.SubscribeTopic(topicSubscriptionInfo).Worker(subscriptionWorker);
            topicSubscription.Start();

            Console.WriteLine("Press any key to stop the workers...");
            Console.ReadKey();
        }
Example #3
0
        static void Main(string[] args)
        {
            CamundaEngineClient camunda = new CamundaEngineClient(new System.Uri("http://localhost:8080/engine-rest/engine/default/"), null, null);

            camunda.Startup();
            //string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("calculate", new Dictionary<string, object>()
            //{
            //    {"x", 25 },
            //    {"y", 20 }
            //},new Dictionary<string, Action<IDictionary<string, object>>> {
            //    {"calculate",
            //        (x) => {
            //            Console.WriteLine("Tan dep trai");
            //        }
            //    }
            //});

            //System.Threading.Thread.Sleep(20000);

            var processInstanceId1 = camunda.BpmnWorkflowService.StartProcessInstanceAsync("calculate", new Dictionary <string, object>()
            {
                { "x", 25 },
                { "y", 30 }
            }, "calculate").Result;

            var processInstanceId2 = camunda.BpmnWorkflowService.StartProcessInstanceAsync("calculate", new Dictionary <string, object>()
            {
                { "x", 35 },
                { "y", 30 }
            }, "calculate").Result;
            var a = 1;

            Console.ReadLine();
            camunda.Shutdown();
        }
Example #4
0
        private static void Main(string[] args)
        {
            var auth = new HubConnectionBuilder()
                       .WithUrl("http://localhost:5051/authenticationhub")
                       .Build();

            auth.StartAsync();
            var s = auth.InvokeAsync <User>("Authenticate", "serviceaccount", "test").Result;

            connection = new HubConnectionBuilder()
                         .WithUrl("http://localhost:5051/eventhub", options => {
                options.AccessTokenProvider = () => Task.FromResult(s.Token);
            })
                         .Build();

            connection.StartAsync().GetAwaiter();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(logo + "\n\n" + "Starting redis client.\n\n");

            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");

            Db = redis.GetDatabase();

            Console.WriteLine("Deploying models and start External Task Workers.\n\nPRESS Ctrl-C TO STOP WORKERS.\n\n");

            CamundaEngineClient camunda = new CamundaEngineClient();

            camunda.Startup(); // Deploys all models to Camunda and Start all found ExternalTask-Workers
            Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
            _closing.WaitOne();
            camunda.Shutdown(); // Stop Task Workers
            connection.DisposeAsync();
        }
        private static void Main(string[] args)
        {
            Console.WriteLine(logo + "\n\n" + "Deploying models and start workers.\n\nPRESS ANY KEY TO STOP WORKERS.\n\n");

            camunda = new CamundaEngineClient(
                new System.Uri("http://localhost:8080/engine-rest/engine/default/"), "demo", "demo");

            // Alternative way of doing it: Search assembly and automatically deploy all models to Camunda and start all found workers
            // camunda.Startup();

            DeployModel();
            RegisterWorker();

            // start some instances:
            for (int i = 0; i < 1; i++)
            {
                string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("FlowingTripBookingSaga", new Dictionary <string, object>()
                {
                    { "someBookingData", "..." }
                });
                Console.WriteLine("Started trip booking saga " + processInstanceId);
            }

            Console.ReadLine(); // wait for ANY KEY
            camunda.Shutdown(); // Stop Task Workers
        }
Example #6
0
        public void TestHappyPath()
        {
            // Engine client should point to a dedicated Camunda instance for test, preferrably locally available
            var camunda = new CamundaEngineClient(new System.Uri("http://localhost:8080/engine-rest/engine/default/"), null, null);

            // Deploy the process under test
            string deploymentId = camunda.RepositoryService.Deploy("testcase", new List <object> {
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "GravaNota2Process.entrega-de-trabalho.bpmn")
            });

            // string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("calculate", new Dictionary<string, object>()
            // {
            //     {"x", 5 },
            //     {"y", 10 }
            // });

            //var externalTasks = camunda.ExternalTaskService.FetchAndLockTasks("testcase", 100, "gravanota", 1000, new List<string>() { "x", "y" });
            //Assert.AreEqual(1, externalTasks.Count);
            //Assert.AreEqual("ServiceTaskCalculate", externalTasks.First().ActivityId);

            //   camunda.ExternalTaskService.Complete("testcase", externalTasks.First().Id, new Dictionary<string, object>() { { "result", 15 } });

            //   var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary<string, string>() {
            //       { "processInstanceId", processInstanceId }
            //   });
            //   Assert.AreEqual(1, tasks.Count);
            //   Assert.AreEqual("UserTaskReviewResult", tasks.First().TaskDefinitionKey);

            //   camunda.HumanTaskService.Complete(tasks.First().Id, new Dictionary<string, object>());

            // not the process instance has ended, TODO: Check state with History

            // cleanup after test case
            camunda.RepositoryService.DeleteDeployment(deploymentId);
        }
Example #7
0
        static void Main(string[] args)
        {
            CamundaEngineClient camunda = new CamundaEngineClient();

            camunda.Startup();  // Deploys all models and Start all found ExternalTask-Workers​
            Console.ReadLine(); // wait for ANY KEY​
            camunda.Shutdown();
        }
Example #8
0
        public void TestInsuranceApplicationManuallyApproved()
        {
            // Engine client should point to a dedicated Camunda instance for test, preferrably locally available

            var camunda = new CamundaEngineClient(new System.Uri("http://localhost:8080/engine-rest/engine/default/"), null, null);

            // Deploy the models under test
            string deploymentId = camunda.RepositoryService.Deploy("testcaseMarcio", new List <object> {
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "InsuranceApplicationCamundaTasklist.CamundaModels.DE.InsuranceApplication.bpmn"),
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "InsuranceApplicationCamundaTasklist.CamundaModels.DE.RiskAssessment.dmn"),
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "InsuranceApplicationCamundaTasklist.CamundaModels.EN.trimFeatures.ps1")
            });

            try
            {
                // Start Instance
                string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("insuranceApplication.NET.DE", new Dictionary <string, object>()
                {
                    { "age", 36 },
                    { "carManufacturer", "Porsche" },
                    { "carType", "911" }
                });

                // Check User Task
                var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>()
                {
                    { "processInstanceId", processInstanceId }
                });
                Assert.AreEqual(1, tasks.Count);
                Assert.AreEqual("userTaskAntragEntscheiden", tasks.First().TaskDefinitionKey);

                // Complete User Task, approve application
                camunda.HumanTaskService.Complete(tasks.First().Id, new Dictionary <string, object>()
                {
                    { "approved", true }
                });

                // Check that External Task for policy created is there
                var externalTasks = camunda.ExternalTaskService.FetchAndLockTasks("testcase", 100, "issuePolicy", 1000, new List <string>());
                Assert.AreEqual(1, externalTasks.Count);
                Assert.AreEqual("ServiceTaskPoliceAusstellen", externalTasks.First().ActivityId);
                camunda.ExternalTaskService.Complete("testcase", externalTasks.First().Id, new Dictionary <string, object>());

                // Check that External Task for sending the policy is there
                externalTasks = camunda.ExternalTaskService.FetchAndLockTasks("testcase", 100, "sendEmail", 1000, new List <string>());
                Assert.AreEqual(1, externalTasks.Count);
                Assert.AreEqual("ServiceTaskSendPolicy", externalTasks.First().ActivityId);
                camunda.ExternalTaskService.Complete("testcase", externalTasks.First().Id, new Dictionary <string, object>());

                // now the process instance has ended, TODO: Check state with History
            }
            finally
            {
                // cleanup after test case
                //  camunda.RepositoryService.DeleteDeployment(deploymentId);
            }
        }
Example #9
0
        private static void writeTasksToConsole(CamundaEngineClient camunda)
        {
            var tasks = camunda.HumanTaskService.LoadTasks();

            foreach (var task in tasks)
            {
                Console.WriteLine(task.Name);
            }
        }
        public TasklistWindow()
        {
            InitializeComponent();
            DataContext  = this;
            Closing     += OnWindowClosing;
            this.Camunda = new CamundaEngineClient();

            Startup();
        }
        private static void Main(string[] args)
        {
            Console.WriteLine(logo + "\n\n" + "Deploying Models + Forms and start External Task Workers.\n\nPRESS ANY KEY TO STOP WORKERS.\n\n");

            CamundaEngineClient camunda = new CamundaEngineClient();

            camunda.Startup();  // Deploys all models to Camunda and Start all found ExternalTask-Workers
            Console.ReadLine(); // wait for ANY KEY
            camunda.Shutdown(); // Stop Task Workers
        }
Example #12
0
        private static void Main(string[] args)
        {
            Console.WriteLine(logo + "\n\n" + "Deploying models and start External Task Workers.\n\nPRESS Ctrl-C TO STOP WORKERS.\n\n");

            CamundaEngineClient camunda = new CamundaEngineClient();

            camunda.Startup(); // Deploys all models to Camunda and Start all found ExternalTask-Workers
            Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
            _closing.WaitOne();
            camunda.Shutdown(); // Stop Task Workers
        }
        public static void Main(string[] args)
        {
            CamundaEngineClient Camunda = new CamundaEngineClient(
                new Uri("http://localhost:8080/engine-rest/engine/default/"),
                "demo",
                "demo");

            Camunda.Startup();  // Deploys all models to Camunda and Start all found ExternalTask-Workers
            Console.ReadLine(); // wait for ANY KEY
            Camunda.Shutdown(); // Stop Task Workers
        }
Example #14
0
        public object createNewFile([FromBody] Dictionary <string, object> file)
        {
            var     o      = (Newtonsoft.Json.Linq.JObject)file["file"];
            dynamic od     = (dynamic)o;
            Guid    fileId = Guid.NewGuid();

            // Save it to Postgresql
            using (var connection = new NpgsqlConnection(Startup.databaseConnection))
            {
                const string stmt = @"INSERT INTO dbo.incidents(id, tenant_id, patient_id, unit_id, type, severity, state, details, created_by, created_on, last_modified_by, last_modified_on)
	                VALUES (@id, @tenant_id, @patient_id, @unit_id, @type, @severity, @state, @details, @cb, @co, @mb, @mo);"    ;
                connection.Open();
                try
                {
                    using (var cmd = new NpgsqlCommand(stmt, connection))
                    {
                        cmd.Parameters.AddWithValue("@id", fileId);
                        cmd.Parameters.AddWithValue("@tenant_id", Guid.Parse((string)od.tenantId.Value));
                        cmd.Parameters.AddWithValue("@patient_id", DBNull.Value);
                        cmd.Parameters.AddWithValue("@unit_id", Guid.Parse((string)od.unitId.Value));
                        cmd.Parameters.AddWithValue("@type", (string)od.type.Value);
                        cmd.Parameters.AddWithValue("@severity", (string)od.severity.Value);
                        cmd.Parameters.AddWithValue("@state", "new");
                        cmd.Parameters.AddWithValue("@details", od.details.ToString()).NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Jsonb;
                        cmd.Parameters.AddWithValue("@cb", (string)od.submittedBy.Value);
                        cmd.Parameters.AddWithValue("@co", DateTime.Now);
                        cmd.Parameters.AddWithValue("@mb", (string)od.submittedBy.Value);
                        cmd.Parameters.AddWithValue("@mo", DateTime.Now);
                        cmd.ExecuteNonQuery();
                    }
                }
                finally
                {
                    connection.Close();
                }
            }

            // Post it to Camunda
            var camunda = new CamundaEngineClient(new System.Uri(Startup.camundaUrl), null, null);

            camunda.Startup();
            try
            {
                var ft = o.ToObject <Dictionary <string, object> >();
                ft["fileId"] = fileId;
                string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("dodoAppRule", ft);
            }
            finally
            {
                camunda.Shutdown();
            }
            return(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
        }
Example #15
0
 private void Init()
 {
     try
     {
         camunda = new CamundaEngineClient(
             new Uri(CamundaSettings.Server),
             null, null);
     }
     catch (Exception ex)
     {
         Logger.LogError(ex, "failure to create camunda instance");
     }
 }
Example #16
0
        public static void CompleteTask(Guid taskId)
        {
            string wfId = null;

            using (var connection = new NpgsqlConnection(Startup.databaseConnection))
            {
                //Ignore user for now...
                connection.Open();
                try
                {
                    string stmt1 = @"SELECT wf_task_id FROM dbo.tasks WHERE id=@id";
                    using (var cmd = new NpgsqlCommand(stmt1, connection))
                    {
                        cmd.Parameters.AddWithValue("@id", taskId);
                        wfId = (string)cmd.ExecuteScalar();
                    }
                    string stmt2 = @"UPDATE dbo.tasks SET status='completed', complete_date=@dt1";
                    using (var cmd2 = new NpgsqlCommand(stmt2, connection))
                    {
                        cmd2.Parameters.AddWithValue("@dt1", DateTime.UtcNow);
                        cmd2.ExecuteNonQuery();
                    }
                }
                finally
                {
                    connection.Close();
                }

                if (wfId != null)
                {
                    var camunda = new CamundaEngineClient(new System.Uri(Startup.camundaUrl), null, null);
                    camunda.Startup();
                    try
                    {
                        camunda.HumanTaskService.Complete(wfId, new Dictionary <string, object>()
                        {
                            { "completed", true }
                        });
                    }
                    finally
                    {
                        camunda.Shutdown();
                    }
                }
            }
        }
Example #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            CamundaEngineClient camunda = new CamundaEngineClient(
                new System.Uri($"http://{Environment.GetEnvironmentVariable("Host")}:{Environment.GetEnvironmentVariable("HttpGatewayPort")}/camunda/rest/engine/default/"),
                Environment.GetEnvironmentVariable("ClientId"),
                Environment.GetEnvironmentVariable("ClientSecret")
                );

            camunda.Startup();

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        public ActionResult PutCustomer([FromQuery] String name)
        {
            System.Console.WriteLine("Starting onboarding process for '" + name + "'");

            var camunda = new CamundaEngineClient(new Uri("http://localhost:8080/engine-rest/engine/default/"), null, null);

            var traceId = Guid.NewGuid().ToString();
            var result  = new Dictionary <String, String>();

            string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance(
                "onboarding",
                traceId,
                new Dictionary <string, object>()
            {
                { "customer", name }
            });

            result.Add("traceId", traceId);
            return(Ok(result));
        }
Example #19
0
        public void TestHappyPath()
        {
            // Engine client should point to a dedicated Camunda instance for test, preferrably locally available
            var camunda = new CamundaEngineClient(new System.Uri("http://localhost:8080/engine-rest/engine/default/"), null, null);

            // Deploy the process under test
            string deploymentId = camunda.RepositoryService.Deploy("testcase", new List <object> {
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "Urlaubsantrag.Models.Urlaubsantrag.bpmn")
            });

            try
            {
                string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("Urlaubsantrag", new Dictionary <string, object>()
                {
                    { "name", "Bernd Rücker" },
                    { "vacationStartDate", 10 },
                    { "duration", 5 }
                });

                var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>()
                {
                    { "processInstanceId", processInstanceId }
                });
                Assert.AreEqual(1, tasks.Count);
                Assert.AreEqual("UserTask_UrlaubGenehmigen", tasks.First().TaskDefinitionKey);

                camunda.HumanTaskService.Complete(tasks.First().Id, new Dictionary <string, object>()
                {
                    { "approved", true }
                });


                var externalTasks = camunda.ExternalTaskService.FetchAndLockTasks(
                    "worker1",
                    100,
                    "leaveAccount",
                    1000,
                    new List <string>()
                {
                    "name"
                });

                // Do the real service logic / calls

                camunda.ExternalTaskService.Complete("worker1", externalTasks.First().Id, new Dictionary <string, object>()
                {
                    { "someResult", 42 }
                });

                // TODO: Simulate timer
                //externalTasks = camunda.ExternalTaskService.FetchAndLockTasks("testcase", 100, "informColleagues", 1000, new List<string>());
                //Assert.AreEqual(1, externalTasks.Count);
                //Assert.AreEqual("ServiceTask_KollegenInformieren", externalTasks.First().ActivityId);
                //camunda.ExternalTaskService.Complete("testcase", externalTasks.First().Id, new Dictionary<string, object>());

                // not the process instance has ended, TODO: Check state with History
            }
            finally
            {
                // cleanup after test case
                camunda.RepositoryService.DeleteDeployment(deploymentId);
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true);
            var configuration = builder.Build();

            connectionString = configuration.GetSection("database").Value;
            camundaUrl       = configuration.GetSection("camunda").Value;

            if (FetchBPMN())
            {
                Console.WriteLine("workflow found");
                var camunda = new CamundaEngineClient(new System.Uri(camundaUrl), null, null);
                camunda.Startup();
                try
                {
                    DateTime lastCheck = DateTime.Now.AddDays(-1);
                    while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
                    {
                        var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>()
                        {
                            { "createdAfter", lastCheck.ToString("yyyy-MM-ddTHH:mm:ss") },
                            { "processDefinitionName", "Incident" }
                        });
                        lastCheck = DateTime.Now;
                        if (tasks != null && tasks.Count != 0)
                        {
                            Console.WriteLine("Human task detected");
                            using (var connection = new NpgsqlConnection(connectionString))
                            {
                                const string stmtInsertTask = @"INSERT INTO dbo.tasks(id, user_id, wf_task_id, task_type, status, created_by, due_date, complete_date, subject, entity, entity_id, action_type, details)
	                                VALUES ( @id, @uid, @wf_task_id, @type, 'assigned', 'workflow', @due_date, null, @subject, 'incident', @file_id, @action_type, @details);"    ;
                                connection.Open();
                                try
                                {
                                    using (var cmd = new NpgsqlCommand(stmtInsertTask, connection))
                                    {
                                        foreach (var task in tasks)
                                        {
                                            var vs = camunda.HumanTaskService.LoadVariables(task.Id);
                                            var ps = Program.GetTaskVariables("userTask", task.TaskDefinitionKey);

                                            string roleName = ps["roleName"];
                                            string unitId   = (string)vs["unitId"];
                                            Guid   uid      = FindUserByParams(unitId, roleName);

                                            string expiry = ps["expiry"];
                                            int    days;

                                            if (!Int32.TryParse(expiry, out days))
                                            {
                                                days = 0;
                                            }

                                            cmd.Parameters.Clear();
                                            cmd.Parameters.AddWithValue("@id", Guid.NewGuid());
                                            cmd.Parameters.AddWithValue("@uid", uid);
                                            cmd.Parameters.AddWithValue("@wf_task_id", task.Id);
                                            cmd.Parameters.AddWithValue("@type", ps["taskType"]);
                                            if (days > 0)
                                            {
                                                cmd.Parameters.AddWithValue("@due_date", DateTime.UtcNow.AddDays(days));
                                            }
                                            else
                                            {
                                                cmd.Parameters.AddWithValue("@due_date", DBNull.Value);
                                            }

                                            cmd.Parameters.AddWithValue("@subject", "someText");
                                            cmd.Parameters.AddWithValue("@file_id", Guid.Parse((string)vs["fileId"]));
                                            cmd.Parameters.AddWithValue("@action_type", "fakeFormName");
                                            cmd.Parameters.AddWithValue("@details", "Something else");
                                            cmd.ExecuteNonQuery();
                                            // Some log?
                                        }
                                    }
                                }
                                finally
                                {
                                    connection.Close();
                                }
                            }
                        }
                        System.Threading.Thread.Sleep(2000);
                    }
                }
                finally
                {
                    camunda.Shutdown();
                }
            }
            else
            {
                Console.WriteLine("No workflow found");
            }
        }
Example #21
0
        static void Main(string[] args)
        {
            const string ruleName = "testRule";
            var          fileName = Directory.GetCurrentDirectory() + "\\" + "testRule.bpmn";

            byte[] ruleContent = System.IO.File.ReadAllBytes(fileName);


            var camunda = new CamundaEngineClient(new System.Uri("http://*****:*****@b.com" },
                { "details", new Dictionary <string, object> {
                      { "patient", "Smith" },
                      { "age", 17 },
                      { "gender", "Male" }
                  } }
            };

            string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance(ruleName, fakeFile);

            DateTime lastCheck = DateTime.Now.AddDays(-1);

            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
            {
                var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>()
                {
                    { "createdAfter", lastCheck.ToString("yyyy-MM-ddTHH:mm:ss") },
                    { "processDefinitionName", "Incident" }
                });
                lastCheck = DateTime.Now;
                if (tasks != null && tasks.Count() != 0)
                {
                    Console.WriteLine("Human task detected");
                    foreach (var task in tasks)
                    {
                        var vs = camunda.HumanTaskService.LoadVariables(task.Id);
                        var ps = Program.GetTaskVariables("userTask", task.TaskDefinitionKey);
                        System.Threading.Thread.Sleep(5000);
                        camunda.HumanTaskService.Complete(task.Id, new Dictionary <string, object>()
                        {
                            { "completed", true }
                        });
                        Console.WriteLine("Complete human task " + ps["taskType"] + "on " + vs["fileId"].ToString());
                    }
                }
                System.Threading.Thread.Sleep(5000);
            }

            camunda.Shutdown(); // Stop Task Workers
        }
Example #22
0
        public static void PublishWorkflow(string bpmn)
        {
            bpmn = bpmn.Trim();
            string connectionString = Startup.databaseConnection;

            using (var connection = new NpgsqlConnection(connectionString))
            {
                connection.Open();
                try
                {
                    Guid         id   = Guid.Empty;
                    const string stmt = @"SELECT id FROM dbo.workflows WHERE entity='Incident'";
                    using (var cmd = new NpgsqlCommand(stmt, connection))
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                id = reader.GetGuid(0);
                            }
                        }
                    }
                    if (id == Guid.Empty)
                    {
                        string stmtInsert = @"INSERT INTO dbo.workflows( id, tenant_id, entity, process_id, bpmn_details, created_by, created_on, last_modified_by, last_modified_on)
                                            VALUES(@id, @tid, 'Incident', null, @bpmn, 'Jian', current_timestamp, 'Jian', current_timestamp)";
                        using (var cmd = new NpgsqlCommand(stmtInsert, connection))
                        {
                            cmd.Parameters.AddWithValue("@id", Guid.NewGuid());
                            cmd.Parameters.AddWithValue("@tid", Guid.Parse("fef554a9-e234-4177-8dac-0680702d4ec7"));
                            var p = cmd.Parameters.AddWithValue("@bpmn", bpmn);
                            p.DbType = DbType.Xml;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    else
                    {
                        string stmtUpdate = @"UPDATE dbo.workflows set bpmn_details = @bpmn WHERE id = @id";
                        using (var cmd = new NpgsqlCommand(stmtUpdate, connection))
                        {
                            cmd.Parameters.AddWithValue("@id", id);
                            var p = cmd.Parameters.AddWithValue("@bpmn", bpmn);
                            p.DbType = DbType.Xml;
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                finally
                {
                    connection.Close();
                }
            }

            string camundaUrl = Startup.camundaUrl;
            var    camunda    = new CamundaEngineClient(new System.Uri(camundaUrl), null, null);

            camunda.Startup();
            try
            {
                string deploymentId = camunda.RepositoryService.Deploy("DodoAppRule", new List <object> {
                    new FileParameter(System.Text.Encoding.UTF8.GetBytes(bpmn), "DodoAppRule.bpmn")
                });
            }
            finally
            {
                camunda.Shutdown();
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("\n\n" + "Iniciando Exemplo camunda CSharp.\n\n");

            // Engine client should point to a dedicated Camunda instance for test, preferrably locally available
            var camunda = new CamundaEngineClient(new System.Uri("http://localhost:8080/engine-rest/engine/default/"), "demo", "demo");

            Console.WriteLine("\n" + "Conectado ao camunda\n");


            // Deploy the process under test
            string deploymentId = camunda.RepositoryService.Deploy("RunMatriculaBPMN", new List <object> {
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "RunMatricula.CamundaModels.diagram_matricula.bpmn"),
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "RunMatricula.CamundaModels.diagram_categoriaidade.dmn"),
                FileParameter.FromManifestResource(Assembly.GetExecutingAssembly(), "RunMatricula.CamundaModels.start.html")
            });

            Console.WriteLine("\n" + "Deploy realizado com sucesso Deplouyid =" + deploymentId + "\n");
            Console.ReadLine(); // wait for ANY KEY

            // inicia uma instancia do processo samplecsharp
            string processInstanceId = camunda.BpmnWorkflowService.StartProcessInstance("processomatricula", new Dictionary <string, object>()
            {
                { "professor", "professor01" }
            });

            Console.WriteLine("\n" + "consulte a instancia criada =" + processInstanceId);
            Console.ReadLine(); // wait for ANY KEY

            var tasks = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>()
            {
                { "processInstanceId", processInstanceId }
            });

            Console.WriteLine("\n" + "LoadTask retornou" + tasks.Count + " Tarefas");
            Console.WriteLine("\n" + "A key da tarefa he =" + tasks.First().TaskDefinitionKey);
            Console.WriteLine("\n" + "A assigner da tarefa he =" + tasks.First().Assignee);
            Console.ReadLine(); // wait for ANY KEY

            camunda.HumanTaskService.Complete(tasks.First().Id, new Dictionary <string, object>()
            {
                { "nome", "Marcio Junior Vieira" },
                { "idade", "19" }
            });

            Console.WriteLine("\n" + "tarefa task1 completa");
            Console.ReadLine(); // wait for ANY KEY

            var tasks2 = camunda.HumanTaskService.LoadTasks(new Dictionary <string, string>()
            {
                { "processInstanceId", processInstanceId }
            });

            Console.WriteLine("\n" + "LoadTask retornou" + tasks2.Count + " Tarefas");
            Console.WriteLine("\n" + "A key da tarefa he =" + tasks2.First().TaskDefinitionKey);
            Console.WriteLine("\n" + "A assigner da tarefa he =" + tasks2.First().Assignee);

            camunda.HumanTaskService.Complete(tasks2.First().Id, new Dictionary <string, object>());

            Console.WriteLine("\n" + "tarefa task2 completa");

            Console.ReadLine(); // wait for ANY KEY
        }