public void ToList_WithValidSmartObjectList()
        {
            //Arrange
            var smartObject = SmartObjectFactory.GetSmartObject(SmartObjectOption.ProcessInfo);

            smartObject.MethodToExecute = smartObject.ListMethods[0].Name;

            var smartObjectList = new SmartObjectList();

            smartObjectList.SmartObjectsList.Add(smartObject);

            // Action
            var actual = SmartObjectExtensions.ToList(smartObjectList, smartObject.MethodToExecute);

            // Assert
            Assert.AreEqual(1, actual.Count());
        }
        public static IEnumerable <SmartObject> ToList(this SmartObjectList smartObjectList, string methodToExecute)
        {
            smartObjectList.ThrowIfNull("smartObjectList");

            var list = new List <SmartObject>();

            foreach (SmartObject smartObject in smartObjectList.SmartObjectsList)
            {
                if (!string.IsNullOrWhiteSpace(methodToExecute))
                {
                    smartObject.MethodToExecute = methodToExecute;
                }

                list.Add(smartObject);
            }

            return(list);
        }
Exemplo n.º 3
0
        private string getTaxData()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();


            SmartObjectClientServer smoServer = ConnectionClass.GetSmartObjectClient();
            SmartObject             mmdSmo    = smoServer.GetSmartObject(this.SMOInternalName);
            SmartListMethod         getList   = mmdSmo.ListMethods["GetAllChildTermsInTermSet"];

            getList.InputProperties["TermStoreId"].Value = this.TermStoreGuid;
            getList.InputProperties["TermSetId"].Value   = this.TermSetGuid;
            mmdSmo.MethodToExecute = "GetAllChildTermsInTermSet";


            var             TermList = new List <Term>();
            SmartObjectList smoList  = smoServer.ExecuteList(mmdSmo);

            foreach (SmartObject smo in smoList.SmartObjectsList)
            {
                string termId    = smo.Properties["TermId"].Value;
                string termLabel = smo.Properties["Label"].Value;
                string termPath  = smo.Properties["Path"].Value;
                TermList.Add(new Term()
                {
                    TermId = termId, TermLabel = termLabel, TermPath = termPath
                });
            }
            var serializer  = new JavaScriptSerializer();
            var serialized  = serializer.Serialize(TermList);
            var fixedString = serialized.Replace("&quot;", @"""");

            sb.Append(@"{""terms"":");
            sb.Append(fixedString);
            sb.Append(@"}");
            return(HttpUtility.HtmlDecode(sb.ToString()));
        }
Exemplo n.º 4
0
        public void RetryWorkflow()
        {
            SmartObjectClientServer soServer = this.NewSmartObjectClientServer();

            try
            {
                using (soServer.Connection)
                {
                    SmartObject soError = soServer.GetSmartObject("com_K2_System_Workflow_SmartObject_ErrorLog");
                    //set method we want to execute.
                    soError.MethodToExecute = "GetErrorLogs";
                    soError.Properties["ErrorProfileName"].Value = "All";

                    //get the list of SmartObjects returned by the method
                    SmartObjectList soListError = soServer.ExecuteList(soError);
                    //iterate over the collection

                    List <K2ErrorLog> listK2ErrorLog = new List <K2ErrorLog>();
                    string[]          workflowNames  = this.AppConfig.WorkflowNames.Split(';');
                    foreach (SmartObject soItem in soListError.SmartObjectsList)
                    {
                        for (int i = 0; i < workflowNames.Length; i++)
                        {
                            if (soItem.Properties["ProcessName"].Value == workflowNames[i])
                            {
                                string soDescription = soItem.Properties["Description"].Value.ToString();
                                if (soDescription.Contains("was deadlocked on lock resources with another process") ||
                                    soDescription.Contains("SQL") ||
                                    soDescription.Contains("IIF"))
                                {
                                    listK2ErrorLog.Add(new K2ErrorLog(soItem));
                                }
                            }
                        }
                        //ambil hanya transaksi deadlocked saja
                    }

                    foreach (K2ErrorLog k2ErrorLog in listK2ErrorLog)
                    {
                        SmartObject errorSO = soServer.GetSmartObject("com_K2_System_Workflow_SmartObject_ErrorLog");
                        //set method we want to execute.
                        errorSO.MethodToExecute = "RetryError";

                        errorSO.Properties["Id"].Value         = k2ErrorLog.Id.ToString();
                        errorSO.Properties["ProcInstId"].Value = k2ErrorLog.ProcInstID.ToString();
                        errorSO.Properties["TypeId"].Value     = k2ErrorLog.TypeID.ToString();
                        errorSO.Properties["ObjectId"].Value   = k2ErrorLog.ObjectID.ToString();
                        errorSO.Properties["UserName"].Value   = "System";

                        this.Logger.Info("K2 Retry ProcInstId = " + k2ErrorLog.ProcInstID.ToString());

                        //get the list of SmartObjects returned by the method
                        Thread.Sleep(1000); //delay 1 detik
                        soServer.ExecuteScalar(errorSO);
                    }
                }
            }
            finally
            {
                soServer.DeleteConnection();
            }
        }
        private void btnGenerateCRMProcess_Click(object sender, RoutedEventArgs e)
        {
            SourceCode.SmartObjects.Client.SmartObjectClientServer smoServer = new SmartObjectClientServer();
            smoServer.CreateConnection();
            smoServer.Connection.Open("Integrated=True;IsPrimaryLogin=True;Authenticate=True;EncryptedPassword=False;Host=localhost;Port=5555");

            SmartObject smoCRM = smoServer.GetSmartObject("Demo_K2_CRM_Functions");

            smoCRM.MethodToExecute = "GetAllEntities";

            SmartObjectList smoEntities = smoServer.ExecuteList(smoCRM);


            // get state status details
            CRMPicklist pl = new CRMPicklist();

//            pl.AttributeLogicalName = att.LogicalName;
            pl.EntityLogicalName = "lead";

            CRMPicklist cp = functions.CRMGetStateStatus(pl);

            int seq = 0;

            foreach (CRMPicklistOption plo in cp.Picklist.OrderBy(p => p.PicklistParentValue).OrderBy(p => p.PicklistValue))
            {
                StateStatus ss = new StateStatus();
                ss.State      = plo.PicklistParentValue;
                ss.StateName  = plo.PicklistParentLabel;
                ss.Status     = plo.PicklistValue;
                ss.StatusName = plo.PicklistLabel;
                ss.Sequence   = seq;
                seq++;
                CRMSS.Add(ss);
            }


            bool ActiveOnly = true;


            string nowish = DateTime.Now.ToString("yyyyMMddHHmmss");

            // Create new process
            process = WorkflowFactory.CreateProcess <DefaultProcess>(nowish, WizardNames.DefaultProcess);

            DataField dfEntityId   = new DataField("Entity Id", "");
            DataField dfEntityName = new DataField("Entity Name", "");

            process.DataFields.Add(dfEntityId);
            process.DataFields.Add(dfEntityName);


            var dimensions = WorkflowHelpers.GetActivityDimensions(process.StartActivity);
            int x          = Convert.ToInt32(Math.Round(dimensions.X + dimensions.Width + 40D));
            int y          = Convert.ToInt32(dimensions.Y) + 100;

            DefaultActivity PrevStatAct   = null;
            DefaultActivity PrevReviewAct = null;

            PrevStatAct = CreateStartActivity("", dfEntityId, dfEntityName, x, ref y);

            SourceCode.Workflow.Authoring.Line startLine = WorkflowFactory.CreateLine("StartLine");
            startLine.StartActivity  = process.StartActivity;
            startLine.FinishActivity = PrevStatAct;
            process.Lines.Add(startLine);

            int c = 0;

            foreach (StateStatus ss in CRMSS.OrderBy(p => p.Sequence))
            {
                DefaultActivity act = CreateStatusActivity(ss.StateName + " - " + ss.StatusName, dfEntityId, dfEntityName, x, ref y);
                if (PrevReviewAct != null)
                {
                    PrevReviewAct.FinishLines[0].FinishActivity = act;
                }

                if (c == 0)
                {
                    SourceCode.Workflow.Authoring.Line firstline = WorkflowFactory.CreateLine("Firstline");
                    firstline.StartActivity  = PrevStatAct;
                    firstline.FinishActivity = act;
                    process.Lines.Add(firstline);
                }
                c++;

                DefaultActivity act1 = null;
                if (!ActiveOnly || ActiveOnly && ss.State == 0)
                {
                    act1 = CreateCRMActivity(ss.StateName + " - " + ss.StatusName, dfEntityId, dfEntityName, x, ref y);

                    SourceCode.Workflow.Authoring.Line line = WorkflowFactory.CreateLine("Line " + ss.Sequence);
                    line.StartActivity  = act;
                    line.FinishActivity = act1;
                    process.Lines.Add(line);

                    if (PrevStatAct != null)
                    {
                        act1.FinishLines[1].FinishActivity = PrevStatAct;
                    }
                }

                if (act1 == null && PrevStatAct.FinishLines.Count == 0)
                {
                    PrevReviewAct = null;
                    SourceCode.Workflow.Authoring.Line updateLine = WorkflowFactory.CreateLine("Update Line " + ss.Sequence);
                    updateLine.StartActivity  = PrevStatAct;
                    updateLine.FinishActivity = act;
                    process.Lines.Add(updateLine);
                }


                if (act != null)
                {
                    WorkflowHelpers.AutoPositionLines(act.StartLines);
                    WorkflowHelpers.AutoPositionLines(act.FinishLines);
                }
                if (act1 != null)
                {
                    WorkflowHelpers.AutoPositionLines(act1.StartLines);
                    WorkflowHelpers.AutoPositionLines(act1.FinishLines);
                }

                PrevReviewAct = act1;
                PrevStatAct   = act;
            }



            process.FinishRule = new DesignCRMClient.CRMClientProcessFinishRule();

            process.SaveAs(txtProcessPath.Text + nowish + ".kprx");

            process = null;
        }
        public void Upload()
        {
            var createMethod       = _settings.CreateMethod ?? "Create";
            var transactionIdName  = _settings.TransactionIdName.FormatColumnName(_settings.HeaderRowSpaces) ?? string.Empty;
            var transactionIdValue = _settings.TransactionIdValue ?? string.Empty;
            var isTransaction      = !string.IsNullOrWhiteSpace(transactionIdName) &&
                                     !string.IsNullOrWhiteSpace(transactionIdValue);

            try
            {
                var conn = GetSmartObjectConnection();

                using (conn.Connection)
                {
                    var importSmartObject = conn.GetSmartObject(_settings.ToSystemSmartObjectName);

                    if (!importSmartObject.Methods.Contains(createMethod))
                    {
                        throw new InvalidOperationException(
                                  $"Could not find method '{createMethod}' on SmartObject '{_settings.SmartObjectName}'.");
                    }

                    var methodType = importSmartObject.Methods[createMethod].Type;

                    if (methodType != MethodType.create && methodType != MethodType.execute)
                    {
                        throw new InvalidOperationException(
                                  $"Method '{createMethod}' on SmartObject '{_settings.SmartObjectName}' is not of type 'Create' or 'Execute'.");
                    }

                    importSmartObject.MethodToExecute = createMethod;

                    // Populate an array of column names
                    var columns = new string[_settings.Data.Columns.Count];
                    foreach (DataColumn col in _settings.Data.Columns)
                    {
                        columns[col.Ordinal] = col.ColumnName;
                    }

                    var smoColumns = new string[importSmartObject.Properties.Count];
                    for (var i = 0; i < importSmartObject.Properties.Count; i++)
                    {
                        smoColumns[i] = importSmartObject.Properties[i].Name;
                    }

                    // Get list of matching columns
                    var matches = columns
                                  .Join(smoColumns, dtCol => dtCol, smoCol => smoCol, (dtCol, smoCol) => smoCol).ToList();

                    if (matches.Count == 0)
                    {
                        throw new InvalidOperationException(
                                  $"No matching columns found on SmartObject '{_settings.SmartObjectName}' and the imported data.");
                    }

                    using (var inputList = new SmartObjectList())
                    {
                        if (isTransaction && importSmartObject.Properties.GetIndexbyName(transactionIdName) == -1)
                        {
                            throw new ApplicationException(
                                      $"Transaction Id column '{transactionIdName}' cannot be found on the SmartObject '{_settings.SmartObjectName}'.");
                        }

                        foreach (DataRow dr in _settings.Data.Rows)
                        {
                            var newSmartObject = importSmartObject.Clone();
                            newSmartObject.MethodToExecute = createMethod;

                            // Loop through collection of matching fields and insert the values
                            foreach (var column in matches)
                            {
                                var smoColumn = newSmartObject.Properties[column];
                                smoColumn.Value = smoColumn.GetValue(dr[column]);
                            }

                            // Add the transaction Id value for identification purposes.
                            if (isTransaction)
                            {
                                newSmartObject.Properties[transactionIdName].Value = transactionIdValue;
                            }

                            inputList.SmartObjectsList.Add(newSmartObject);
                        }

                        if (_settings.IsBulkImport)
                        {
                            conn.ExecuteBulkScalar(importSmartObject, inputList);

                            Status   = UploadStatus.Complete;
                            Message +=
                                $"Uploaded {_settings.Data.Rows.Count} rows with {matches.Count} matching columns to '{_settings.SmartObjectName}'. ";

                            if (importSmartObject.Properties.HasDateProperty())
                            {
                                Message += "WARNING: Bulk upload completed with Date / Time property present on SmartObject. ";
                            }
                        }
                        else
                        {
                            var uploaded   = 0;
                            var currentRow = 0;
                            var failedRows = "";

                            Status = UploadStatus.Complete;

                            foreach (SmartObject smo in inputList.SmartObjectsList)
                            {
                                currentRow++;
                                try
                                {
                                    conn.ExecuteScalar(smo);
                                    uploaded++;
                                }
                                catch
                                {
                                    Status      = UploadStatus.Partial;
                                    failedRows += $"{currentRow}, ";
                                }
                            }

                            Message +=
                                $"Uploaded {uploaded} of {_settings.Data.Rows.Count} rows with {matches.Count} matching columns to '{_settings.SmartObjectName}'. ";

                            if (failedRows.Length > 0)
                            {
                                Message += $"The following rows failed to upload: {failedRows.Remove(failedRows.Length - 2)}. ";
                            }
                        }
                    }

                    // Indicate the Transaction Id name and value in the results field
                    if (isTransaction)
                    {
                        Message += $"Transaction '{transactionIdName}' added with value '{transactionIdValue}'. ";
                    }
                }
            }
            catch (ApplicationException aEx)
            {
                Status  = UploadStatus.Error;
                Message = "Unable to insert data into SmartObject: " + aEx.Message;
            }
            catch (FormatException fEx)
            {
                Status  = UploadStatus.Error;
                Message = "Unable to insert data into SmartObject due to data type mismatch: " + fEx.Message;
            }
            catch (System.Net.Sockets.SocketException)
            {
                Status  = UploadStatus.Error;
                Message = $"Could not connect to '{_settings.K2Server}' on port '{_settings.Port}'";
            }
            catch (SmartObjectNotFoundException)
            {
                Status  = UploadStatus.Error;
                Message = $"Could not find SmartObject '{_settings.SmartObjectName}'";
            }
            catch (InvalidOperationException ioEx)
            {
                Status  = UploadStatus.Error;
                Message = ioEx.Message;
            }
            catch (SmartObjectException smoEx)
            {
                Status = UploadStatus.Error;
                if (!_settings.IsBulkImport)
                {
                    foreach (SmartObjectExceptionData smOExBrokerData in smoEx.BrokerData)
                    {
                        if (smOExBrokerData.Message.Equals("Unable to create the object. An object with the specified key property(s) already exist."))
                        {
                            Message += "Error uploading data - Cannot upload row by row if data has a duplicate key value, try bulk methods or add an auto number / auto guid column to the target SmartObject. ";
                        }
                    }
                }
                else
                {
                    foreach (SmartObjectExceptionData smOExBrokerData in smoEx.BrokerData)
                    {
                        Message += smOExBrokerData.Message;
                    }
                }
            }
            catch (Exception ex)
            {
                Status   = UploadStatus.Error;
                Message += $"Unknown error: {ex.Message}";
            }
        }