Exemplo n.º 1
0
        private void ExecuteInitialize()
        {
            object oldValue = null;

            if (_Exists)
            {
                oldValue = _Config.Value;
            }
            else
            {
                _Config = new Config();
            }

            _Config.Name   = _NameName;
            _Config.Module = _NameModule;
            _Config.Value  = Value;

            ApplyCommonSettings();

            _Config.Initialized = true;
            ConfigurationHost.Configurations[_NameFull] = _Config;

            if (_Exists)
            {
                try { ApplyValue(oldValue); }
                catch (Exception e)
                {
                    InvokeCommand.InvokeScript(true, ScriptBlock.Create(String.Format(_updateError, _NameFull, EnableException.ToBool())), null, e);
                    _KillIt = true;
                    return;
                }
            }
        }
Exemplo n.º 2
0
 public void Handle(NetClient netclient, InvokeCommand cmd)
 {
     netclient.WriteServiceData(new InvokeResult {
         Success = true,
         Data    = _keyLocker.GetLockedKeys()
     });
 }
        /// <summary>
        /// For each record, execute it, and push the results into the success stream.
        /// </summary>
        protected override void ProcessRecord()
        {
            Diagnostics.Assert(Command != null, "Command is null");

            ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command);

            // If the runspace has ever been in ConstrainedLanguage, lock down this
            // invocation as well - it is too easy for the command to be negatively influenced
            // by malicious input (such as ReadOnly + Constant variables)
            if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
            {
                myScriptBlock.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            var emptyArray = Array.Empty <object>();

            myScriptBlock.InvokeUsingCmdlet(
                contextCmdlet: this,
                useLocalScope: false,
                errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                dollarUnder: AutomationNull.Value,
                input: emptyArray,
                scriptThis: AutomationNull.Value,
                args: emptyArray);
        }
        public void ExecutePSScriptInternal(string path)
        {
            try
            {
                if (path != null)
                {
                    string command = "& " + PathUtility.EscapePSPath(path) + " $__rootPath $__toolsPath $__package $__project";
                    LogCore(MessageLevel.Info, String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_ExecutingScript, path));

                    InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);
                }

                // clear temp variables
                SessionState.PSVariable.Remove("__rootPath");
                SessionState.PSVariable.Remove("__toolsPath");
                SessionState.PSVariable.Remove("__package");
                SessionState.PSVariable.Remove("__project");
            }
            catch (Exception ex)
            {
                _scriptException = ex;
            }
            finally
            {
                ScriptEndSemaphore.Release();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Processes the specified exception specified
        /// </summary>
        /// <param name="Item">The exception to process</param>
        /// <returns>The transformed exception</returns>
        private Exception ResolveException(Exception Item)
        {
            if (Item == null)
            {
                return(Item);
            }

            string lowTypeName = Item.GetType().FullName.ToLower();

            if (MessageHost.ExceptionTransforms.ContainsKey(lowTypeName))
            {
                try { return((Exception)InvokeCommand.InvokeScript(false, ScriptBlock.Create(MessageHost.ExceptionTransforms[lowTypeName].ToString()), null, Item)[0].BaseObject); }
                catch (Exception e)
                {
                    MessageHost.WriteTransformError(new ErrorRecord(e, "Write-PSFMessage", ErrorCategory.OperationStopped, null), FunctionName, ModuleName, Item, TransformType.Exception, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId);
                    return(Item);
                }
            }

            TransformCondition transform = MessageHost.ExceptionTransformList.Get(lowTypeName, ModuleName, FunctionName);

            if (transform != null)
            {
                try { return((Exception)InvokeCommand.InvokeScript(false, ScriptBlock.Create(transform.ScriptBlock.ToString()), null, Item)[0].BaseObject); }
                catch (Exception e)
                {
                    MessageHost.WriteTransformError(new ErrorRecord(e, "Write-PSFMessage", ErrorCategory.OperationStopped, null), FunctionName, ModuleName, Item, TransformType.Exception, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId);
                    return(Item);
                }
            }

            return(Item);
        }
Exemplo n.º 6
0
        string GetHtml()
        {
            List <PSObject> inputs = null;
            string          html   = null;

            foreach (PSObject data in _data.Take(15))
            {
                var a = data.ToString();
                if (a.Contains("<html"))
                {
                    inputs = _data;
                    break;
                }
            }

            if (null == inputs)
            {
                inputs = new List <PSObject>(
                    InvokeCommand.InvokeScript(
                        "$input | convertto-html",
                        true,
                        PipelineResultTypes.None,
                        _data)
                    );
            }

            var sb = new StringBuilder();

            inputs.ToList().ForEach(i => sb.Append(i.ToString()));
            html = sb.ToString();

            return(html);
        }
Exemplo n.º 7
0
        private void DrainCommands()
        {
            logger.Debug("DrainCommands()");

            if (sendCommand != null)
            {
                sendCommand.SetResult(null, null);
                sendCommand = null;

                //sendCommand.Dispose();
                //sendCommand = null;
            }

            while (commandQueue.Count > 0)
            {
                TryGetCommand(out var command);

                if (command != null)
                {
                    command.SetResult(null, null);

                    //command.Dispose();
                    //command = null;
                }
            }
        }
Exemplo n.º 8
0
        private void QuitarTablaDetalle()
        {
            if (metroGrid1.SelectedRows.Count > 0)
            {
                try
                {
                    int id_prod = GetIdProdEnGridDetalle();
                    IReadOnlyList <Entities.Producto> detalleToRemove = bingindList.Where(x => (x.id == id_prod)).ToList();

                    foreach (var d in detalleToRemove)
                    {
                        total -= d.precio * d.cantidad;
                        bingindList.Remove(d);
                        listProd.Remove(d);
                    }
                }
                catch (Exception ex)
                {
                    InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Error, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Error carga de datos", ex.StackTrace, ex.Message));
                    Notifications.FrmError.ErrorForm(Language.SearchValue("errorBuscarDatos") + "\n" + ex.Message);
                }
            }
            else
            {
                Notifications.FrmInformation.InformationForm(Helps.Language.SearchValue("infoSelecEliminar"));
            }
        }
Exemplo n.º 9
0
        protected override void ProcessRecord()
        {
            try
            {
                if (String.IsNullOrEmpty(AppId))
                {
                    AppId = InputHelper.GetUserInput(this, "AppId");
                }
                if (String.IsNullOrEmpty(SecretKey))
                {
                    SecretKey = InputHelper.GetUserInput(this, "SecretKey");
                }
                if (String.IsNullOrEmpty(AccountId))
                {
                    AccountId = InputHelper.GetUserInput(this, "AccountId");
                }
                if (String.IsNullOrEmpty(From))
                {
                    From = InputHelper.GetUserInput(this, "From");
                }
                if (String.IsNullOrEmpty(To))
                {
                    To = InputHelper.GetUserInput(this, "To");
                }

                Latch latch = new Latch(AppId, SecretKey);
                WriteObject(latch.History(AccountId, DateTime.Parse(From), DateTime.Parse(To)), true);
            }
            catch (Exception ex)
            {
                InvokeCommand.InvokeScript(String.Format("Write-Host Error: \"{0}\"", ex.Message));
            }
        }
Exemplo n.º 10
0
        protected override void ProcessRecord()
        {
            try
            {
                if (String.IsNullOrEmpty(AppId))
                {
                    AppId = InputHelper.GetUserInput(this, "AppId");
                }
                if (String.IsNullOrEmpty(SecretKey))
                {
                    SecretKey = InputHelper.GetUserInput(this, "SecretKey");
                }
                if (String.IsNullOrEmpty(Token))
                {
                    Token = InputHelper.GetUserInput(this, "Token");
                }

                Latch latch = new Latch(AppId, SecretKey);
                WriteObject(latch.Pair(Token), true);
            }
            catch (Exception ex)
            {
                InvokeCommand.InvokeScript(String.Format("Write-Host Error: \"{0}\"", ex.Message));
            }
        }
Exemplo n.º 11
0
        private void WriteDiagnostic()
        {
            if (PrtgSessionState.Client == null)
            {
                throw new InvalidOperationException("You are not connected to a PRTG Server. Please connect first using Connect-PrtgServer.");
            }

            var versionTable = (Hashtable)GetVariableValue("PSVersionTable");

            var asmPath = typeof(PSCmdlet).Assembly.Location;
            var version = FileVersionInfo.GetVersionInfo(asmPath).ProductVersion;

            var dict = new Dictionary <string, string>
            {
                ["PSVersion"]      = versionTable["PSVersion"].ToString(),
                ["PSEdition"]      = versionTable["PSEdition"].ToString(),
                ["OS"]             = GetOS(versionTable),
                ["PrtgAPIVersion"] = ValueOrUnknown(InvokeCommand.InvokeScript("(Get-Module PrtgAPI).Version")),
                ["Culture"]        = CultureInfo.CurrentCulture.ToString(),
                ["CLRVersion"]     = GetCLRVersion(),

                ["PrtgVersion"]  = PrtgSessionState.Client.Version.ToString(),
                ["PrtgLanguage"] = PrtgLanguageOrUnknown()
            };

            var obj = new PSObject();

            foreach (var item in dict)
            {
                obj.Properties.Add(new PSNoteProperty(item.Key, item.Value));
            }

            WriteObject(obj);
        }
Exemplo n.º 12
0
 public void Handle(NetClient netclient, InvokeCommand cmd)
 {
     _keyLocker.UnLockAnyway(cmd.Method);
     netclient.WriteServiceData(new InvokeResult {
         Success = true
     });
 }
        private void btnQuitar_Click(object sender, EventArgs e)
        {
            if (metroGrid1.SelectedRows.Count > 0)
            {
                try
                {
                    Patente patente = BLL.UFP.Patente.GetAdapted(GetId());
                    familia.Remove(patente);

                    IReadOnlyList <FamiliaElement> ToRemove = bind.Where(x => (x.IdFamiliaElement == patente.IdFamiliaElement)).ToList();

                    foreach (var d in ToRemove)
                    {
                        bind.Remove(d);
                    }
                }
                catch (Exception ex)
                {
                    InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Error, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Error carga de datos", ex.StackTrace, ex.Message));
                    Notifications.FrmError.ErrorForm(Language.SearchValue("errorBuscarDatos") + "\n" + ex.Message);
                }
            }
            else
            {
                Notifications.FrmInformation.InformationForm(Helps.Language.SearchValue("infoSelecEditar"));
            }
        }
Exemplo n.º 14
0
        private void BtnEliminar_Click(object sender, EventArgs e)
        {
            if (metroGrid1.SelectedRows.Count > 0)
            {
                Entities.UFP.Familia familia = BLL.UFP.Familia.GetAdapted(GetId());
                try
                {
                    DialogResult confirmation = new Notifications.FrmQuestion(Helps.Language.SearchValue("preguntaEliminar")).ShowDialog();

                    if (confirmation == DialogResult.OK)
                    {
                        BLL.UFP.Familia.Delete(familia);

                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Delete, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Familia: " + familia.Nombre, "", ""));

                        RefrescarTabla();
                        Notifications.FrmSuccess.SuccessForm(Helps.Language.SearchValue("eliminadoOK"));
                    }
                }
                catch (Exception ex)
                {
                    InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.DeleteError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Familia: " + familia.Nombre, ex.StackTrace, ex.Message));
                    RefrescarTabla();
                    Notifications.FrmError.ErrorForm(Helps.Language.SearchValue("eliminadoError") + "\n" + ex.Message);
                }
                RefrescarTabla();
            }
            else
            {
                Notifications.FrmInformation.InformationForm(Helps.Language.SearchValue("infoSelecEliminar"));
            }
        }
Exemplo n.º 15
0
        public void Handle(NetClient netclient, InvokeCommand cmd)
        {
            //System.Diagnostics.Debugger.Launch();
            if (!IsDebug)
            {
                netclient.WriteServiceData(new InvokeResult()
                {
                    Data    = "not support in release",
                    Success = false
                });
                return;
            }
            string code = null;
            bool   success;

            try
            {
                code    = _codeBuilder.GenerateCode(cmd.Parameters[0], cmd.Parameters[1], cmd.Service);
                success = true;
            }
            catch (Exception ex)
            {
                code    = ex.ToString();
                success = false;
            }
            netclient.WriteServiceData(new InvokeResult()
            {
                Data    = code,
                Success = success
            });
        }
Exemplo n.º 16
0
        private void BtnAnular_Click(object sender, EventArgs e)
        {
            if (metroGrid1.SelectedRows.Count > 0)
            {
                int?idEntity = GetId();

                Entities.Doc_cabecera_egreso entity = bllCabecera.GetById(Convert.ToInt32(idEntity));
                entity.listDetalle = bllDetalle.ListDetallesByCabecera(entity.id);

                try
                {
                    DialogResult confirmation = new Notifications.FrmQuestion(Helps.Language.SearchValue("preguntaEliminar")).ShowDialog();

                    if (confirmation == DialogResult.OK)
                    {
                        bllCabecera.Anular(entity);
                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Delete, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Ingreso anulado: " + entity.factura, "", ""));

                        RefrescarTabla();
                        Notifications.FrmSuccess.SuccessForm(Helps.Language.SearchValue("eliminadoOK"));
                    }
                }
                catch (Exception ex)
                {
                    InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.DeleteError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Ingreso anulado: " + entity.factura, ex.StackTrace, ex.Message));
                    RefrescarTabla();
                    Notifications.FrmError.ErrorForm(Helps.Language.SearchValue("eliminadoError") + "\n" + ex.Message);
                }
                RefrescarTabla();
            }
            else
            {
                Notifications.FrmInformation.InformationForm(Helps.Language.info["infoSelecEliminar"]);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Processes key press.
        /// </summary>
        /// <param name="pressedKey">Pressed key.</param>
        /// <returns>True if the event was handled, false otherwise.</returns>
        public bool ProcessKeyPress(InputKey pressedKey)
        {
            if (entries.ProcessKeyPress(pressedKey))
            {
                return(true);
            }

            if (pressedKey == 'l' || pressedKey == Keys.Left || pressedKey == Keys.Enter)
            {
                var parentDir = entries.EntryInFocus.GetType() == typeof(SearchResultDirectoryEntry) ?
                                entries.EntryInFocus.Info.FullName :
                                ((FileInfo)entries.EntryInFocus.Info).DirectoryName;

                Search.Cancel();

                InvokeCommand?.Invoke(new ChangeDirectoryCommand(parentDir));
                return(true);
            }

            if (pressedKey == Keys.Escape)
            {
                Search.Cancel();
                pane.Status = JobStatus.Canceled;

                return(false);
            }

            return(false);
        }
 private void RebuildTemplate(FeatureLayer flayer)
 {
     var templates = new List<TemplateItem>();
     FeatureServiceLayerInfo serviceInfo = null;
     var gdbFeatureTable = flayer.FeatureTable as ArcGISFeatureTable;
     if (gdbFeatureTable != null && !gdbFeatureTable.IsReadOnly && flayer.Status == LayerStatus.Initialized)
     {
         try
         {
             serviceInfo = gdbFeatureTable.ServiceInfo;
         }
         catch{}
     }
     if (serviceInfo != null)
     {
         var cmd = new InvokeCommand(OnItemClicked);
         var renderer = flayer.Renderer ?? (serviceInfo.DrawingInfo == null ? null : serviceInfo.DrawingInfo.Renderer);
         if (serviceInfo.Templates != null)
         {
             foreach (var template in serviceInfo.Templates)
             {
                 var item = new TemplateItem
                 {
                     Layer = flayer,
                     FeatureTemplate = template,
                     Command = cmd,
                 };
                 templates.Add(item);
                 if (renderer != null)
                 {
                     var g = new Graphic(template.Prototype.Attributes ?? Enumerable.Empty<System.Collections.Generic.KeyValuePair<string, object>>()); // Need to disambiguate from winstore toolkit KeyValuePair
                     item.SetSymbol(renderer.GetSymbol(g));
                 }
             }
         }
         if (serviceInfo.Types != null)
         {
             foreach (var type in serviceInfo.Types)
             {
                 foreach (var template in type.Templates)
                 {
                     var item = new TemplateItem
                     {
                         Layer = flayer,
                         FeatureType = type,
                         FeatureTemplate = template,
                         Command = cmd,
                     };
                     templates.Add(item);
                     if (renderer != null)
                     {
                         var g = new Graphic(template.Prototype.Attributes ?? Enumerable.Empty<System.Collections.Generic.KeyValuePair<string, object>>());
                         item.SetSymbol(renderer.GetSymbol(g));
                     }
                 }
             }
         }
     }
     _templatesByLayer[flayer] = templates;
 }
Exemplo n.º 19
0
        protected virtual void ExecuteScript(string rootPath, string scriptFileName, IPackage package, Project project)
        {
            string toolsPath = Path.Combine(rootPath, "tools");
            string fullPath  = Path.Combine(toolsPath, scriptFileName);

            if (File.Exists(fullPath))
            {
                var psVariable = SessionState.PSVariable;

                // set temp variables to pass to the script
                psVariable.Set("__rootPath", rootPath);
                psVariable.Set("__toolsPath", toolsPath);
                psVariable.Set("__package", package);
                psVariable.Set("__project", project);

                string command = "& '" + fullPath + "' $__rootPath $__toolsPath $__package $__project";
                WriteVerbose(String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath));
                InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Output | PipelineResultTypes.Error, null, null);

                // clear temp variables
                psVariable.Remove("__rootPath");
                psVariable.Remove("__toolsPath");
                psVariable.Remove("__package");
                psVariable.Remove("__project");
            }
        }
Exemplo n.º 20
0
        private void ExecuteUpdate()
        {
            if (_PolicyEnforced)
            {
                InvokeCommand.InvokeScript(String.Format(_updatePolicyForbids, _NameFull, EnableException.ToBool()));
                _KillIt = true;
                return;
            }
            ApplyCommonSettings();

            if (!MyInvocation.BoundParameters.ContainsKey("Value"))
            {
                return;
            }

            try {
                if (!Default)
                {
                    ApplyValue(Value);
                }
            }
            catch (Exception e)
            {
                InvokeCommand.InvokeScript(true, ScriptBlock.Create(String.Format(_updateError, _NameFull, EnableException.ToBool())), null, e);
                _KillIt = true;
                return;
            }
        }
Exemplo n.º 21
0
        private void btnQuitar_Click(object sender, EventArgs e)
        {
            if (metroGrid1.SelectedRows.Count > 0)
            {
                try
                {
                    string idARemover = GetId();
                    usuario.Permisos.RemoveAll(x => x.IdFamiliaElement == idARemover);

                    IReadOnlyList <Entities.UFP.FamiliaElement> ToRemove = bind.Where(x => (x.IdFamiliaElement == idARemover)).ToList();

                    foreach (var d in ToRemove)
                    {
                        bind.Remove(d);
                    }
                    MostrarPermisosEstructura();
                }
                catch (Exception ex)
                {
                    InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Error, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Error carga de datos", ex.StackTrace, ex.Message));
                    Notifications.FrmError.ErrorForm(Language.SearchValue("errorBuscarDatos") + "\n" + ex.Message);
                }
            }
            else
            {
                Notifications.FrmInformation.InformationForm(Helps.Language.SearchValue("infoSelecEditar"));
            }
        }
Exemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="transactionId">事务id</param>
        /// <param name="cmd">请求对象</param>
        /// <param name="userContent">身份信息对象</param>
        public string Build(string transactionId, InvokeCommand cmd, object userContent)
        {
            if (Directory.Exists(_microServiceHost.RetryCommitPath) == false)
            {
                Directory.CreateDirectory(_microServiceHost.RetryCommitPath);
            }

            Type userContentType = userContent?.GetType();

            if (userContent != null && userContent is System.Security.Claims.ClaimsPrincipal claimsPrincipal)
            {
                using (var ms = new System.IO.MemoryStream())
                {
                    claimsPrincipal.WriteTo(new System.IO.BinaryWriter(ms));
                    ms.Position = 0;
                    userContent = ms.ToArray();
                }
            }

            var filepath = $"{_microServiceHost.RetryCommitPath}/{transactionId}_{DateTime.Now.Ticks}.txt";

            File.WriteAllText(filepath, new RequestInfo
            {
                Cmd              = cmd,
                TransactionId    = transactionId,
                UserContentType  = userContent == null ? null : userContentType,
                UserContentValue = userContent?.ToJsonString()
            }.ToJsonString(), Encoding.UTF8);
            return(filepath);
        }
Exemplo n.º 23
0
        private void BtnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                BLL.UFP.Usuario.Update(usuario);

                InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Update, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Usuario: " + usuario.Nombre, "", ""));

                Notifications.FrmSuccess.SuccessForm(Helps.Language.SearchValue("editadoOK"));

                MostrarPermisosEstructura();
            }
            catch (Exception ex)
            {
                if (ex.Message == EValidaciones.existe)
                {
                    Notifications.FrmError.ErrorForm(Helps.Language.SearchValue("errorExiste"));
                }
                else
                {
                    InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.UpdateError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Usuario: " + usuario.Nombre, ex.StackTrace, ex.Message));
                    Notifications.FrmError.ErrorForm(Helps.Language.SearchValue("editadoError") + "\n" + ex.Message);
                }
            }
        }
Exemplo n.º 24
0
        private string RenderInputObjectsToText()
        {
            StringBuilder formattedOutput = new StringBuilder();

            // Format any other object type using out-string
            string cmd = String.Empty;

            if (_width.HasValue)
            {
                cmd = String.Format(CultureInfo.InvariantCulture, "$input | out-string -width {0}", _width.Value);
            }
            else
            {
                cmd = "$input | out-string";
            }

            Collection <PSObject> results = InvokeCommand.InvokeScript(cmd, false, PipelineResultTypes.None, _objects);

            foreach (PSObject obj in results)
            {
                string   text  = obj.ToString();
                string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                foreach (string line in lines)
                {
                    formattedOutput.AppendLine(line.TrimEnd(null));
                }
            }

            return(formattedOutput.ToString().TrimEnd(null));
        }
Exemplo n.º 25
0
        protected override void ProcessRecord()
        {
            // This lets us do just `Jump-Location -Initialize` to initialize everything in the profile script
            if (Initialize)
            {
                InvokeCommand.InvokeScript(@"
                    Register-EngineEvent -SourceIdentifier PowerShell.OnIdle -Action {
                        [Jump.Location.SetJumpLocationCommand]::UpdateTime($($(Get-Item -Path $(Get-Location))).PSPath)
                    }
                ");
                return;
            }

            if (Query == null)
            {
                Query = new string[] {};
            }

            // If last term is absolute path it's probably because of autocomplition
            // so and we can safely process it here.
            if (Query.Any() && Path.IsPathRooted(Query.Last()))
            {
                ChangeDirectory(Query.Last());
                return;
            }

            var best = Controller.FindBest(Query);

            if (best == null)
            {
                throw new LocationNotFoundException(Query.First());
            }

            ChangeDirectory(best.Path);
        }
Exemplo n.º 26
0
        protected override void ProcessRecord()
        {
            var setup    = SetupMock;
            var mockBody = CreateMock;

            Collection <PSObject> preCommandOutput = null;

            if (!string.IsNullOrWhiteSpace(setup))
            {
                preCommandOutput = InvokeCommand.NewScriptBlock(setup).Invoke(FunctionName, MockWith, ParameterFilter);
            }

            var sb = InvokeCommand.NewScriptBlock(mockBody);

            var method = sb.GetType()
                         .GetMethod("InvokeUsingCmdlet", BindingFlags.Instance | BindingFlags.NonPublic);

            var       emptyArray              = new object[0];
            var       automationNull          = new PSObject();
            const int writeToCurrentErrorPipe = 1;

            var input = ExpandInput(preCommandOutput);

            var @params = new object[]
            { this, false, writeToCurrentErrorPipe, automationNull, emptyArray, automationNull, new[] { input } };

            method.Invoke(sb, @params);
        }
        protected override void ProcessRecord()
        {
            // This lets us do just `Jump-Location` to initialize everything in the profile script
            if (Initialize)
            {
                InvokeCommand.InvokeScript(@"
                    [Jump.Location.JumpLocationCommand]::UpdateTime($($(Get-Item -Path $(Get-Location))).PSPath);
                ");
                return;
            }

            if (Query == null)
            {
                Query = new string[] {};
            }

            // If last term is absolute path it's probably because of autocomplition
            // so and we can safely process it here.
            if (Query.Any() && Path.IsPathRooted(Query.Last()))
            {
                ChangeDirectory(Query.Last());
                return;
            }

            var best = Controller.FindBest(Query);

            if (best == null)
            {
                throw new LocationNotFoundException(Query.First());
            }

            var fullPath = GetResultPath(best);

            ChangeDirectory(fullPath);
        }
        private void ConnectToGoPrtgServer(GoPrtgServer server)
        {
            if (client != null && client.Server == server.Server && client.UserName == server.UserName)
            {
                WriteColorOutput($"\nAlready connected to {server.Server} as {server.UserName}\n", ConsoleColor.Yellow);
            }
            else
            {
                var passhash = InvokeCommand.InvokeScript($"ConvertTo-SecureString {server.PassHash}").First().BaseObject as SecureString;

                var credential = new PSCredential(server.UserName, passhash);

                Connect(server.Server, credential);

                WriteColorOutput($"\nConnected to {server.Server} as {server.UserName}\n", ConsoleColor.Green);
            }

            if (LogLevel != null)
            {
                LogLevel level = PrtgAPI.LogLevel.None;

                foreach (var l in LogLevel)
                {
                    level |= l;
                }

                PrtgSessionState.Client.LogLevel = level;
            }
        }
Exemplo n.º 29
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            InvokeCommand.InvokeScript(@"Set-PSBreakpoint -Variable pwd -Mode Write -Action {
                [Jump.Location.JumpLocationCommand]::UpdateTime($($(Get-Item -Path $(Get-Location))).PSPath);
            }");
        }
Exemplo n.º 30
0
        /// <summary>
        /// guarda los cambios
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnGuardar_Click(object sender, EventArgs e)
        {
            Entities.Categoria categoria = new Entities.Categoria();
            categoria.categoria = TxtNombre.Text;

            var  validation = new Helps.DataValidations(categoria).Validate();
            bool valid      = validation.Item1;

            if (valid == true)
            {
                if (editarse == false)
                {
                    try
                    {
                        categoria = bll.Insert(categoria);

                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Insert, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Categoria: " + categoria.categoria, "", ""));

                        Notifications.FrmSuccess.SuccessForm(Language.SearchValue("guardadoOK"));
                        RefrescarTabla();
                        LimpiarTxt();
                    }
                    catch (Exception ex)
                    {
                        System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException;
                        erro = sqlException.Number;
                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.InsertError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Categoria: " + categoria.categoria, ex.StackTrace, ex.Message));
                        Notifications.FrmError.ErrorForm(Language.SearchValue("guardadoError") + "\n" + ex.Message);
                    }
                }
                if (editarse == true)
                {
                    try
                    {
                        categoria.id = id;

                        bll.Update(categoria);

                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.Update, 1, this.GetType().FullName, MethodInfo.GetCurrentMethod().Name, "Categoria: " + categoria.categoria, "", ""));

                        Notifications.FrmSuccess.SuccessForm(Language.SearchValue("editadoOK"));
                        RefrescarTabla();
                        LimpiarTxt();
                        editarse = false;
                    }
                    catch (Exception ex)
                    {
                        InvokeCommand.InsertLog().Execute(CreateLog.Clog(ETipoLog.UpdateError, 1, ex.TargetSite.DeclaringType.FullName, ex.TargetSite.Name, "Categoria: " + categoria.categoria, ex.StackTrace, ex.Message));
                        Notifications.FrmError.ErrorForm(Language.SearchValue("editadoError") + "\n" + ex.Message);
                    }
                }
            }
            else
            {
                string messageValid = validation.Item2;
                Notifications.FrmInformation.InformationForm(messageValid);
            }
        }
 private void RebuildTemplate(FeatureLayer flayer)
 {
     var templates = new List<TemplateItem>();
     FeatureServiceLayerInfo serviceInfo = null;
     var ft = flayer.FeatureTable;
     if (ft != null && !ft.IsReadOnly && flayer.Status == LayerStatus.Initialized)
     {
         try
         {
             serviceInfo = ft.ServiceInfo;
         }
         catch{}
     }
     if (serviceInfo != null)
     {
         var cmd = new InvokeCommand(OnItemClicked);
         var renderer = flayer.Renderer ?? (serviceInfo.DrawingInfo == null ? null : serviceInfo.DrawingInfo.Renderer);
         if (serviceInfo.Templates != null)
         {
             foreach (var template in serviceInfo.Templates)
             {
                 var item = new TemplateItem
                 {
                     Layer = flayer,
                     FeatureTemplate = template,
                     Command = cmd,
                 };
                 templates.Add(item);
                 if (renderer != null)
                 {
                     var g = new Graphic(template.Prototype.Attributes ?? Enumerable.Empty<System.Collections.Generic.KeyValuePair<string, object>>()); // Need to desambiguate from winstore toolkit KeyValuePair
                     item.SetSwatch(renderer.GetSymbol(g));
                 }
             }
         }
         if (serviceInfo.Types != null)
         {
             foreach (var type in serviceInfo.Types)
             {
                 foreach (var template in type.Templates)
                 {
                     var item = new TemplateItem
                     {
                         Layer = flayer,
                         FeatureType = type,
                         FeatureTemplate = template,
                         Command = cmd,
                     };
                     templates.Add(item);
                     if (renderer != null)
                     {
                         var g = new Graphic(template.Prototype.Attributes);
                         item.SetSwatch(renderer.GetSymbol(g));
                     }
                 }
             }
         }
     }
     _templatesByLayer[flayer] = templates;
 }