Beispiel #1
0
        public bool EmptyForm(ImageFile imgFile, int imageWidth, int imageHeight, string drawString)
        {
            //ImageFile imgFile = new ImageFile(imageFileName);
            ImageFile tempFile = new ImageFile(Path.GetTempPath() + "i" + DateTimeOffset.UtcNow.UtcTicks.ToString("x") + ".png");

            // example: convert -size 180x225 xc:white -fill 292990_01_Gallery.png -draw "circle 30,110 32,82" -fuzz 5% -trim CircleW.png
            callString = ImPath + ConvertCommand + " -size " + imageWidth + "x" + imageHeight +
                         " xc:white -fill " + Os.Escape(imgFile.FullName, EscapeMode.paramEsc) +
                         " -draw \"" + drawString + "\" -fuzz 50% -trim " + Os.Escape(tempFile.FullName, EscapeMode.paramEsc);
            call = new RaiSystem(callString);
            string msg = new string(' ', 200);;

            call.Exec(out msg);
            try
            {
                File.Delete(tempFile.FullName);
            }
            catch (Exception)
            {
            }
            if (msg.Contains("geometry does not contain image"))
            {
                return(true);
            }
            return(false);
        }
Beispiel #2
0
        private void DeleteDebugRepo()
        {
            string repoPath = Path.Combine(Environment.CurrentDirectory, "PitDebug");

            if (!Directory.Exists(repoPath))
            {
                Log.Error("Directory does not exist.");
                Environment.Exit(1);
            }

            Log.Info("Delete this directory?");
            Log.Blue(repoPath);
            Log.Blue("(Y/n)");
            string input = Console.ReadLine();

            string[] positive = { "y", "Y", "" };
            if (!positive.Contains(input))
            {
                Environment.Exit(0);
            }

            ProcessRunner runner = new ProcessRunner();

            string command = new Os().IsLinux()
                ? $"rm -rf {repoPath}"
                : $"Remove-Item -Recurse -Force {repoPath}";

            runner.RunWithDefault(command);

            Log.Green("Done.");
        }
Beispiel #3
0
        public bool ClickOnNodeAction(Diagram.Diagram diagram, DiagramView diagramView, Node node)
        {
            if (node.link.Trim() == "#csharp")  // OPEN SCRIPT node with link "script" is executed as script
            {
                String clipboard = Os.GetTextFormClipboard();

                try
                {
                    this.EvaluateAsync(diagram, diagramView, node, clipboard).Wait();
                }
                catch (System.AggregateException ae)
                {
                    ae.Handle(ex =>
                    {
                        Program.log.Write("Exception in embed csharp script: " + ex.Message);
                        return(true);
                    });
                }


                return(true);
            }

            return(false);
        }
Beispiel #4
0
 protected void WriteComment(string comment)
 {
     AddTabs(2);
     Os.Write(Begincomment, 0, Begincomment.Length);
     Write(comment);
     Os.Write(Endcomment, 0, Endcomment.Length);
 }
Beispiel #5
0
        static OsInfo()
        {
            var platform = Environment.OSVersion.Platform;

            switch (platform)
            {
            case PlatformID.Win32NT:
            {
                Os = Os.Windows;
                break;
            }

            case PlatformID.MacOSX:
            case PlatformID.Unix:
            {
                // Sometimes Mac OS reports itself as Unix
                if (Directory.Exists("/System/Library/CoreServices/") &&
                    (File.Exists("/System/Library/CoreServices/SystemVersion.plist") ||
                     File.Exists("/System/Library/CoreServices/ServerVersion.plist"))
                    )
                {
                    Os = Os.Osx;
                }
                else
                {
                    Os = Os.Linux;
                }
                break;
            }
            }
        }
Beispiel #6
0
 public void Bind(IOpeningCondition oc)
 {
     if (!Os.Contains(oc))
     {
         Os.Add(oc);
     }
 }
Beispiel #7
0
        public async Task <Os> CadastrarOS(Os ordemServico)
        {
            var rng    = new Random();
            var retoro = await _oSService.InsereDadosOSAsync(ordemServico);

            return(retoro);
        }
Beispiel #8
0
 public static VMExtensionWrapper?DependencyExtension(AzureLocation region, Os vmOs)
 {
     if (vmOs == Os.Windows)
     {
         return(new VMExtensionWrapper {
             Location = region,
             Name = "DependencyAgentWindows",
             AutoUpgradeMinorVersion = true,
             Publisher = "Microsoft.Azure.Monitoring.DependencyAgent",
             TypePropertiesType = "DependencyAgentWindows",
             TypeHandlerVersion = "9.5"
         });
     }
     else
     {
         // THIS TODO IS FROM PYTHON CODE
         //# TODO: dependency agent for linux is not reliable
         //# extension = {
         //#     "name": "DependencyAgentLinux",
         //#     "publisher": "Microsoft.Azure.Monitoring.DependencyAgent",
         //#     "type": "DependencyAgentLinux",
         //#     "typeHandlerVersion": "9.5",
         //#     "location": vm.region,
         //#     "autoUpgradeMinorVersion": True,
         //# }
         return(null);
     }
 }
Beispiel #9
0
        private void btnfechar_Click(object sender, EventArgs e)
        {
            try
            {
                Os os = new Os();
                os.Dataabertura_os            = dtpservico.Value.ToString("yyyy/MM/dd");
                os.Dataservico_os             = dtpabertura.Value.ToString("yyyy/MM/dd");
                os.Cep_os                     = txtcep.Text;
                os.Numendereco_os             = Convert.ToInt32(txtnumeroendereco.Text);
                os.Complemento_os             = txtcomplemento.Text;
                os.Vip_os                     = Convert.ToInt32(txtvip.Text);
                os.Horacontratadas_os         = Convert.ToInt32(txthorascontratadas.Text);
                os.Descricao_os               = txtdescricao.Text;
                os.Comentarios_os             = txtcomentario.Text;
                os.Status_os                  = 1;
                os.Tbl_servicos_id_servico    = Convert.ToInt32(txtservico.Text);
                os.Tbl_cliente_id_cliente     = Convert.ToInt32(txtcliente.Text);
                os.Tbl_prestador_id_prestador = Convert.ToInt32(txtprestador.Text);
                os.Id_os = Convert.ToInt32(txtid.Text);
                LimparCampos();

                dataGridView1.DataSource = new PrestadorBLL().ListarWhere("tbl_prestador_id_prestador =" + Globais.id);
                MessageBox.Show("Chamado fechado com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #10
0
        //public override bool Equals(object obj)
        //{
        //    return base.Equals(obj);
        //}

        //public override int GetHashCode()
        //{
        //    return base.GetHashCode();
        //}

        public async Task InsereOSAsync(Os ordemServico)


        {
            string sql = @"INSERT INTO os
                           Numero_OS, 
                           TituloServico,
                           CNPJCliente,
                           NomeCliente,
                           CPFPrestador,
                           NomePrestador,
                           DataExecução,
                           ValorServico)
                                  VALUES
                                       ( Numero_OS, 
                                        TituloServico,
                                        CNPJCliente,
                                        NomeCliente,
                                        CPFPrestador,
                                        NomePrestador,
                                        DataExecução,
                                        ValorServico)";

            await dbConnection.ExecuteAsync(sql, ordemServico);
        }
Beispiel #11
0
 private void btnexcluir_Click(object sender, EventArgs e)
 {
     try
     {
         if (!txtid.Text.Equals(string.Empty))
         {
             if (MessageBox.Show("Está ação irá deletar o registro selecionado e não poderá ser desfeito, deseja continuar?", "confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
             {
                 Os os = new Os();
                 os.Id_os = Convert.ToInt32(txtid.Text);
                 new OsBLL().Excluir(os);
                 LimparCampos();
                 dtgOs.DataSource = new OsBLL().Listar();
             }
         }
         else
         {
             MessageBox.Show("Favor selecionar o registro a ser deletado");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Beispiel #12
0
        public OsInfo(IEnumerable <IOsVersionAdapter> versionAdapters, Logger logger)
        {
            OsVersionModel osInfo = null;

            foreach (var osVersionAdapter in versionAdapters.Where(c => c.Enabled))
            {
                try
                {
                    osInfo = osVersionAdapter.Read();
                }
                catch (Exception e)
                {
                    logger.Error(e, "Couldn't get OS Version info");
                }

                if (osInfo != null)
                {
                    break;
                }
            }

            if (osInfo != null)
            {
                Name     = osInfo.Name;
                Version  = osInfo.Version;
                FullName = osInfo.FullName;
            }
            else
            {
                Name     = Os.ToString();
                FullName = Name;
            }
        }
Beispiel #13
0
 public void Invoke(string operation,
                    Ice.OperationMode mode,
                    Ice.FormatType?format,
                    Dictionary <string, string>?context,
                    bool synchronous,
                    System.Action <Ice.OutputStream>?write)
 {
     Debug.Assert(Os != null);
     try
     {
         Prepare(operation, mode, context);
         if (write != null)
         {
             Os.StartEncapsulation(Encoding, format);
             write(Os);
             Os.EndEncapsulation();
         }
         else
         {
             Os.WriteEmptyEncapsulation(Encoding);
         }
         Invoke(operation, synchronous);
     }
     catch (Ice.Exception ex)
     {
         Abort(ex);
     }
 }
Beispiel #14
0
 public void Dispose()
 {
     if (IsManaged)
     {
         Os.CloseNativeHandle(Handle.Object);
     }
 }
        internal IEnumerator DoImport(Item item, Skin skin)
        {
            ImportVersion2 importVersion2 = null;

            if (importVersion2.Bundle != null)
            {
                importVersion2.Bundle.Unload(true);
                importVersion2.Bundle = null;
            }
            WorkshopItemEditor.Loading(true, "Downloading..", "", 0f);
            if (!item.IsInstalled)
            {
                item.Download(true);
                while (item.IsDownloading)
                {
                    yield return(null);
                }
                while (!item.IsInstalled)
                {
                    yield return(null);
                }
            }
            string str = string.Concat(item.Directory, "/bundle");

            if (!File.Exists(str))
            {
                UnityEngine.Debug.LogWarning("No Bundle Found!");
                Os.OpenFolder(item.Directory);
                yield return(new WaitForSeconds(5f));
            }
            else
            {
                yield return(importVersion2.StartCoroutine(importVersion2.LoadItem(item.Directory, str, skin)));
            }
        }
Beispiel #16
0
        // SCRIPT evaluate python script in nodes signed with stamp in node link [F9]
        private void Evaluate(Diagram.Diagram diagram, DiagramView diagramView)
        {
            Nodes nodes = null;

            if (diagramView.selectedNodes.Count() > 0)
            {
                nodes = new Nodes(diagramView.selectedNodes);
            }
            else
            {
                nodes = new Nodes(diagram.GetAllNodes());
            }
            // remove nodes whit link other then [ ! | eval | evaluate | !#num_order | eval#num_order |  evaluate#num_order]
            // higest number is executed first
            Regex regex = new Regex(@"^\s*(eval(uate)|!){1}(#\w+){0,1}\s*$");
            nodes.RemoveAll(n => !regex.Match(n.link).Success);

            nodes.OrderByLink();
            nodes.Reverse();

            String clipboard = Os.GetTextFormClipboard();

#if !DEBUG
            Job.DoJob(
                new DoWorkEventHandler(
                    delegate (object o, DoWorkEventArgs args)
                    {
#endif
                        this.Evaluate(diagram, diagramView, nodes, clipboard);
#if !DEBUG
                    }
                )
            );
#endif
        }
Beispiel #17
0
        public void TestInitialize()
        {
            Memory memory = new Memory();

            m_cpu = new Cpu(memory);
            m_os  = new Os(m_cpu, memory);
        }
Beispiel #18
0
        private void MenuItemList_Click(object sender, RoutedEventArgs e)
        {
            ShowMyContentWindowDialog dialog = new ShowMyContentWindowDialog(Os.suc);

            if (dialog.ShowDialog() == true)
            {
                if (dialog.resultFileName.EndsWith(".lightScript"))
                {
                    if ((Os.suc.mw.LastProjectPath + @"\LightScript\" + dialog.resultFileName).Equals(Os.suc.filePath))
                    {
                        return;
                    }
                    ImportLibraryDialog _dialog = new ImportLibraryDialog(Os.suc.mw, Os.suc, Os.suc.mw.LastProjectPath + @"\LightScript\" + dialog.resultFileName, FinishEvent);
                    Os.suc.mw.ShowMakerDialog(_dialog);
                }
                else
                {
                    needClose = false;

                    RunCombo.Text      = dialog.resultFileName;
                    contextMenu.IsOpen = false;
                    Os.ToRefresh();
                }
            }
        }
Beispiel #19
0
    private Result <string> PrepareRemoteFilePath(Os operatingSystem = Os.Windows, params string[] paths)
    {
        if (paths == null || !paths.Any())
        {
            return(Result.Fail <string>($"{nameof(paths)} is not defined"));
        }

        try
        {
            switch (operatingSystem)
            {
            case Os.Linux: return(Result.Ok(string.Join("/", paths.Select(p => p.TrimStart('/').TrimEnd('/')))));

            case Os.Windows:
                return(Result.Ok
                       (
                           System.IO.Path.Combine(paths.Select(p => p.TrimStart('\\').TrimEnd('\\')).ToArray())
                       ));

            default: return(Result.Fail <string>($"Operation is not defined for [{operatingSystem}]"));
            }
        }
        catch (Exception e)
        {
            StartupBase.Current.DependencyResolver.Resolve <ILogger>()?.Log(e);
            return(Result.Fail <string>($"Path generation failed for paths [{string.Join(@",", paths)}]. Error: {e.Message}"));
        }
    }
        private static bool CheckOS(string systemOs, List <string> requierementOs)
        {
            try
            {
                foreach (string Os in requierementOs)
                {
                    if (systemOs.ToLower().IndexOf("10") > -1)
                    {
                        return(true);
                    }

                    if (systemOs.ToLower().IndexOf(Os.ToLower()) > -1)
                    {
                        return(true);
                    }

                    int numberOsRequirement = 0;
                    int numberOsPc          = 0;
                    Int32.TryParse(Os, out numberOsRequirement);
                    Int32.TryParse(Regex.Replace(systemOs, "[^.0-9]", string.Empty).Trim(), out numberOsPc);
                    if (numberOsRequirement != 0 && numberOsPc != 0 && numberOsPc >= numberOsRequirement)
                    {
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogError(ex, "SystemChecker", $"Error on CheckOs() with {systemOs} & {JsonConvert.SerializeObject(requierementOs)}");
            }

            return(false);
        }
        internal Host GetHost()
        {
            if (_host is null)
            {
                // Architecture osArchitecture = RuntimeInformation.OSArchitecture;
                // if (osDescription.Contains('#'))
                // {
                //     int indexOfHash = osDescription.IndexOf('#');
                //     osDescription = osDescription.Substring(0, Math.Max(0, indexOfHash - 1));
                // }

                var operatingSystem = new Os
                {
                    Full     = RuntimeInformation.OSDescription,
                    Platform = Environment.OSVersion.Platform.ToString(),
                    Version  = Environment.OSVersion.Version.ToString()
                };
                _host = new Host
                {
                    Hostname     = Environment.MachineName,
                    Architecture = RuntimeInformation.OSArchitecture.ToString(),
                    Os           = operatingSystem
                };
            }

            return(_host);
        }
Beispiel #22
0
        public async Task <IActionResult> Create()
        {
            bool isWindows = Request.Headers.TryGetValue("User-Agent", out StringValues userAgentValues) && userAgentValues.Any((string x) => x?.ToUpperInvariant().Contains("WINDOWS") ?? false);
            bool isMac     = Request.Headers.TryGetValue("User-Agent", out userAgentValues) && userAgentValues.Any((string x) => x?.ToUpperInvariant().Contains("MAC OS") ?? false);

            Os os = isWindows ? Os.Windows : isMac ? Os.MacOs : Os.LinuxOrUnix;

            const string               clientId    = "fa24eac7-0684-4964-ab13-9d4ff772e3d1";
            X509Certificate2           cert        = new X509Certificate2(@"App_Data\1script.pfx", "No password");
            ClientAssertionCertificate certCred    = new ClientAssertionCertificate(clientId, cert);
            AuthenticationContext      authContext = new AuthenticationContext("https://login.windows.net/b550583b-bc56-47d4-b547-6982b363a8b0/");
            AuthenticationResult       authResult  = await authContext.AcquireTokenAsync("https://management.azure.com/", certCred);

            string token = authResult.AccessToken;

            string siteName = Guid.NewGuid().ToString().Replace("-", "").ToLowerInvariant();

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            string payload = @"{
    ""location"": ""West US"",
    ""name"": ""Generated156789765467i87654"",
    ""type"": ""Microsoft.Web/sites"",
    ""tags"": {
        ""hidden-related:subscriptions/c09ce800-abd2-48c5-8565-dc51435d90ec/resourceGroups/1script/providers/Microsoft.Web/serverfarms/1scriptplan"": ""empty""
    },
    ""kind"": ""app"",
    ""properties"": {
        ""name"": ""Generated156789765467i87654"",
        ""serverFarmId"": ""subscriptions/c09ce800-abd2-48c5-8565-dc51435d90ec/resourceGroups/1script/providers/Microsoft.Web/serverfarms/1scriptplan"",
        ""kind"": ""app""
    }
}".Replace("Generated156789765467i87654", siteName);

            string location      = "https://management.azure.com/subscriptions/c09ce800-abd2-48c5-8565-dc51435d90ec/resourceGroups/1script/providers/Microsoft.Web/sites/Generated156789765467i87654?api-version=2016-08-01".Replace("Generated156789765467i87654", siteName);
            string credsLocation = "https://management.azure.com/subscriptions/c09ce800-abd2-48c5-8565-dc51435d90ec/resourceGroups/1script/providers/Microsoft.Web/sites/Generated156789765467i87654/config/publishingcredentials/list?api-version=2016-08-01".Replace("Generated156789765467i87654", siteName);


            StringContent       content         = new StringContent(payload, Encoding.UTF8, "application/json");
            HttpResponseMessage responseMessage = await client.PutAsync(location, content);

            responseMessage.EnsureSuccessStatusCode();
            content = new StringContent(string.Empty, Encoding.UTF8, "text/plain");
            HttpResponseMessage response = await client.PostAsync(credsLocation, content);

            string credsString = await response.Content.ReadAsStringAsync();

            JObject responseJson = JObject.Parse(credsString);
            string  username     = responseJson["properties"]["publishingUserName"].ToString();
            string  password     = responseJson["properties"]["publishingPassword"].ToString();

            string realResponse = GenerateScript(siteName, username, password, os);

            byte[] data = Encoding.UTF8.GetBytes(realResponse);
            string name = isWindows ? "get-started.cmd" : "get-started.sh";

            return(File(data, "text/plain", name));
        }
        internal static UserInfo RequestUserInfo(string username, string token, string tld, RestClient rest)
        {
            var response = rest.PostForm <R.Lookup>(
                LookupUrl(tld, username),
                new Dictionary <string, object>
            {
                ["mode"]        = "primary",
                ["cli_time"]    = Os.UnixMilliseconds(),
                ["servicename"] = ServiceName,
            },
                headers: new Dictionary <string, string> {
                ["X-ZCSRF-TOKEN"] = $"iamcsrcoo={token}"
            },
                cookies: new Dictionary <string, string> {
                ["iamcsr"] = token
            });

            if (!response.IsSuccessful)
            {
                throw MakeErrorOnFailedRequest(response);
            }

            var status = response.Data;

            // Success (200..299)
            if (status.StatusCode / 100 == 2)
            {
                var result = status.Result;
                if (result == null)
                {
                    throw MakeInvalidResponseError("lookup result not found");
                }

                return(new UserInfo(id: result.UserId,
                                    digest: result.Digest,
                                    tld: DataCenterToTld(result.DataCenter)));
            }

            var error = GetError(status);

            switch (error.Code)
            {
            // User exists in another data center
            case "U400":
                var redirect = status.Redirect;
                if (redirect == null)
                {
                    throw MakeInvalidResponseError("redirect info not found");
                }

                return(RequestUserInfo(username, token, DataCenterToTld(redirect.DataCenter), rest));

            // User doesn't exist
            case "U401":
                throw new BadCredentialsException("The username is invalid");
            }

            throw MakeInvalidResponseError(status);
        }
Beispiel #24
0
 private void TestOpening()
 {
     OResults = Os.Select(condition =>
                          Tuple.Create(
                              condition,
                              Range(0, N).Where(condition.Query).ToArray()
                              )).ToDictionary(t => t.Item1, t => t.Item2);
 }
Beispiel #25
0
 protected virtual void Dispose(bool Disposing)
 {
     if (Disposing)
     {
         Os.Dispose();
         VFs.Dispose();
     }
 }
Beispiel #26
0
        private void ColorPanel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            needClose = false;

            RunCombo.Text      = ((ListBox)sender).SelectedIndex.ToString();
            contextMenu.IsOpen = false;
            Os.ToRefresh();
        }
Beispiel #27
0
        public static bool CheckSpaceAvailable(Context context, DownloadDetails.RootDirectoryDetails root, long neededSpace)
        {
            var descriptor     = context.ContentResolver.OpenFileDescriptor(root.DocumentFile.Uri, "r");
            var stats          = Os.Fstatvfs(descriptor.FileDescriptor);
            var availableSpace = (stats.FBavail * stats.FBsize);

            return(neededSpace <= availableSpace);
        }
Beispiel #28
0
        private void _menuItem_Click(object sender, RoutedEventArgs e)
        {
            needClose = false;

            RunCombo.Text      = ((MenuItem)sender).Header.ToString();
            contextMenu.IsOpen = false;
            Os.ToRefresh();
        }
Beispiel #29
0
 public void OpenFileLocation()
 {
     if (this.IsDefault)
     {
         return;
     }
     Os.OpenFolder(this.Filename);
 }
Beispiel #30
0
        //
        // Internal
        //

        internal XDocument SendCommand(string command, string commandId, string authKey = "")
        {
            var timestamp = Os.UnixMilliseconds();
            var id        = $"{command}-{Client.DeviceKind}-{Client.ServiceId}-{timestamp}";
            var auth      = authKey.IsNullOrEmpty() ? "" : $"MPAuthKeyValueInBase64='{authKey}' ";

            return(RequestXml($"<message xmlns='jabber:client' id='{id}' to='kpm-sync@{_jid.Host}' from='{_jid.Bare}'><body/><root unique_id='{commandId}' productVersion='' protocolVersion='' projectVersion='9.2.0.1' deviceType='0' osType='0' {auth}/></message>"));
        }
Beispiel #31
0
        public ConsoleRunHost([NotNull] ServiceDescription description, [NotNull] IServiceCoordinator coordinator, [NotNull]Os osCommands)
        {
            if (description == null)
                throw new ArgumentNullException("description");
            if (coordinator == null)
                throw new ArgumentNullException("coordinator");
            if(osCommands ==null)
                throw new ArgumentNullException("osCommands");

            _description = description;
            _coordinator = coordinator;
            _osCommands = osCommands;
        }
 public void WyborOsi(Os os)
 {
     matlab.Execute(@"[os, oska] = wybor_osi(" + (int)os + @");");
 }
 private void Filtruj(Staw staw, Os os, string nazwaSkeletona = "SKELETON")
 {
     matlab.Execute(@"[SKELETON] = filtr(SKELETON, " + (int)staw + ", " + (int)os + ");");
 }