private string GetDynamicParamValue(string paramName)
        {
            RuntimeDefinedParameter paramDef;

            _runtimeParamsCollection.TryGetValue(paramName, out paramDef);

            return((paramDef == null || paramDef.Value == null) ? String.Empty : paramDef.Value.ToString());
        }
示例#2
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var CollectionRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Collection", out CollectionRuntime);
                string Collection = "";
                if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString()))
                {
                    Collection = CollectionRuntime.Value.ToString();
                }
                string col = Collection;
                if (string.IsNullOrEmpty(Id))
                {
                    if (Object != null)
                    {
                        json = Object.toJson();
                    }
                    JObject tmpObject = JObject.Parse(json);
                    if (string.IsNullOrEmpty(col)) // If not overwriten by param, then check for old collection
                    {
                        if (tmpObject.ContainsKey("__pscollection"))
                        {
                            col = tmpObject.Value <string>("__pscollection");
                        }
                        else
                        {
                            col = "entities";
                        }
                    }
                    Id = tmpObject.Value <string>("_id");
                }
                if (string.IsNullOrEmpty(col))
                {
                    Id = null;
                    WriteError(new ErrorRecord(new ArgumentException("Collection is mandatory when not using objects"), "", ErrorCategory.InvalidArgument, null));
                    return;
                }
                await global.webSocketClient.DeleteOne(col, Id);

                Id = null;
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
                Id = null;
            }
        }
示例#3
0
        private string GetDynamicNamespace()
        {
            if (_dynamicParameters == null)
            {
                return(null);
            }

            RuntimeDefinedParameter runtimeParameter;

            if (!_dynamicParameters.TryGetValue(CimNamespaceParameter, out runtimeParameter))
            {
                return(null);
            }

            return(runtimeParameter.Value as string);
        }
示例#4
0
        private Dictionary <string, ScriptBlock> GetDslKeywordDefinitions(ResourceSchema resourceSchema)
        {
            if (resourceSchema.Discriminator is null)
            {
                return(resourceSchema.KeywordDefinitions);
            }

            if (!_dynamicParameters.TryGetValue(resourceSchema.Discriminator, out RuntimeDefinedParameter discriminatorParameter))
            {
                // This should be impossible since the parameter is mandatory, but nevertheless...
                var exception = new ArgumentException($"The '{resourceSchema.Discriminator}' parameter must be provided");
                this.ThrowTerminatingError(exception, "DiscriminatorParameterMissing", ErrorCategory.InvalidArgument, target: this);
                return(null);
            }

            string discriminatorValue;

            try
            {
                discriminatorValue = ((IArmString)discriminatorParameter.Value).CoerceToString();
            }
            catch (Exception e)
            {
                this.ThrowTerminatingError(e, "InvalidDiscriminatorType", ErrorCategory.InvalidArgument, target: discriminatorParameter);
                return(null);
            }

            if (!resourceSchema.DiscriminatedKeywords.TryGetValue(discriminatorValue, out Dictionary <string, ScriptBlock> discriminatedKeywords))
            {
                // This shouldn't be possible due to the ValidateSet attribute, but we handle it anyway
                this.ThrowTerminatingError(
                    new KeyNotFoundException($"'{discriminatorValue}' is not a valid value for parameter '{resourceSchema.Discriminator}'"),
                    "InvalidDiscriminatorValue",
                    ErrorCategory.InvalidArgument,
                    target: discriminatorValue);
                return(null);
            }

            var keywords = new Dictionary <string, ScriptBlock>(resourceSchema.KeywordDefinitions, StringComparer.OrdinalIgnoreCase);

            foreach (KeyValuePair <string, ScriptBlock> keywordDefinition in discriminatedKeywords)
            {
                keywords[keywordDefinition.Key] = keywordDefinition.Value;
            }

            return(keywords);
        }
示例#5
0
        protected override void BeginProcessing()
        {
            if (Force)
            {
                fs = new FileStream(Path, FileMode.Create, FileAccess.Write, FileShare.None);
            }
            else
            {
                fs = new FileStream(Path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
            }

            #region SetPageSize
            var PageSizeRuntime = new RuntimeDefinedParameter();
            _staticStorage.TryGetValue("PageSize", out PageSizeRuntime);
            WriteDebug("setting PageSize property info");

            FieldInfo pageSizeProperty = typeof(PageSize).GetField(PageSizeRuntime.Value.ToString());
            WriteDebug("Selecting PageSize");
            Rectangle rectangle = (Rectangle)pageSizeProperty.GetValue(null);
            #endregion


            #region SetPageOrientation
            if (FlipOrientation)
            {
                //flips the orientation of the page.
                WriteDebug("Fliping page dimensions and instantiating document");
                doc = new Document(rectangle.Rotate());
            }
            else
            {
                WriteDebug("instantiating document");
                doc = new Document(rectangle);
            }
            #endregion
            writer = PdfWriter.GetInstance(doc, fs);
            WriteDebug("stamping document with creation time and author");
            doc.AddCreationDate();
            doc.AddAuthor(Environment.UserName);
            WriteDebug("Opening Document");
            doc.Open();
            base.BeginProcessing();
        }
        public string GetMemoryValue(CacheServiceSkuType sku)
        {
            RuntimeDefinedParameter memoryParameter;
            string memory = string.Empty;

            if (_parameters.TryGetValue(MemoryParameterName, out memoryParameter))
            {
                if (memoryParameter != null && memoryParameter.Value != null)
                {
                    memory = memoryParameter.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(memory))
            {
                memory = new CacheSkuCountConvert(sku).ToMemorySize(1);
            }
            return(memory);
        }
        private static void UpdateParametersWithObject(string[] staticParameters, RuntimeDefinedParameterDictionary dynamicParameters, Hashtable templateParameterObject)
        {
            const string duplicatedParameterSuffix = "FromTemplate";

            if (templateParameterObject != null)
            {
                foreach (string paramName in templateParameterObject.Keys)
                {
                    string dynamicParamName = staticParameters.Contains(paramName, StringComparer.OrdinalIgnoreCase)
                        ? paramName + duplicatedParameterSuffix
                        : paramName;

                    if (dynamicParameters.TryGetValue(dynamicParamName, out RuntimeDefinedParameter dynamicParameter))
                    {
                        dynamicParameter.Value = templateParameterObject[paramName] is TemplateFileParameterV1 templateFileParameterV1
                            ? templateFileParameterV1.Value
                            : templateParameterObject[paramName];

                        dynamicParameter.IsSet = true;
                        ((ParameterAttribute)dynamicParameter.Attributes[0]).Mandatory = false;
                    }
                }
            }
        }
示例#8
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var CollectionRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Collection", out CollectionRuntime);
                string Collection = "";
                if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString()))
                {
                    Collection = CollectionRuntime.Value.ToString();
                }
                if (string.IsNullOrEmpty(Collection))
                {
                    Collection = "entities";
                }
                string col = Collection;
                if (!string.IsNullOrEmpty(Query))
                {
                    var affectedrows = await global.webSocketClient.DeleteMany(col, Query);

                    WriteVerbose("Removed " + affectedrows + " rows from " + col);
                    return;
                }
                if (Objects != null && Objects.Count > 0)
                {
                    var colls = new Dictionary <string, List <string> >();
                    foreach (PSObject obj in Objects)
                    {
                        col = Collection;
                        if (obj.Properties["__pscollection"] != null && obj.Properties["__pscollection"].Value != null)
                        {
                            col = obj.Properties["__pscollection"].Value.ToString();
                        }
                        if (!colls.ContainsKey(col))
                        {
                            colls.Add(col, new List <string>());
                        }
                        Id = obj.Properties["_id"].Value.ToString();
                        colls[col].Add(Id);
                    }
                    foreach (var kv in colls)
                    {
                        var affectedrows = await global.webSocketClient.DeleteMany(kv.Key, kv.Value.ToArray());

                        WriteVerbose("Removed " + affectedrows + " rows from " + col);
                    }
                    return;
                }
                if (!string.IsNullOrEmpty(json))
                {
                    JObject tmpObject = JObject.Parse(json);
                    if (string.IsNullOrEmpty(col)) // If not overwriten by param, then check for old collection
                    {
                        if (tmpObject.ContainsKey("__pscollection"))
                        {
                            col = tmpObject.Value <string>("__pscollection");
                        }
                        else
                        {
                            col = "entities";
                        }
                    }
                    Id = tmpObject.Value <string>("_id");
                }
                if (string.IsNullOrEmpty(col))
                {
                    Id = null;
                    WriteError(new ErrorRecord(new ArgumentException("Collection is mandatory when not using objects"), "", ErrorCategory.InvalidArgument, null));
                    return;
                }
                WriteVerbose("Removing " + Id + " from " + col);
                await global.webSocketClient.DeleteOne(col, Id);

                Id = null;
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
                Id = null;
            }
        }
示例#9
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var    WorkflowRuntime = new RuntimeDefinedParameter();
                string WorkflowName    = "";
                if (_staticStorage != null)
                {
                    _staticStorage.TryGetValue("Workflow", out WorkflowRuntime);
                    if (WorkflowRuntime.Value != null && !string.IsNullOrEmpty(WorkflowRuntime.Value.ToString()))
                    {
                        WorkflowName = WorkflowRuntime.Value.ToString();
                    }
                }
                var workflow = (_workflows == null ? null : _workflows.Where(x => x.name == WorkflowName).FirstOrDefault());
                if ((workflow == null || string.IsNullOrEmpty(WorkflowName)) && string.IsNullOrEmpty(TargetQueue))
                {
                    WriteError(new ErrorRecord(new Exception("Missing workflow name or workflow not found"), "", ErrorCategory.NotSpecified, null));
                    return;
                }
                if (workflow != null)
                {
                    TargetQueue = workflow.queue;
                }
                if (Object != null)
                {
                    json = Object.toJson();
                }
                if (string.IsNullOrEmpty(json))
                {
                    json = "{}";
                }
                await RegisterQueue();

                JObject tmpObject = JObject.Parse(json);
                correlationId = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", "");

                if (global.webSocketClient != null)
                {
                    global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage;
                }

                if (workflow != null)
                {
                    WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflow.name));
                }
                if (workflow == null)
                {
                    WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + TargetQueue));
                }
                var result = await global.webSocketClient.QueueMessage(TargetQueue, tmpObject, psqueue, correlationId);

                workItemsWaiting.WaitOne();
                WriteProgress(new ProgressRecord(0, "Invoking", "completed")
                {
                    RecordType = ProgressRecordType.Completed
                });

                JObject payload = msg;
                if (msg.ContainsKey("payload"))
                {
                    payload = msg.Value <JObject>("payload");
                }
                if (state == "failed")
                {
                    var message = "Invoke OpenFlow Workflow failed";
                    if (msg.ContainsKey("error"))
                    {
                        message = msg["error"].ToString();
                    }
                    if (msg.ContainsKey("_error"))
                    {
                        message = msg["_error"].ToString();
                    }
                    if (payload.ContainsKey("error"))
                    {
                        message = payload["error"].ToString();
                    }
                    if (payload.ContainsKey("_error"))
                    {
                        message = payload["_error"].ToString();
                    }
                    if (string.IsNullOrEmpty(message))
                    {
                        message = "Invoke OpenFlow Workflow failed";
                    }
                    WriteError(new ErrorRecord(new Exception(message), "", ErrorCategory.NotSpecified, null));
                    return;
                }
                if (payload != null)
                {
                    var _result = payload.toPSObject();
                    WriteObject(_result);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
                WriteProgress(new ProgressRecord(0, "Invoking", "completed")
                {
                    RecordType = ProgressRecordType.Completed
                });
            }
        }
示例#10
0
        public object GetDynamicParameters()
        {
            try
            {
                callcount++;
                if (_Collections == null)
                {
                    Initialize().Wait(5000);
                }
                if (global.webSocketClient == null || !global.webSocketClient.isConnected || global.webSocketClient.user == null)
                {
                    return(new RuntimeDefinedParameterDictionary());
                }
                RuntimeDefinedParameter targetnameparameter   = null;
                RuntimeDefinedParameter workflownameparameter = null;
                if (_robots == null)
                {
                    WriteStatus("Getting possible robots and roles");
                    _robots = global.webSocketClient.Query <apiuser>("users", "{\"$or\":[ {\"_type\": \"user\"}, {\"_type\": \"role\", \"rparole\": true} ]}", top: 2000).Result;
                }
                var TargetName = this.GetUnboundValue <string>("TargetName");
                if (_staticStorage != null)
                {
                    _staticStorage.TryGetValue("TargetName", out targetnameparameter);
                    _staticStorage.TryGetValue("WorkflowName", out workflownameparameter);
                    //WriteStatus(2, "targetname: " + targetnameparameter.Value + " workflowname: " + workflownameparameter.Value + " test: " + TargetName + "    ");
                    //WriteStatus(1, "targetname: " + targetnameparameter.IsSet + " workflowname: " + workflownameparameter.IsSet + "     ");
                }
                else
                {
                    var robotnames     = _robots.Select(x => x.name).ToArray();
                    var targetnameattr = new Collection <Attribute>()
                    {
                        new ParameterAttribute()
                        {
                            HelpMessage = "Targer username or group name",
                            Position    = 1
                        },
                        new ValidateSetAttribute(robotnames)
                    };
                    targetnameparameter = new RuntimeDefinedParameter("TargetName", typeof(string), targetnameattr);
                    var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary();
                    runtimeDefinedParameterDictionary.Add("TargetName", targetnameparameter);
                    _staticStorage = runtimeDefinedParameterDictionary;
                }

                apiuser robot    = null;
                string  targetid = TargetId;

                if (targetnameparameter.Value != null)
                {
                    TargetName = targetnameparameter.Value.ToString();
                }
                if (!string.IsNullOrEmpty(TargetName))
                {
                    robot = _robots.Where(x => x.name == TargetName).FirstOrDefault();
                    if (robot != null)
                    {
                        targetid = robot._id;
                    }
                }
                else if (!string.IsNullOrEmpty(targetid))
                {
                    robot = _robots.Where(x => x._id == targetid).FirstOrDefault();
                }

                if ((_workflows == null || lasttargetid != targetid) && robot != null)
                {
                    WriteStatus("Getting possible workflows for " + robot.name);
                    _workflows   = global.webSocketClient.Query <workflow>("openrpa", "{_type: 'workflow'}", projection: "{\"projectandname\": 1}", queryas: targetid, top: 2000).Result;
                    lasttargetid = targetid;
                }
                int wflen = 0;
                if (_workflows != null)
                {
                    wflen = _workflows.Length;
                }
                if (robot != null)
                {
                    WriteStatus("(" + callcount + ") robots: " + _robots.Length + " workflows: " + wflen + " for " + robot.name);
                }
                else
                {
                    WriteStatus("(" + callcount + ") robots: " + _robots.Length + " workflows: " + wflen);
                }

                if (workflownameparameter == null)
                {
                    var workflownameattr = new Collection <Attribute>()
                    {
                        new ParameterAttribute()
                        {
                            HelpMessage = "Workflow name",
                            Position    = 2
                        }
                    };
                    workflownameparameter = new RuntimeDefinedParameter("WorkflowName", typeof(string), workflownameattr);
                    _staticStorage.Add("WorkflowName", workflownameparameter);
                }
                if (workflownameparameter != null)
                {
                    ValidateSetAttribute wfname = (ValidateSetAttribute)workflownameparameter.Attributes.Where(x => x.GetType() == typeof(ValidateSetAttribute)).FirstOrDefault();
                    if (wfname != null)
                    {
                        workflownameparameter.Attributes.Remove(wfname);
                    }
                    if (_workflows != null && _workflows.Length > 0)
                    {
                        var workflownames = _workflows.Select(x => x.ProjectAndName).ToArray();
                        wfname = new ValidateSetAttribute(workflownames);
                        workflownameparameter.Attributes.Add(wfname);
                    }
                }
                return(_staticStorage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine(ex.Message);
                throw;
            }
        }
示例#11
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var CollectionRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Collection", out CollectionRuntime);
                string Collection = "entities";
                if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString()))
                {
                    Collection = CollectionRuntime.Value.ToString();
                }
                // if (Top == 0) Top = 100;

                JObject q    = null;
                string  json = "";
                try
                {
                    q    = JObject.Parse(Query);
                    json = q.ToString();
                }
                catch (Exception)
                {
                }
                if (string.IsNullOrEmpty(json) && Query != null)
                {
                    Query = Query.Trim();
                    if (!Query.StartsWith("{") && !Query.EndsWith("}"))
                    {
                        Query = "{" + Query + "}";
                    }
                    q    = JObject.Parse(Query);
                    json = q.ToString();
                }
                if (!string.IsNullOrEmpty(Type))
                {
                    if (q == null)
                    {
                        q = JObject.Parse("{}");
                    }
                    q["_type"] = Type;
                    json       = q.ToString();
                }
                var entities = await global.webSocketClient.Query <JObject>(Collection, json, Projection, Top, Skip, Orderby, QueryAs);

                // var results = new List<PSObject>();
                int index = 0;
                foreach (var entity in entities)
                {
                    if (entity.ContainsKey("name"))
                    {
                        WriteVerbose("Parsing " + entity.Value <string>("_id") + " " + entity.Value <string>("name"));
                    }
                    else
                    {
                        WriteVerbose("Parsing " + entity.Value <string>("_id"));
                    }
                    entity["__pscollection"] = Collection;
                    var obj = entity.toPSObject();
                    //var display = new PSPropertySet("DefaultDisplayPropertySet", new[] { "name", "_type", "_createdby", "_created" });
                    //var mi = new PSMemberSet("PSStandardMembers", new[] { display });
                    //obj.Members.Add(mi);
                    obj.TypeNames.Insert(0, "OpenRPA.PS.Entity");
                    if (Collection == "openrpa")
                    {
                        if (entity.Value <string>("_type") == "workflow")
                        {
                            obj.TypeNames.Insert(0, "OpenRPA.Workflow");
                        }
                        if (entity.Value <string>("_type") == "project")
                        {
                            obj.TypeNames.Insert(0, "OpenRPA.Project");
                        }
                        if (entity.Value <string>("_type") == "detector")
                        {
                            obj.TypeNames.Insert(0, "OpenRPA.Detector");
                        }
                        if (entity.Value <string>("_type") == "unattendedclient")
                        {
                            obj.TypeNames.Insert(0, "OpenRPA.UnattendedClient");
                        }
                        if (entity.Value <string>("_type") == "unattendedserver")
                        {
                            obj.TypeNames.Insert(0, "OpenRPA.UnattendedServer");
                        }
                    }
                    else if (Collection == "files")
                    {
                        obj.TypeNames.Insert(0, "OpenRPA.File");
                    }
                    // results.Add(obj);
                    WriteObject(obj);
                    index++;
                    if (index % 10 == 9)
                    {
                        await Task.Delay(1);
                    }
                }
                // WriteObject(results, true);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
            }
        }
示例#12
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var CollectionRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Collection", out CollectionRuntime);
                string Collection = "";
                if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString()))
                {
                    Collection = CollectionRuntime.Value.ToString();
                }
                JObject obj = null;
                if (Object != null)
                {
                    json = Object.toJson();
                }
                JObject tmpObject = JObject.Parse(json);
                string  col       = Collection;
                if (string.IsNullOrEmpty(col)) // If not overwriten by param, then check for old collection
                {
                    if (tmpObject.ContainsKey("__pscollection"))
                    {
                        col = tmpObject.Value <string>("__pscollection");
                        tmpObject.Remove("__pscollection");
                    }
                    else
                    {
                        col = "entities";
                    }
                }
                else
                {
                    if (tmpObject.ContainsKey("__pscollection"))
                    {
                        tmpObject.Remove("__pscollection");
                    }
                }
                if (!string.IsNullOrEmpty(Type))
                {
                    tmpObject["_type"] = Type;
                }
                if (!SkipLowercaseName.IsPresent)
                {
                    bool loopAgain = true;
                    while (loopAgain)
                    {
                        loopAgain = false;
                        foreach (var v in tmpObject)
                        {
                            if (v.Key.ToLower() == "name" && v.Key != "name")
                            {
                                tmpObject["name"] = tmpObject[v.Key];
                                tmpObject.Remove(v.Key);
                                loopAgain = true;
                                break;
                            }
                        }
                    }
                }
                if (MyInvocation.InvocationName == "Add-Entity")
                {
                    if (tmpObject.ContainsKey("_id"))
                    {
                        tmpObject.Remove("_id");
                    }
                }

                if (UniqueKeys != null && UniqueKeys.Length > 0)
                {
                    string uniqeness = string.Join(",", UniqueKeys);
                    obj = await global.webSocketClient.InsertOrUpdateOne(col, 1, false, uniqeness, tmpObject);
                }
                else
                {
                    if (tmpObject.ContainsKey("_id"))
                    {
                        obj = await global.webSocketClient.UpdateOne(col, 1, false, tmpObject);
                    }
                    else
                    {
                        if (MyInvocation.InvocationName == "Add-Entity")
                        {
                            obj = await global.webSocketClient.InsertOne(col, 1, false, tmpObject);
                        }
                        else
                        {
                            WriteError(new ErrorRecord(new Exception("Missing _id and UniqueKeys, either use Add-Entity or set UniqueKeys"), "", ErrorCategory.NotSpecified, null));
                            return;
                        }
                    }
                }
                var _obj = obj.toPSObject();
                _obj.TypeNames.Insert(0, "OpenRPA.PS.Entity");
                if (Collection == "openrpa")
                {
                    if (obj.Value <string>("_type") == "workflow")
                    {
                        _obj.TypeNames.Insert(0, "OpenRPA.Workflow");
                    }
                    if (obj.Value <string>("_type") == "project")
                    {
                        _obj.TypeNames.Insert(0, "OpenRPA.Project");
                    }
                    if (obj.Value <string>("_type") == "detector")
                    {
                        _obj.TypeNames.Insert(0, "OpenRPA.Detector");
                    }
                    if (obj.Value <string>("_type") == "unattendedclient")
                    {
                        _obj.TypeNames.Insert(0, "OpenRPA.UnattendedClient");
                    }
                    if (obj.Value <string>("_type") == "unattendedserver")
                    {
                        _obj.TypeNames.Insert(0, "OpenRPA.UnattendedServer");
                    }
                }
                WriteObject(_obj);
                await Task.Delay(1);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
            }
        }
示例#13
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var CollectionRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Collection", out CollectionRuntime);
                string Collection = "";
                if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString()))
                {
                    Collection = CollectionRuntime.Value.ToString();
                }
                if (string.IsNullOrEmpty(Collection))
                {
                    Collection = "entities";
                }

                // If not using UniqueKeys and we are trying to ADD multiple new items, use add many for better performance.
                if (Objects != null && Objects.Count > 1 && MyInvocation.InvocationName == "Add-Entity" && (UniqueKeys == null || UniqueKeys.Length == 0))
                {
                    var colls = new Dictionary <string, List <JObject> >();
                    var col   = Collection;
                    foreach (PSObject obj in Objects)
                    {
                        var     json      = obj.toJson();
                        JObject tmpObject = JObject.Parse(json);
                        col = Collection;
                        if (tmpObject.ContainsKey("__pscollection") && tmpObject["__pscollection"] != null)
                        {
                            col = tmpObject.Value <string>("__pscollection");
                            tmpObject.Remove("__pscollection");
                        }
                        if (!colls.ContainsKey(col))
                        {
                            colls.Add(col, new List <JObject>());
                        }
                        colls[col].Add(tmpObject);
                    }
                    if (BatchSize <= 0)
                    {
                        BatchSize = 15;
                    }
                    if (BatchSize < 2)
                    {
                        BatchSize = 2;
                    }
                    foreach (var kv in colls)
                    {
                        var total = kv.Value.Count;
                        for (var i = 0; i < total; i = i + BatchSize)
                        {
                            if (Stopping)
                            {
                                break;
                            }
                            var count = BatchSize;
                            if ((i + count) > total)
                            {
                                count = total - i;
                            }
                            var items        = kv.Value.GetRange(i, count).ToArray();
                            var affectedrows = await global.webSocketClient.InsertMany(kv.Key, 1, false, SkipResults.IsPresent, items);

                            WriteVerbose("Added " + (i + count) + " rows out of " + total + " to collection " + col);
                            foreach (var obj in affectedrows)
                            {
                                var _obj = obj.toPSObject();
                                _obj.TypeNames.Insert(0, "OpenRPA.PS.Entity");
                                if (Collection == "openrpa")
                                {
                                    if (obj.Value <string>("_type") == "workflow")
                                    {
                                        _obj.TypeNames.Insert(0, "OpenRPA.Workflow");
                                    }
                                    if (obj.Value <string>("_type") == "project")
                                    {
                                        _obj.TypeNames.Insert(0, "OpenRPA.Project");
                                    }
                                    if (obj.Value <string>("_type") == "detector")
                                    {
                                        _obj.TypeNames.Insert(0, "OpenRPA.Detector");
                                    }
                                    if (obj.Value <string>("_type") == "unattendedclient")
                                    {
                                        _obj.TypeNames.Insert(0, "OpenRPA.UnattendedClient");
                                    }
                                    if (obj.Value <string>("_type") == "unattendedserver")
                                    {
                                        _obj.TypeNames.Insert(0, "OpenRPA.UnattendedServer");
                                    }
                                }
                                WriteObject(_obj);
                            }
                        }
                    }
                    return;
                }
                else
                {
                    var PSObjects = new List <PSObject>();
                    if (Objects == null || Objects.Count == 0)
                    {
                        PSObjects.Add(json.JsonToPSObject());
                    }
                    else
                    {
                        foreach (var obj in Objects)
                        {
                            PSObjects.Add(JObject.FromObject(obj, new JsonSerializer()
                            {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }).ToString().JsonToPSObject());
                        }
                    }
                    foreach (PSObject Object in PSObjects)
                    {
                        JObject obj = null;
                        if (Object != null)
                        {
                            json = Object.toJson();
                        }
                        JObject tmpObject = JObject.Parse(json);
                        string  col       = Collection;
                        if (string.IsNullOrEmpty(col)) // If not overwriten by param, then check for old collection
                        {
                            if (tmpObject.ContainsKey("__pscollection"))
                            {
                                col = tmpObject.Value <string>("__pscollection");
                                tmpObject.Remove("__pscollection");
                            }
                            else
                            {
                                col = "entities";
                            }
                        }
                        else
                        {
                            if (tmpObject.ContainsKey("__pscollection"))
                            {
                                tmpObject.Remove("__pscollection");
                            }
                        }
                        if (!string.IsNullOrEmpty(Type))
                        {
                            tmpObject["_type"] = Type;
                        }
                        if (!SkipLowercaseName.IsPresent)
                        {
                            bool loopAgain = true;
                            while (loopAgain)
                            {
                                loopAgain = false;
                                foreach (var v in tmpObject)
                                {
                                    if (v.Key.ToLower() == "name" && v.Key != "name")
                                    {
                                        tmpObject["name"] = tmpObject[v.Key];
                                        tmpObject.Remove(v.Key);
                                        loopAgain = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (MyInvocation.InvocationName == "Add-Entity")
                        {
                            if (tmpObject.ContainsKey("_id"))
                            {
                                tmpObject.Remove("_id");
                            }
                        }

                        if (UniqueKeys != null && UniqueKeys.Length > 0)
                        {
                            string uniqeness = string.Join(",", UniqueKeys);
                            obj = await global.webSocketClient.InsertOrUpdateOne(col, 1, false, uniqeness, tmpObject);
                        }
                        else
                        {
                            if (tmpObject.ContainsKey("_id"))
                            {
                                obj = await global.webSocketClient.UpdateOne(col, 1, false, tmpObject);
                            }
                            else
                            {
                                if (MyInvocation.InvocationName == "Add-Entity")
                                {
                                    obj = await global.webSocketClient.InsertOne(col, 1, false, tmpObject);
                                }
                                else
                                {
                                    WriteError(new ErrorRecord(new Exception("Missing _id and UniqueKeys, either use Add-Entity or set UniqueKeys"), "", ErrorCategory.NotSpecified, null));
                                    return;
                                }
                            }
                        }
                        var _obj = obj.toPSObject();
                        _obj.TypeNames.Insert(0, "OpenRPA.PS.Entity");
                        if (Collection == "openrpa")
                        {
                            if (obj.Value <string>("_type") == "workflow")
                            {
                                _obj.TypeNames.Insert(0, "OpenRPA.Workflow");
                            }
                            if (obj.Value <string>("_type") == "project")
                            {
                                _obj.TypeNames.Insert(0, "OpenRPA.Project");
                            }
                            if (obj.Value <string>("_type") == "detector")
                            {
                                _obj.TypeNames.Insert(0, "OpenRPA.Detector");
                            }
                            if (obj.Value <string>("_type") == "unattendedclient")
                            {
                                _obj.TypeNames.Insert(0, "OpenRPA.UnattendedClient");
                            }
                            if (obj.Value <string>("_type") == "unattendedserver")
                            {
                                _obj.TypeNames.Insert(0, "OpenRPA.UnattendedServer");
                            }
                        }
                        WriteObject(_obj);
                        await Task.Delay(1);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
            }
        }
示例#14
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var CollectionRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Collection", out CollectionRuntime);
                string Collection = "entities";
                if (CollectionRuntime.Value != null && !string.IsNullOrEmpty(CollectionRuntime.Value.ToString()))
                {
                    Collection = CollectionRuntime.Value.ToString();
                }
                // if (Top == 0) Top = 100;

                JObject q    = null;
                string  json = "";
                try
                {
                    q    = JObject.Parse(Query);
                    json = q.ToString();
                }
                catch (Exception)
                {
                }
                if (string.IsNullOrEmpty(json) && Query != null)
                {
                    Query = Query.Trim();
                    if (!Query.StartsWith("{") && !Query.EndsWith("}"))
                    {
                        Query = "{" + Query + "}";
                    }
                    q    = JObject.Parse(Query);
                    json = q.ToString();
                }
                if (!string.IsNullOrEmpty(Type))
                {
                    if (q == null)
                    {
                        q = JObject.Parse("{}");
                    }
                    q["_type"] = Type;
                    json       = q.ToString();
                }
                var entities = await global.webSocketClient.Query <JObject>(Collection, json, Projection, Top, Skip, Orderby, QueryAs);

                // var results = new List<PSObject>();
                int index = 0;
                foreach (var entity in entities)
                {
                    if (entity.ContainsKey("name"))
                    {
                        WriteVerbose("Parsing " + entity.Value <string>("_id") + " " + entity.Value <string>("name"));
                    }
                    else
                    {
                        WriteVerbose("Parsing " + entity.Value <string>("_id"));
                    }
                    // results.Add(obj);
                    WriteObject(entity.toPSObjectWithTypeName(Collection));
                    index++;
                    if (index % 10 == 9)
                    {
                        await Task.Delay(1);
                    }
                }
                // WriteObject(results, true);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
            }
        }