Exemplo n.º 1
0
        private void DecryptFile(string p_input)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            string v_output;

            try
            {
                Console.Write("Type the password to decrypt the file: ");
                v_cryptor = new Spartacus.Utils.Cryptor(Console.ReadLine());

                if (p_input.EndsWith(".crypt"))
                {
                    v_output = p_input.Replace(".crypt", "");
                }
                else
                {
                    v_output = p_input + ".decrypt";
                }

                v_cryptor.DecryptFile(p_input, v_output);

                Console.WriteLine();
                Console.WriteLine("File {0} successfully decrypted to the file {1}.", p_input, v_output);
            }
            catch (Spartacus.Utils.Exception e)
            {
                Console.WriteLine(e.v_message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 2
0
        public static AjaxReturn GetUsers()
        {
            AjaxReturn v_return      = new AjaxReturn();
            UsersData  v_return_data = new UsersData();
            Session    v_session     = (Session)System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"];

            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            if (v_session == null)
            {
                v_return.v_error    = true;
                v_return.v_error_id = 1;
                return(v_return);
            }

            System.Data.DataTable v_users = v_session.v_omnidb_database.v_connection.Query("select * from users order by user_id", "Users");

            System.Collections.Generic.List <System.Collections.Generic.List <string> > v_user_list = new System.Collections.Generic.List <System.Collections.Generic.List <string> >();
            System.Collections.Generic.List <string> v_user_id_list = new System.Collections.Generic.List <string>();

            int v_index = 0;

            foreach (System.Data.DataRow v_user in v_users.Rows)
            {
                System.Collections.Generic.List <string> v_user_data_list = new System.Collections.Generic.List <string>();

                v_user_data_list.Add(v_user["user_name"].ToString());

                try
                {
                    v_user_data_list.Add(v_cryptor.Decrypt(v_user["password"].ToString()));
                }
                catch (Spartacus.Utils.Exception)
                {
                    v_user_data_list.Add(v_user["password"].ToString());
                }

                if (v_user["user_name"].ToString() == "admin")
                {
                    v_user_data_list.Add("");
                }
                else
                {
                    v_user_data_list.Add("<img src='images/tab_close.png' class='img_ht' onclick='removeUser(" + v_user["user_id"].ToString() + ")'/>");
                }

                v_index++;

                v_user_list.Add(v_user_data_list);

                v_user_id_list.Add(v_user["user_id"].ToString());
            }

            v_return_data.v_data     = v_user_list;
            v_return_data.v_user_ids = v_user_id_list;

            v_return.v_data = v_return_data;
            return(v_return);
        }
Exemplo n.º 3
0
        public static AjaxReturn SaveConnections(System.Collections.Generic.List <System.Collections.Generic.List <string> > p_data, System.Collections.Generic.List <string> p_conn_id_list)
        {
            AjaxReturn v_return  = new AjaxReturn();
            Session    v_session = (Session)System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"];

            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            if (v_session == null)
            {
                v_return.v_error    = true;
                v_return.v_error_id = 1;
                return(v_return);
            }

            string v_update_format = "update connections " +
                                     "set dbt_st_name = '#p_dbt_st_name#', " +
                                     "server          = '#p_server#', " +
                                     "port            = '#p_port#', " +
                                     "service         = '#p_service#', " +
                                     "schema          = '#p_schema#', " +
                                     "user            = '******', " +
                                     "password        = '******', " +
                                     "alias           = '#p_alias#' " +
                                     "where conn_id   = #p_conn_id#";

            for (int i = 0; i < p_data.Count; i++)
            {
                string v_update = v_update_format;
                v_update = v_update.Replace("#p_conn_id#", p_conn_id_list[i]);
                v_update = v_update.Replace("#p_dbt_st_name#", p_data [i][0]);
                try
                {
                    v_update = v_update.Replace("#p_server#", v_cryptor.Encrypt(p_data [i][1]));
                    v_update = v_update.Replace("#p_port#", v_cryptor.Encrypt(p_data [i][2]));
                    v_update = v_update.Replace("#p_service#", v_cryptor.Encrypt(p_data [i][3]));
                    v_update = v_update.Replace("#p_schema#", v_cryptor.Encrypt(p_data [i][4]));
                    v_update = v_update.Replace("#p_user#", v_cryptor.Encrypt(p_data [i][5]));
                    v_update = v_update.Replace("#p_password#", v_cryptor.Encrypt(p_data [i][6]));
                    v_update = v_update.Replace("#p_alias#", v_cryptor.Encrypt(p_data [i][7]));
                }
                catch (Spartacus.Utils.Exception)
                {
                    v_update = v_update.Replace("#p_server#", p_data [i][1]);
                    v_update = v_update.Replace("#p_port#", p_data [i][2]);
                    v_update = v_update.Replace("#p_service#", p_data [i][3]);
                    v_update = v_update.Replace("#p_schema#", p_data [i][4]);
                    v_update = v_update.Replace("#p_user#", p_data [i][5]);
                    v_update = v_update.Replace("#p_password#", p_data [i][6]);
                    v_update = v_update.Replace("#p_alias#", p_data [i][7]);
                }

                v_session.v_omnidb_database.v_connection.Execute(v_update);
            }

            v_session.RefreshDatabaseList();

            return(v_return);
        }
Exemplo n.º 4
0
        public static AjaxReturn SaveConfigUser(string p_pwd)
        {
            AjaxReturn v_return  = new AjaxReturn();
            Session    v_session = (Session)System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"];

            if (v_session == null)
            {
                v_return.v_error    = true;
                v_return.v_error_id = 1;
                return(v_return);
            }

            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            System.IO.File.WriteAllText("config/admin.txt", v_cryptor.Encrypt(p_pwd));

            return(v_return);
        }
Exemplo n.º 5
0
        private void DecryptString(string p_input)
        {
            Spartacus.Utils.Cryptor v_cryptor;

            try
            {
                Console.Write("Type the password to decrypt the string: ");
                v_cryptor = new Spartacus.Utils.Cryptor(Console.ReadLine());

                Console.WriteLine("                The decrypted string is: {0}", v_cryptor.Decrypt(p_input));
            }
            catch (Spartacus.Utils.Exception e)
            {
                Console.WriteLine(e.v_message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 6
0
        public static AjaxReturn SaveUsers(System.Collections.Generic.List <System.Collections.Generic.List <string> > p_data, System.Collections.Generic.List <string> p_user_id_list)
        {
            AjaxReturn v_return  = new AjaxReturn();
            Session    v_session = (Session)System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"];

            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            if (v_session == null)
            {
                v_return.v_error    = true;
                v_return.v_error_id = 1;
                return(v_return);
            }

            string v_update_format = "update users  " +
                                     "set user_name   = '#p_user_name#', " +
                                     "password        = '******'   " +
                                     "where user_id   = #p_user_id#";

            for (int i = 0; i < p_data.Count; i++)
            {
                string v_update = v_update_format;
                v_update = v_update.Replace("#p_user_id#", p_user_id_list[i]);
                v_update = v_update.Replace("#p_user_name#", p_data [i][0]);
                try
                {
                    v_update = v_update.Replace("#p_password#", v_cryptor.Encrypt(p_data [i][1]));
                }
                catch (Spartacus.Utils.Exception)
                {
                    v_update = v_update.Replace("#p_password#", p_data [i][1]);
                }

                v_session.v_omnidb_database.v_connection.Execute(v_update);
            }


            return(v_return);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Informa o texto ou valor a ser mostrado no Textbox.
        /// Usado para mostrar ao usuário um formulário já preenchido.
        /// O texto é passado criptografado, e é descriptografado para ser exibido ao usuário.
        /// </summary>
        /// <param name="p_text">Texto a ser mostrado no Textbox.</param>
        /// <param name="p_decryptpassword">Senha para descriptografar.</param>
        public void SetEncryptedValue(string p_text, string p_decryptpassword)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            string v_decrypted;

            v_cryptor = new Spartacus.Utils.Cryptor(p_decryptpassword);

            try
            {
                v_decrypted = v_cryptor.Decrypt(p_text);
            }
            catch (Spartacus.Utils.Exception)
            {
                v_decrypted = p_text;
            }
            catch (System.Exception)
            {
                v_decrypted = p_text;
            }

            this.v_textbox.Text = v_decrypted;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Retorna o texto ou valor atual do Textbox, porém criptografado.
        /// </summary>
        /// <returns>Texto ou valor atual do Textbox, porém criptografado.</returns>
        /// <param name="p_encryptpassword">Senha para criptografar.</param>
        public string GetEncryptedValue(string p_encryptpassword)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            string v_encrypted;

            v_cryptor = new Spartacus.Utils.Cryptor(p_encryptpassword);

            try
            {
                v_encrypted = v_cryptor.Encrypt(this.v_textbox.Text);
            }
            catch (Spartacus.Utils.Exception)
            {
                v_encrypted = this.v_textbox.Text;
            }
            catch (System.Exception)
            {
                v_encrypted = this.v_textbox.Text;
            }

            return(v_encrypted);
        }
Exemplo n.º 9
0
        private void DecryptFile(string p_input, string p_output)
        {
            Spartacus.Utils.Cryptor v_cryptor;

            try
            {
                Console.Write("Type the password to decrypt the file: ");
                v_cryptor = new Spartacus.Utils.Cryptor(Console.ReadLine());

                v_cryptor.DecryptFile(p_input, p_output);

                Console.WriteLine();
                Console.WriteLine("File {0} successfully decrypted to the file {1}.", p_input, p_output);
            }
            catch (Spartacus.Utils.Exception e)
            {
                Console.WriteLine(e.v_message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 10
0
        private void EncryptString()
        {
            Spartacus.Utils.Cryptor v_cryptor;
            string v_input;

            try
            {
                Console.Write("Type the password to encrypt the string: ");
                v_cryptor = new Spartacus.Utils.Cryptor(Console.ReadLine());

                Console.Write("        Type the string to be encrypted: ");
                v_input = Console.ReadLine();

                Console.WriteLine("                The encrypted string is: {0}", v_cryptor.Encrypt(v_input));
            }
            catch (Spartacus.Utils.Exception e)
            {
                Console.WriteLine(e.v_message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Retorna o nome completo criptografado do arquivo ou diretório atual.
        /// Isso é necessário para armazenar strings sem acento no banco de dados.
        /// </summary>
        /// <returns>
        /// Nome completo do arquivo ou diretório atual.
        /// </returns>
        /// <param name='p_encryptname'>
        /// Se deve criptografar ou não o nome do arquivo.
        /// </param>
        public string CompleteFileName(bool p_encryptname)
        {
            Spartacus.Utils.Cryptor v_cryptor;

            if (p_encryptname)
            {
                v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                return v_cryptor.Encrypt(this.CompleteFileName());
            }
            else
                return this.CompleteFileName();
        }
Exemplo n.º 12
0
        private void OnConnect(Spartacus.Net.ConnectEventClass obj, Spartacus.Net.ConnectEventArgs e)
        {
            System.IO.StreamReader      v_reader;
            System.IO.StreamWriter      v_writer;
            System.Text.StringBuilder   v_data;
            Spartacus.Utils.Cryptor     v_cryptor;
            System.Net.Mail.MailMessage v_message;
            string v_line = null;

            System.Data.DataTable v_table;
            bool v_achou;
            int  k, v_inserted;

            if (this.v_log)
            {
                Console.WriteLine("Cliente {0} - {1}:{2} conectado", e.v_index, e.v_clientip, e.v_clientport);
            }

            v_reader           = new System.IO.StreamReader(this.v_streams[e.v_index]);
            v_writer           = new System.IO.StreamWriter(this.v_streams[e.v_index]);
            v_writer.NewLine   = "\r\n";
            v_writer.AutoFlush = true;

            v_cryptor = new Spartacus.Utils.Cryptor(null);

            v_message = new System.Net.Mail.MailMessage();
            v_message.BodyEncoding = System.Text.Encoding.UTF8;
            v_message.IsBodyHtml   = false;

            try
            {
                v_writer.WriteLine("220 Spartacus FakeSMTP Server");

                while (v_reader != null)
                {
                    v_line = v_reader.ReadLine();
                    if (this.v_log)
                    {
                        Console.WriteLine("Client: {0} - Line: [{1}]", e.v_index, v_line);
                    }

                    if (!string.IsNullOrWhiteSpace(v_line))
                    {
                        if (v_line.StartsWith("HELO") || v_line.StartsWith("EHLO"))
                        {
                            if (this.v_credential == null)
                            {
                                this.v_credential = new System.Net.NetworkCredential("", "");

                                v_writer.WriteLine("250 AUTH LOGIN");
                                v_line = v_reader.ReadLine();

                                v_writer.WriteLine("334 VXNlcm5hbWU6");
                                this.v_credential.UserName = v_cryptor.Base64Decode(v_reader.ReadLine());

                                v_writer.WriteLine("334 UGFzc3dvcmQ6");
                                this.v_credential.Password = v_cryptor.Base64Decode(v_reader.ReadLine());

                                v_writer.WriteLine("235 OK");
                            }
                            else
                            {
                                v_writer.WriteLine("250 OK");
                            }
                        }
                        else if (v_line.StartsWith("MAIL FROM:"))
                        {
                            v_message.From = new System.Net.Mail.MailAddress(v_line.Substring("MAIL FROM:".Length + 1, v_line.Length - ("MAIL FROM:".Length + 2)).Replace("<", "").Replace(">", ""));
                            v_writer.WriteLine("250 OK");
                        }
                        else if (v_line.StartsWith("RCPT TO:"))
                        {
                            v_message.To.Add(new System.Net.Mail.MailAddress(v_line.Substring("RCPT TO:".Length + 1, v_line.Length - ("RCPT TO:".Length + 2)).Replace("<", "").Replace(">", "")));
                            v_writer.WriteLine("250 OK");
                        }
                        else if (v_line == "DATA")
                        {
                            v_writer.WriteLine("354 Start input, end data with <CRLF>.<CRLF>");

                            v_data = new System.Text.StringBuilder();

                            v_line = v_reader.ReadLine();

                            while (v_line != null && v_line != ".")
                            {
                                if (v_line.StartsWith("Subject: "))
                                {
                                    v_message.Subject = v_line.Substring("Subject: ".Length);
                                }

                                v_data.AppendLine(v_line);
                                v_line = v_reader.ReadLine();
                            }

                            v_message.Body = v_data.ToString();

                            // logando mensagem
                            if (this.v_log)
                            {
                                Console.WriteLine("===============================================================================");
                                Console.WriteLine("{0}: Currently connected clients: {1}", System.DateTime.Now, this.v_numclients);
                                Console.WriteLine("All good, received ­email");
                                Console.WriteLine("-------------------------------------------------------------------------------");
                                Console.WriteLine("User: {0}", this.v_credential.UserName);
                                Console.WriteLine("Password: {0}", this.v_credential.Password);
                                Console.WriteLine("-------------------------------------------------------------------------------");
                                Console.WriteLine("From: " + v_message.From);
                                Console.Write("To: ");
                                foreach (System.Net.Mail.MailAddress m in v_message.To)
                                {
                                    Console.Write("{0} ", m.Address);
                                }
                                Console.WriteLine();
                                Console.WriteLine("Subject: " + v_message.Subject);
                                if (this.v_logeml)
                                {
                                    Console.WriteLine("-------------------------------------------------------------------------------");
                                    Console.WriteLine(v_message.Body);
                                    Console.WriteLine("-------------------------------------------------------------------------------");
                                }
                                Console.WriteLine("===============================================================================");
                            }

                            // redirecionando mensagem
                            if (this.v_redirect)
                            {
                                if (this.v_log)
                                {
                                    Console.Write("Sending message to {0}:{1}... ", this.v_realhost, this.v_realport);
                                }

                                this.v_mailclient.Send(this.v_realhost, this.v_realport, v_credential, v_message.Body);

                                if (this.v_log)
                                {
                                    Console.WriteLine("OK");
                                }
                            }

                            // inserindo enderecos na whitelist
                            if (this.v_whitelist)
                            {
                                if (this.v_log)
                                {
                                    Console.Write("Updating whitelist... ");
                                }

                                v_inserted = 0;
                                this.v_database.Open();
                                v_table = this.v_database.Query(this.v_select, "WHITELIST");

                                k       = 0;
                                v_achou = false;
                                while (k < v_table.Rows.Count && !v_achou)
                                {
                                    if (v_table.Rows[k][0].ToString() == v_message.From.Address)
                                    {
                                        v_achou = true;
                                    }
                                    else
                                    {
                                        k++;
                                    }
                                }
                                if (!v_achou)
                                {
                                    this.v_insert.SetValue(0, v_message.From.Address);
                                    this.v_database.Execute(this.v_insert.GetUpdatedText());
                                    v_inserted++;
                                }

                                foreach (System.Net.Mail.MailAddress m in v_message.To)
                                {
                                    if (m.Address != v_message.From.Address)
                                    {
                                        k       = 0;
                                        v_achou = false;
                                        while (k < v_table.Rows.Count && !v_achou)
                                        {
                                            if (v_table.Rows[k][0].ToString() == m.Address)
                                            {
                                                v_achou = true;
                                            }
                                            else
                                            {
                                                k++;
                                            }
                                        }
                                        if (!v_achou)
                                        {
                                            this.v_insert.SetValue(0, m.Address);
                                            this.v_database.Execute(this.v_insert.GetUpdatedText());
                                            v_inserted++;
                                        }
                                    }
                                }

                                this.v_database.Close();
                                if (this.v_log)
                                {
                                    Console.WriteLine("OK, {0} addresses inserted on whitelist.", v_inserted);
                                }
                            }

                            if (this.v_log)
                            {
                                Console.WriteLine();
                            }

                            v_writer.WriteLine("250 OK");
                        }
                        else if (v_line == "QUIT")
                        {
                            v_writer.WriteLine("250 OK");
                            v_reader = null;
                            if (this.v_log)
                            {
                                Console.WriteLine();
                            }
                        }
                        else
                        {
                            if (this.v_log)
                            {
                                Console.WriteLine("UNHANDLED: {0}", v_line);
                            }
                            v_writer.WriteLine("250 OK");
                        }
                    }
                    else
                    {
                        if (this.v_log)
                        {
                            Console.WriteLine("EMPTY: {0}", v_line);
                        }
                        v_writer.WriteLine("250 OK");
                    }
                }
            }
            catch (System.Exception exc)
            {
                if (this.v_log)
                {
                    Console.WriteLine("ERROR: {0}", exc.Message);
                }
            }
            finally
            {
                this.StopClient(e.v_index);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Constrói o banco de dados temporário.
        /// </summary>
        /// <param name="p_sql">Texto SQL.</param>
        private void BuildCache(string p_sql)
        {
            Spartacus.Utils.ProgressEventClass v_progress;
            Spartacus.Utils.ErrorEventClass    v_error;
            Spartacus.Utils.Cryptor            v_cryptor;
            System.IO.FileInfo v_info;
            long v_totalsize;

            v_totalsize = 0;
            foreach (string s in this.ExtractFromString(p_sql, "[", "]"))
            {
                if (!s.StartsWith("."))
                {
                    v_info = new System.IO.FileInfo(this.v_service + "/" + s);

                    if (v_info.Exists)
                    {
                        if (p_sql.ToLower().Contains("drop table [" + s.ToLower() + "]"))
                        {
                            this.v_tabletodrop = s.ToLower();
                        }

                        v_totalsize += v_info.Length;
                        this.v_tables.Add(s);
                    }
                    else
                    {
                        if (p_sql.ToLower().Contains("create table [" + s.ToLower() + "]"))
                        {
                            this.v_tables.Add(s.ToLower());
                        }
                        else
                        {
                            throw new Spartacus.Database.Exception("File '{0}' does not exist and is not going to be created.", s);
                        }
                    }
                }
            }

            if (v_totalsize > this.v_cachethreshold)
            {
                v_cryptor           = new Spartacus.Utils.Cryptor("spartacus");
                this.v_tempdatabase = v_cryptor.RandomString() + ".db";
                this.v_database     = new Spartacus.Database.Sqlite(this.v_tempdatabase);
            }
            else
            {
                this.v_tempdatabase = "";
                this.v_database     = new Spartacus.Database.Memory();
            }

            this.v_database.SetTimeout(-1);
            this.v_database.SetExecuteSecurity(false);
            this.v_database.Open();
            this.v_database.Execute("PRAGMA synchronous=OFF");

            v_progress = new Spartacus.Utils.ProgressEventClass();
            v_progress.ProgressEvent += new Spartacus.Utils.ProgressEventClass.ProgressEventHandler(OnProgress);
            v_error             = new Spartacus.Utils.ErrorEventClass();
            v_error.ErrorEvent += new Spartacus.Utils.ErrorEventClass.ErrorEventHandler(OnError);

            foreach (string t in this.v_tables)
            {
                v_info = new System.IO.FileInfo(this.v_service + "/" + t);
                if (v_info.Exists)
                {
                    this.v_database.TransferFromFile(this.v_service + "/" + t, this.v_separator, this.v_delimiter, this.v_header, this.v_encoding, "[" + t + "]", v_progress, v_error);
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Salva como PDF parcialmente.
        /// Usado para renderização de pacotes de arquivos PDF.
        /// </summary>
        /// <param name="p_pdf">Objeto PDF aberto.</param>
        public void SavePartial(PDFjet.NET.PDF p_pdf)
        {
            PDFjet.NET.Table v_dataheadertable = null, v_datatable;
            float[] v_layout;
            PDFjet.NET.Page v_page;
            System.Collections.Generic.List<System.Collections.Generic.List<PDFjet.NET.Cell>> v_rendered;
            int v_numpages, v_currentpage;
            Spartacus.Utils.Cryptor v_cryptor;
            string v_datafilename;
            System.IO.StreamReader v_reader;

            // se o relatório não tiver dados, não faz nada
            if (this.v_table.Rows.Count == 0)
                return;

            try
            {
                this.v_progress.FireEvent("Spartacus.Reporting.Report", "ExportPDF", this.v_perc, "Renderizando o relatorio " + this.v_reportid.ToString());
                this.v_inc = this.v_percstep / (double) this.v_table.Rows.Count;
                this.v_renderedrows = 0;

                if (this.v_settings.v_layout == Spartacus.Reporting.PageLayout.LANDSCAPE)
                    v_layout = PDFjet.NET.A4.LANDSCAPE;
                else
                    v_layout = PDFjet.NET.A4.PORTRAIT;

                v_page = new PDFjet.NET.Page(p_pdf, v_layout);

                // tabela de cabecalho de dados

                if (this.v_settings.v_showdataheader)
                {
                    v_dataheadertable = new PDFjet.NET.Table();
                    v_dataheadertable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height);

                    v_rendered = this.RenderDataHeader(
                        v_page.GetHeight(),
                        v_page.GetWidth(),
                        this.v_settings.v_dataheaderfont.GetFont(p_pdf)
                    );

                    v_dataheadertable.SetData(v_rendered, PDFjet.NET.Table.DATA_HAS_0_HEADER_ROWS);
                    //v_dataheadertable.SetCellBordersWidth(1.5f);
                }

                // tabela de dados

                v_datatable = new PDFjet.NET.Table();
                //v_datatable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height + ((this.v_settings.v_dataheaderfont.v_size + 2) * 1.8 * this.v_numrowsdetail));
                if (this.v_settings.v_showdataheader)
                    v_datatable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height + ((this.v_settings.v_dataheaderfont.v_size + 2) * 1.8 * this.v_numrowsdataheader));
                else
                    v_datatable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height);
                v_datatable.SetBottomMargin(this.v_settings.v_bottommargin + this.v_footer.v_height);

                this.BuildTemplates(
                    v_page.GetHeight(),
                    v_page.GetWidth(),
                    this.v_settings.v_datafieldfont.GetFont(p_pdf),
                    this.v_settings.v_groupheaderfont.GetFont(p_pdf),
                    this.v_settings.v_groupfooterfont.GetFont(p_pdf)
                );

                v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                v_datafilename = v_cryptor.RandomString() + ".tmp";
                this.v_datafile = System.IO.File.Open(
                    v_datafilename,
                    System.IO.FileMode.Create,
                    System.IO.FileAccess.ReadWrite
                );

                v_rendered = this.RenderData(
                    v_page.GetHeight(),
                    v_page.GetWidth(),
                    this.v_settings.v_datafieldfont.GetFont(p_pdf),
                    this.v_settings.v_groupheaderfont.GetFont(p_pdf),
                    this.v_settings.v_groupfooterfont.GetFont(p_pdf)
                );

                v_datatable.SetData(v_rendered, PDFjet.NET.Table.DATA_HAS_0_HEADER_ROWS);
                //v_datatable.SetCellBordersWidth(1.5f);

                this.v_datafile.Seek(0, System.IO.SeekOrigin.Begin);
                v_reader = new System.IO.StreamReader(this.v_datafile);

                // salvando PDF

                this.v_header.SetValues(this.v_table);
                this.v_footer.SetValues(this.v_table);

                v_numpages = v_datatable.GetNumberOfPages(v_page);
                v_currentpage = 1;
                while (v_datatable.HasMoreData())
                {
                    this.v_header.SetPageNumber(v_currentpage, v_numpages);
                    this.v_footer.SetPageNumber(v_currentpage, v_numpages);

                    this.v_header.Render(
                        this.v_settings.v_reportheaderfont,
                        this.v_settings.v_leftmargin,
                        this.v_settings.v_topmargin,
                        this.v_settings.v_rightmargin,
                        p_pdf,
                        v_page
                    );

                    if (this.v_settings.v_showdataheader)
                        v_dataheadertable.DrawOn(v_page);
                    v_datatable.ImprovedDrawOn(v_page, v_reader);

                    this.v_footer.Render(
                        this.v_settings.v_reportfooterfont,
                        this.v_settings.v_leftmargin,
                        v_page.GetHeight() - v_settings.v_bottommargin - v_footer.v_height,
                        this.v_settings.v_rightmargin,
                        p_pdf,
                        v_page
                    );

                    if (v_datatable.HasMoreData())
                    {
                        if (this.v_settings.v_showdataheader)
                            v_dataheadertable.ResetRenderedPagesCount();

                        v_page = new PDFjet.NET.Page(p_pdf, v_layout);
                        v_currentpage++;
                    }
                }

                v_reader.Close();
                this.v_datafile.Close();
                (new System.IO.FileInfo(v_datafilename)).Delete();

                this.v_perc = this.v_lastperc;
                this.v_progress.FireEvent("Spartacus.Reporting.Report", "ExportPDF", this.v_perc, "Relatorio " + this.v_reportid.ToString() + " renderizado.");
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Reporting.Exception("Erro ao gerar o arquivo PDF de saída.", e);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Salva todos os relatórios em arquivos separados.
        /// </summary>
        /// <param name="p_filenames">Lista de nomes de arquivos, que deve possuir o mesmo número de elementos.</param>
        /// <param name="p_compress">Gerar arquivo ZIP com todos os arquivos PDF.</param>
        /// <param name="p_outfilename">Nome do arquivo ZIP de saída.</param>
        public void SaveSplitted(System.Collections.ArrayList p_filenames, bool p_compress, string p_outfilename)
        {
            Spartacus.ThirdParty.ZipStorer v_zipstorer;
            Spartacus.Utils.Cryptor v_cryptor;
            string v_encrypted;
            Spartacus.Reporting.Report v_report;
            double v_perc, v_percstep, v_lastperc;

            try
            {
                if (p_compress)
                {
                    v_cryptor = new Spartacus.Utils.Cryptor("spartacus");

                    v_zipstorer = Spartacus.ThirdParty.ZipStorer.Create(p_outfilename, "Generated with ZipStorer (by Jaime Olivares) embedded in Spartacus (by William Ivanski)");
                    v_zipstorer.EncodeUTF8 = true;

                    v_perc = 0.0;
                    v_percstep = 100.0 / (double) this.v_reports.Count;
                    v_lastperc = v_percstep;

                    for (int k = 0; k < this.v_reports.Count; k++)
                    {
                        v_encrypted = v_cryptor.RandomString() + ".pdf";

                        v_report = (Spartacus.Reporting.Report) this.v_reports[k];

                        v_report.v_perc = v_perc;
                        v_report.v_percstep = v_percstep;
                        v_report.v_lastperc = v_lastperc;

                        v_report.Save(v_encrypted);
                        if (v_report.v_table.Rows.Count > 0)
                        {
                            v_zipstorer.AddFile(Spartacus.ThirdParty.ZipStorer.Compression.Deflate, v_encrypted, (string)p_filenames[k], "");
                            (new System.IO.FileInfo(v_encrypted)).Delete();
                        }

                        v_perc = v_lastperc;
                        v_lastperc += v_percstep;
                    }

                    v_zipstorer.Close();
                }
                else
                {
                    v_perc = 0.0;
                    v_percstep = 100.0 / (double) this.v_reports.Count;
                    v_lastperc = v_percstep;

                    for (int k = 0; k < this.v_reports.Count; k++)
                    {
                        v_report = (Spartacus.Reporting.Report) this.v_reports[k];

                        v_report.v_perc = v_perc;
                        v_report.v_percstep = v_percstep;
                        v_report.v_lastperc = v_lastperc;

                        v_report.Save((string)p_filenames[k]);

                        v_perc = v_lastperc;
                        v_lastperc += v_percstep;
                    }
                }
            }
            catch (Spartacus.Reporting.Exception e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Reporting.Exception("Erro ao gerar o pacote PDF de saída.", e);
            }
        }
Exemplo n.º 16
0
        public static AjaxReturn GetConnections()
        {
            AjaxReturn      v_return      = new AjaxReturn();
            ConnectionsData v_return_data = new ConnectionsData();
            Session         v_session     = (Session)System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"];

            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            if (v_session == null)
            {
                v_return.v_error    = true;
                v_return.v_error_id = 1;
                return(v_return);
            }

            System.Data.DataTable v_connections = v_session.v_omnidb_database.v_connection.Query("select * from connections where user_id = " + v_session.v_user_id + " order by dbt_st_name, conn_id", "Connections");
            System.Data.DataTable v_techs       = v_session.v_omnidb_database.v_connection.Query("select dbt_st_name from db_type", "Technologies");

            System.Collections.Generic.List <System.Collections.Generic.List <string> > v_connection_list = new System.Collections.Generic.List <System.Collections.Generic.List <string> >();
            System.Collections.Generic.List <string> v_tech_list    = new System.Collections.Generic.List <string>();
            System.Collections.Generic.List <string> v_conn_id_list = new System.Collections.Generic.List <string>();

            foreach (System.Data.DataRow v_tech in v_techs.Rows)
            {
                v_tech_list.Add(v_tech["dbt_st_name"].ToString());
            }

            int v_index = 0;

            foreach (System.Data.DataRow v_connection in v_connections.Rows)
            {
                System.Collections.Generic.List <string> v_connection_data_list = new System.Collections.Generic.List <string>();

                v_connection_data_list.Add(v_connection["dbt_st_name"].ToString());

                try
                {
                    v_connection_data_list.Add(v_cryptor.Decrypt(v_connection["server"].ToString()));
                    v_connection_data_list.Add(v_cryptor.Decrypt(v_connection["port"].ToString()));
                    v_connection_data_list.Add(v_cryptor.Decrypt(v_connection["service"].ToString()));
                    v_connection_data_list.Add(v_cryptor.Decrypt(v_connection["schema"].ToString()));
                    v_connection_data_list.Add(v_cryptor.Decrypt(v_connection["user"].ToString()));
                    v_connection_data_list.Add(v_cryptor.Decrypt(v_connection["password"].ToString()));
                }
                catch (Spartacus.Utils.Exception)
                {
                    v_connection_data_list.Add(v_connection["server"].ToString());
                    v_connection_data_list.Add(v_connection["port"].ToString());
                    v_connection_data_list.Add(v_connection["service"].ToString());
                    v_connection_data_list.Add(v_connection["schema"].ToString());
                    v_connection_data_list.Add(v_connection["user"].ToString());
                    v_connection_data_list.Add(v_connection["password"].ToString());
                }

                v_connection_data_list.Add("<img src='images/tab_close.png' class='img_ht' onclick='removeConnection(" + v_connection["conn_id"].ToString() + ")'/>" +
                                           "<img src='images/test.png' class='img_ht' onclick='testConnection(" + v_index + ")'/>");

                v_index++;

                v_connection_list.Add(v_connection_data_list);

                v_conn_id_list.Add(v_connection["conn_id"].ToString());
            }

            v_return_data.v_data         = v_connection_list;
            v_return_data.v_technologies = v_tech_list;
            v_return_data.v_conn_ids     = v_conn_id_list;

            v_return.v_data = v_return_data;
            return(v_return);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Refreshing session databases.
        /// </summary>
        public void RefreshDatabaseList()
        {
            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            v_databases.Clear();

            // Getting connections from OmniDB database and instantiating databases.
            System.Data.DataTable v_connections = v_omnidb_database.v_connection.Query("select * " +
                                                                                       "from connections " +
                                                                                       "where user_id=" + v_user_id + " " +
                                                                                       "order by dbt_st_name, conn_id",
                                                                                       "Connections");

            int v_count = 0;

            foreach (System.Data.DataRow v_connection in v_connections.Rows)
            {
                OmniDatabase.Generic v_database;
                string v_timeout;

                try
                {
                    v_database = OmniDatabase.Generic.InstantiateDatabase(
                        v_cryptor.Decrypt(v_connection["alias"].ToString()),
                        v_connection["conn_id"].ToString(),
                        v_connection["dbt_st_name"].ToString(),
                        v_cryptor.Decrypt(v_connection["server"].ToString()),
                        v_cryptor.Decrypt(v_connection["port"].ToString()),
                        v_cryptor.Decrypt(v_connection["service"].ToString()),
                        v_cryptor.Decrypt(v_connection["user"].ToString()),
                        v_cryptor.Decrypt(v_connection["password"].ToString()),
                        v_cryptor.Decrypt(v_connection["schema"].ToString())
                        );

                    v_timeout = System.Web.Configuration.WebConfigurationManager.AppSettings ["OmniDB.Timeout." + v_connection["dbt_st_name"].ToString()].ToString();

                    if (v_timeout != "-1")
                    {
                        v_database.v_connection.SetTimeout(Convert.ToInt32(v_timeout));
                    }

                    v_database.v_connection.SetExecuteSecurity(false);

                    AddDatabase(v_database);
                }
                catch (Spartacus.Utils.Exception)
                {
                    v_database = OmniDatabase.Generic.InstantiateDatabase(
                        v_connection ["alias"].ToString(),
                        v_connection ["conn_id"].ToString(),
                        v_connection ["dbt_st_name"].ToString(),
                        v_connection ["server"].ToString(),
                        v_connection ["port"].ToString(),
                        v_connection ["service"].ToString(),
                        v_connection ["user"].ToString(),
                        v_connection ["password"].ToString(),
                        v_connection ["schema"].ToString()
                        );

                    v_timeout = System.Web.Configuration.WebConfigurationManager.AppSettings ["OmniDB.Timeout." + v_connection["dbt_st_name"].ToString()].ToString();

                    if (v_timeout != "-1")
                    {
                        v_database.v_connection.SetTimeout(Convert.ToInt32(v_timeout));
                    }

                    AddDatabase(v_database);
                }

                v_count++;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Baseado em um DataTable preenchido, cria um XLSX para ser usado como template.
        /// </summary>
        /// <returns>Nome do arquivo a ser usado como template.</returns>
        /// <param name="p_freezeheader">Se deve congelar ou não a primeira linha da planilha.</param>
        /// <param name="p_showfilter">Se deve mostrar ou não o filtro na primeira linha da planilha.</param>
        private string CreateTemplate(bool p_freezeheader, bool p_showfilter)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            System.IO.FileInfo v_dst;
            string v_dstname;
            string v_column;
            string v_prefix;

            v_cryptor = new Spartacus.Utils.Cryptor("spartacus");

            v_dstname = v_cryptor.RandomString() + ".xlsx";
            v_dst = new System.IO.FileInfo(v_dstname);

            using (OfficeOpenXml.ExcelPackage v_package = new OfficeOpenXml.ExcelPackage(v_dst))
            {
                foreach (System.Data.DataTable v_table in this.v_set.Tables)
                {
                    OfficeOpenXml.ExcelWorksheet v_worksheet = v_package.Workbook.Worksheets.Add(v_table.TableName);

                    v_worksheet.View.ShowGridLines = true;

                    for (int k = 1; k <= v_table.Columns.Count; k++)
                    {
                        v_column = v_table.Columns[k-1].ColumnName.ToUpper();

                        if (v_column.Contains("_RE_"))
                            v_prefix = "*RE_";
                        else
                        {
                            if (v_column.Contains("_IN_"))
                                v_prefix = "*IN_";
                            else
                                v_prefix = "*ST_";
                        }

                        v_worksheet.Cells[1, k].Value = v_column;
                        v_worksheet.Cells[2, k].Value = v_prefix + v_column;
                    }

                    if (p_freezeheader)
                        v_worksheet.View.FreezePanes(2, 1);

                    if (p_showfilter)
                    {
                        v_worksheet.Tables.Add(v_worksheet.Cells["A1:" + OfficeOpenXml.ExcelCellBase.GetAddress(v_table.Rows.Count + 1, v_table.Columns.Count)], v_table.TableName);
                        v_worksheet.Tables[0].TableStyle = OfficeOpenXml.Table.TableStyles.None;
                        v_worksheet.Tables[0].ShowFilter = true;
                    }
                }

                v_package.Save();
            }

            return v_dstname;
        }
        /// <summary>
        /// Renderiza uma imagem no Bloco.
        /// Essa imagem precisa vir de um arquivo em disco.
        /// </summary>
        /// <param name="p_object">Objeto a ser renderizado.</param>
        /// <param name="p_posx">Posição X.</param>
        /// <param name="p_posy">Posição Y.</param>
        /// <param name="p_rightmargin">Margem direita.</param>
        /// <param name="p_pdf">Objeto PDF.</param>
        /// <param name="p_page">Página onde o objeto será renderizado.</param>
        private void RenderImage(Spartacus.Reporting.Object p_object, double p_posx, double p_posy, double p_rightmargin, PDFjet.NET.PDF p_pdf, PDFjet.NET.Page p_page)
        {
            PDFjet.NET.Image        v_image;
            System.IO.FileInfo      v_info;
            char[]                  v_ch;
            string[]                v_temp;
            Spartacus.Utils.Cryptor v_cryptor;
            string                  v_path;

            if (p_object.v_pdfobject == null)
            {
                v_ch    = new char[1];
                v_ch[0] = '.';

                v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                try
                {
                    v_path = v_cryptor.Decrypt(p_object.v_value);
                }
                catch (System.Exception)
                {
                    v_path = p_object.v_value;
                }

                v_info = new System.IO.FileInfo(v_path);
                if (v_info.Exists)
                {
                    v_temp = v_path.Split(v_ch);
                    switch (v_temp[v_temp.Length - 1].ToUpper())
                    {
                    case "BMP":
                        v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.BMP);
                        break;

                    case "JPG":
                        v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.JPG);
                        break;

                    case "JPEG":
                        v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.JPG);
                        break;

                    case "PNG":
                        v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.PNG);
                        break;

                    case "JET":
                        v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.JET);
                        break;

                    default:
                        v_image = null;
                        break;
                    }

                    if (v_image != null)
                    {
                        switch (p_object.v_align)
                        {
                        case Spartacus.Reporting.FieldAlignment.LEFT:
                            v_image.SetPosition(p_posx + p_object.v_posx, p_posy + p_object.v_posy);
                            break;

                        case Spartacus.Reporting.FieldAlignment.RIGHT:
                            v_image.SetPosition(p_page.GetWidth() - p_rightmargin - v_image.GetWidth(), p_posy + p_object.v_posy);
                            break;

                        case Spartacus.Reporting.FieldAlignment.CENTER:
                            v_image.SetPosition(p_posx + ((p_page.GetWidth() - p_rightmargin - p_posx) / 2) - (v_image.GetWidth() / 2), p_posy + p_object.v_posy);
                            break;

                        default:
                            break;
                        }
                        v_image.DrawOn(p_page);

                        p_object.v_pdfobject = v_image;
                    }
                }
            }
            else
            {
                ((PDFjet.NET.Image)p_object.v_pdfobject).DrawOn(p_page);
            }
        }
Exemplo n.º 20
0
        public static AjaxReturn SignIn(string p_username, string p_pwd)
        {
            AjaxReturn v_return = new AjaxReturn();

            Spartacus.Utils.Cryptor v_cryptor = new Spartacus.Utils.Cryptor("omnidb_spartacus");

            // Instantiating tool management database.
            OmniDatabase.Generic v_omnidb_database = OmniDatabase.Generic.InstantiateDatabase("", "0",
                                                                                              "sqlite",
                                                                                              "",
                                                                                              "",
                                                                                              System.Web.Configuration.WebConfigurationManager.AppSettings ["OmniDB.Database"].ToString(),
                                                                                              "",
                                                                                              "",
                                                                                              "");


            if (p_username == "admin")
            {
                string v_encrypted_pwd = System.IO.File.ReadAllText("config/admin.txt");

                string v_pwd;
                try {
                    v_pwd = v_cryptor.Decrypt(v_encrypted_pwd);

                    if (v_pwd == p_pwd)
                    {
                        Session v_session = new Session("-1", p_username, v_omnidb_database, "", "", "", "");
                        v_session.v_omnidb_version = System.Web.Configuration.WebConfigurationManager.AppSettings ["OmniDB.Version"].ToString();
                        System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"] = v_session;
                        v_return.v_data = true;
                    }
                    else
                    {
                        System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"] = null;
                        v_return.v_data = false;
                    }
                } catch (Spartacus.Utils.Exception) {
                    System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"] = null;
                    v_return.v_data = false;
                }

                return(v_return);
            }
            else
            {
                try {
                    // Querying user information.
                    System.Data.DataTable v_user_data = v_omnidb_database.v_connection.Query(
                        "select u.user_id,              " +
                        "       u.password,             " +
                        "       t.theme_id,             " +
                        "       t.theme_name,           " +
                        "       t.theme_type,           " +
                        "       u.editor_font_size      " +
                        "from users u,                  " +
                        "     themes t                  " +
                        " where u.theme_id = t.theme_id " +
                        "and u.user_name = '" + p_username + "' ", "db_data");

                    // If username exists, decrypt password.
                    if (v_user_data.Rows.Count > 0)
                    {
                        string v_pwd;
                        try {
                            v_pwd = v_cryptor.Decrypt(v_user_data.Rows [0] ["password"].ToString());
                        } catch (Spartacus.Utils.Exception) {
                            v_pwd = v_user_data.Rows [0] ["password"].ToString();
                        }

                        // If password is correct, set user as logged in, instantiate Session and return true.
                        if (v_pwd == p_pwd)
                        {
                            Session v_session = new Session(v_user_data.Rows [0] ["user_id"].ToString(), p_username, v_omnidb_database, v_user_data.Rows[0]["theme_name"].ToString(), v_user_data.Rows[0]["theme_type"].ToString(), v_user_data.Rows[0]["theme_id"].ToString(), v_user_data.Rows [0] ["editor_font_size"].ToString());
                            v_session.v_omnidb_version = System.Web.Configuration.WebConfigurationManager.AppSettings ["OmniDB.Version"].ToString();
                            System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"] = v_session;

                            if (!((Dictionary <string, Session>)System.Web.HttpContext.Current.Application["OMNIDB_SESSION_LIST"]).ContainsKey(v_session.v_user_id))
                            {
                                ((Dictionary <string, Session>)System.Web.HttpContext.Current.Application["OMNIDB_SESSION_LIST"]).Add(v_session.v_user_id, v_session);
                            }
                            else
                            {
                                ((Dictionary <string, Session>)System.Web.HttpContext.Current.Application["OMNIDB_SESSION_LIST"])[v_session.v_user_id] = v_session;
                            }

                            v_return.v_data = true;
                        }
                        else
                        {
                            System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"] = null;
                            v_return.v_data = false;
                        }
                    }
                    else
                    {
                        System.Web.HttpContext.Current.Session ["OMNIDB_SESSION"] = null;
                        v_return.v_data = false;
                    }
                } catch (Spartacus.Database.Exception e) {
                    v_return.v_error = true;
                    v_return.v_data  = e.v_message;
                }

                return(v_return);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>.
        /// </summary>
        /// <param name='p_type'>
        /// Indica se é um arquivo ou um diretório.
        /// </param>
        /// <param name='p_completename'>
        /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual.
        /// </param>
        /// <param name='p_encryptedname'>
        /// Se o nome do arquivo está criptografado ou não.
        /// </param>
        /// <param name='p_separator'>
        /// Separador de diretórios do caminho completo do arquivo.
        /// </param>
        public File(Spartacus.Utils.FileType p_type, string p_completename, bool p_encryptedname, Spartacus.Utils.PathSeparator p_separator)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            string v_completename;

            if (p_encryptedname)
            {
                try
                {
                    v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                    v_completename = v_cryptor.Decrypt(p_completename);
                }
                catch (System.Exception)
                {
                    v_completename = p_completename;
                }
            }
            else
                v_completename = p_completename;

            this.v_filetype = p_type;
            this.v_pathseparator = p_separator;
            this.v_name = this.GetBaseName(v_completename);
            this.v_extension = this.GetExtension(v_completename);
            this.v_path = this.GetPath(v_completename);
            this.v_size = -1;
            this.v_encoding = System.Text.Encoding.GetEncoding("utf-8");
            this.v_protected = false;
            this.v_hidden = this.GetHidden();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>.
        /// </summary>
        /// <param name='p_type'>
        /// Indica se é um arquivo ou um diretório.
        /// </param>
        /// <param name='p_completename'>
        /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual.
        /// </param>
        /// <param name='p_encryptedname'>
        /// Se o nome do arquivo está criptografado ou não.
        /// </param>
        /// <param name='p_lastwritedate'>
        /// Data da última modificação do arquivo ou diretório.
        /// </param>
        /// <param name='p_size'>
        /// Tamanho do arquivo.
        /// </param>
        /// <param name='p_encoding'>
        /// Codificação do arquivo.
        /// </param>
        public File(Spartacus.Utils.FileType p_type, string p_completename, bool p_encryptedname, System.DateTime p_lastwritedate, long p_size, System.Text.Encoding p_encoding)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            string v_completename;

            if (p_encryptedname)
            {
                try
                {
                    v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                    v_completename = v_cryptor.Decrypt(p_completename);
                }
                catch (System.Exception)
                {
                    v_completename = p_completename;
                }
            }
            else
                v_completename = p_completename;

            this.v_filetype = p_type;
            this.v_pathseparator = Spartacus.Utils.PathSeparator.SLASH;
            this.v_name = this.GetBaseName(v_completename);
            this.v_extension = this.GetExtension(v_completename);
            this.v_path = this.GetPath(v_completename);
            this.v_lastwritedate = p_lastwritedate;
            this.v_size = p_size;
            this.v_encoding = p_encoding;
            this.v_protected = false;
            this.v_hidden = this.GetHidden();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Substitui valores de células conforme configuração do cabeçalho, que deve estar na célula A1 e seguir formato específico.
        /// Cada planilha a princípio está em um arquivo diferente, e o arquivo resultante contém todas as planilhas de todos os arquivos.
        /// </summary>
        /// <returns>Nome do arquivo XLSX com cabeçalho aplicado em todas as planilhas.</returns>
        /// <param name="p_templatenames">Nome dos arquivo XLSX usados como templates.</param>
        private string ReplaceMarkup(System.Collections.ArrayList p_templatenames)
        {
            Spartacus.Utils.Cryptor v_cryptor;
            System.IO.FileInfo v_src;
            System.IO.FileInfo v_dst;
            string v_dstname;
            System.Data.DataTable v_table;
            string v_imagefilename;
            string v_line;
            string[] v_options;
            int k;
            System.Drawing.Bitmap v_image;
            OfficeOpenXml.Drawing.ExcelPicture v_picture;
            int v_col, v_row;
            int v_offset;
            int v_datastart = 1;
            int v_width, v_height;

            v_cryptor = new Spartacus.Utils.Cryptor("spartacus");

            v_dstname = v_cryptor.RandomString() + ".xlsx";
            v_dst = new System.IO.FileInfo(v_dstname);

            using (OfficeOpenXml.ExcelPackage v_package_dst = new OfficeOpenXml.ExcelPackage(v_dst))
            {
                for (int t = 0; t < p_templatenames.Count; t++)
                {
                    v_src = new System.IO.FileInfo((string)p_templatenames[t]);

                    using (OfficeOpenXml.ExcelPackage v_package_src = new OfficeOpenXml.ExcelPackage(v_src))
                    {
                        foreach (OfficeOpenXml.ExcelWorksheet v_worksheet_src in v_package_src.Workbook.Worksheets)
                        {
                            OfficeOpenXml.ExcelWorksheet v_worksheet = v_package_dst.Workbook.Worksheets.Add(v_worksheet_src.Name);
                            v_package_dst.Workbook.Styles.UpdateXml();

                            v_worksheet.View.ShowGridLines = v_worksheet_src.View.ShowGridLines;

                            v_table = this.v_set.Tables[v_worksheet.Name];
                            if (v_table != null && v_table.Rows.Count > 0)
                            {
                                using (System.IO.StringReader v_reader = new System.IO.StringReader(v_worksheet_src.Cells["A1"].Value.ToString()))
                                {
                                    /* EXEMPLO DE CONFIGURACAO DE MARKUP:
                                        TIPO|CAMPO|POSICAO|OPCIONAL
                                        CA||A1:AD12|
                                        CX|A:AD|11|30
                                        ST|titulo|A6|
                                        ST|filtro|A8|
                                        ST|ano|E2:J2|
                                        ST|empresa|E4:J4|
                                        FO|U10/S10|V7|
                                        TO|SUM(#)|M9|M12
                                        TO|SUBTOTAL(9,#)|M10|M12
                                        TO|SUMIF(#0,2,#1)|N10|O12;N12
                                        CF|#DBE5F1|A11:AD11|
                                        TA|A:AD|11|30
                                        IM|imagem|0:0|80;240
                                        TD|metodo,margem;qtdetotal,custototal,ajustetotal|Método,Margem,Qtde Total,Custo Total,Ajuste Total|F6
                                        FC|$W2=2|#D3D3D3|A:AD
                                     */

                                    v_line = string.Empty;
                                    k = 0;

                                    do
                                    {
                                        v_line = v_reader.ReadLine();

                                        if (v_line != null && k > 0)
                                        {
                                            v_options = v_line.Split('|');

                                            switch (v_options[0])
                                            {
                                                case "CA":
                                                    foreach (OfficeOpenXml.ExcelRangeBase v_cell in v_worksheet_src.Cells[v_options[2]])
                                                    {
                                                        // valor
                                                        v_worksheet.Cells[v_cell.Address].Value = v_worksheet_src.Cells[v_cell.Address].Value;

                                                        // alinhamento
                                                        v_worksheet.Cells[v_cell.Address].Style.VerticalAlignment = v_worksheet_src.Cells[v_cell.Address].Style.VerticalAlignment;
                                                        v_worksheet.Cells[v_cell.Address].Style.HorizontalAlignment = v_worksheet_src.Cells[v_cell.Address].Style.HorizontalAlignment;

                                                        // bordas
                                                        v_worksheet.Cells[v_cell.Address].Style.Border.Top.Style = v_worksheet_src.Cells[v_cell.Address].Style.Border.Top.Style;
                                                        v_worksheet.Cells[v_cell.Address].Style.Border.Left.Style = v_worksheet_src.Cells[v_cell.Address].Style.Border.Left.Style;
                                                        v_worksheet.Cells[v_cell.Address].Style.Border.Right.Style = v_worksheet_src.Cells[v_cell.Address].Style.Border.Right.Style;
                                                        v_worksheet.Cells[v_cell.Address].Style.Border.Bottom.Style = v_worksheet_src.Cells[v_cell.Address].Style.Border.Bottom.Style;

                                                        // padrão de cor de fundo
                                                        v_worksheet.Cells[v_cell.Address].Style.Fill.PatternType = v_worksheet_src.Cells[v_cell.Address].Style.Fill.PatternType;

                                                        // fonte
                                                        v_worksheet.Cells[v_cell.Address].Style.Font.Bold = v_worksheet_src.Cells[v_cell.Address].Style.Font.Bold;
                                                        v_worksheet.Cells[v_cell.Address].Style.Font.Italic = v_worksheet_src.Cells[v_cell.Address].Style.Font.Italic;
                                                        v_worksheet.Cells[v_cell.Address].Style.Font.Size = v_worksheet_src.Cells[v_cell.Address].Style.Font.Size;
                                                        v_worksheet.Cells[v_cell.Address].Style.Font.Family = v_worksheet_src.Cells[v_cell.Address].Style.Font.Family;
                                                        if (v_worksheet_src.Cells[v_cell.Address].Style.Font.Color.Theme == "0")
                                                            v_worksheet.Cells[v_cell.Address].Style.Font.Color.SetColor(System.Drawing.Color.White);

                                                        // formato numérico
                                                        v_worksheet.Cells[v_cell.Address].Style.Numberformat.Format = v_worksheet_src.Cells[v_cell.Address].Style.Numberformat.Format;

                                                        // quebrar texto automaticamente
                                                        v_worksheet.Cells[v_cell.Address].Style.WrapText = v_worksheet_src.Cells[v_cell.Address].Style.WrapText;

                                                        // comentários
                                                        if (v_worksheet_src.Cells[v_cell.Address].Comment != null)
                                                        {
                                                            v_worksheet.Cells[v_cell.Address].AddComment(v_worksheet_src.Cells[v_cell.Address].Comment.Text, v_worksheet_src.Cells[v_cell.Address].Comment.Author);
                                                            v_worksheet.Cells[v_cell.Address].Comment.AutoFit = true;
                                                        }
                                                    }
                                                    break;
                                                case "CX":
                                                    v_row = int.Parse(v_options[2]);
                                                    for (int i = 1; i <= v_row; i++)
                                                        v_worksheet.Row(i).Height = v_worksheet_src.Row(i).Height;
                                                    v_col = int.Parse(v_options[3]);
                                                    for (int j = 1; j <= v_col; j++)
                                                        v_worksheet.Column(j).Width = v_worksheet_src.Column(j).Width;
                                                    // passando informação para demais configurações
                                                    v_datastart = int.Parse(v_options[2]);
                                                    // passando informação para SejExcel
                                                    v_worksheet.Cells["A1"].Value = v_options[2];
                                                    break;
                                                case "ST":
                                                    v_worksheet.Cells[v_options[2]].Value = System.Net.WebUtility.HtmlDecode(v_table.Rows[0][v_options[1]].ToString());
                                                    if (v_options[2].Contains(':'))
                                                        v_worksheet.Cells[v_options[2]].Merge = true;
                                                    break;
                                                case "FO":
                                                    v_worksheet.Cells[v_options[2]].Formula = v_options[1];
                                                    break;
                                                case "IM":
                                                    try
                                                    {
                                                        v_imagefilename = v_cryptor.Decrypt(v_table.Rows[0][v_options[1]].ToString());
                                                    }
                                                    catch (Spartacus.Utils.Exception)
                                                    {
                                                        v_imagefilename = "";
                                                    }
                                                    if (v_imagefilename != "")
                                                    {
                                                        try
                                                        {
                                                            v_image = new System.Drawing.Bitmap(v_imagefilename);
                                                            v_picture = null;
                                                            if (v_image != null)
                                                            {
                                                                v_picture = v_worksheet.Drawings.AddPicture(v_imagefilename, v_image);
                                                                v_picture.SetPosition(int.Parse(v_options[2].Split(':')[0]), int.Parse(v_options[2].Split(':')[1]));

                                                                if (v_options[3].Split(';').Length > 1)
                                                                {
                                                                    v_height = int.Parse(v_options[3].Split(';')[0]);
                                                                    v_width = v_height * v_image.Width / v_image.Height;
                                                                    if (v_width > int.Parse(v_options[3].Split(';')[1]))
                                                                    {
                                                                        v_width = int.Parse(v_options[3].Split(';')[1]);
                                                                        v_height = v_width * v_image.Height / v_image.Width;
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    v_height = int.Parse(v_options[3].Split(';')[0]);
                                                                    v_width = v_height * v_image.Width / v_image.Height;
                                                                }
                                                                v_picture.SetSize(v_width, v_height);
                                                            }
                                                        }
                                                        catch (System.Exception)
                                                        {
                                                        }
                                                    }
                                                    break;
                                                case "TO":
                                                    v_worksheet.Cells [v_options[2]].Value = "";
                                                    if (v_options[3].Split(';').Length > 1)
                                                    {
                                                        k = 0;
                                                        v_worksheet.Cells [v_options[2]].Formula = v_options[1];
                                                        foreach (string v_dest in v_options[3].Split(';'))
                                                        {
                                                            v_row = v_worksheet.Cells[v_dest].Start.Row;
                                                            v_col = v_worksheet.Cells[v_dest].Start.Column;
                                                            if (v_options[1] != "")
                                                                v_worksheet.Cells [v_options[2]].Formula = v_worksheet.Cells [v_options[2]].Formula.Replace("#" + k.ToString(), v_worksheet.Cells [v_row, v_col].Address + ":" + v_worksheet.Cells [v_table.Rows.Count + v_row - 1, v_col].Address);
                                                            else
                                                                v_worksheet.Cells [v_options[2]].Formula = "SUM(" + v_worksheet.Cells [v_row, v_col].Address + ":" + v_worksheet.Cells [v_table.Rows.Count + v_row - 1, v_col].Address + ")";
                                                            k++;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        v_row = v_worksheet.Cells[v_options[3]].Start.Row;
                                                        v_col = v_worksheet.Cells[v_options[3]].Start.Column;
                                                        if (v_options[1] != "")
                                                            v_worksheet.Cells [v_options[2]].Formula = v_options[1].Replace("#", v_worksheet.Cells [v_row, v_col].Address + ":" + v_worksheet.Cells [v_table.Rows.Count + v_row - 1, v_col].Address);
                                                        else
                                                            v_worksheet.Cells [v_options[2]].Formula = "SUM(" + v_worksheet.Cells [v_row, v_col].Address + ":" + v_worksheet.Cells [v_table.Rows.Count + v_row - 1, v_col].Address + ")";
                                                    }
                                                    break;
                                                case "CF":
                                                    v_worksheet.Cells[v_options[2]].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml(v_options[1]));
                                                    break;
                                                case "TA":
                                                    v_row = int.Parse(v_options[2]);
                                                    for (int i = 1; i <= v_row; i++)
                                                        v_worksheet.Row(i).Height = v_worksheet_src.Row(i).Height;
                                                    v_col = int.Parse(v_options[3]);
                                                    for (int j = 1; j <= v_col; j++)
                                                        v_worksheet.Column(j).Width = v_worksheet_src.Column(j).Width;
                                                    v_worksheet.View.FreezePanes(v_row + 1, 1);
                                                    v_worksheet.Tables.Add(v_worksheet.Cells[v_options[1].Split(':')[0] + v_options[2] + ":" + v_options[1].Split(':')[1] + (v_table.Rows.Count + v_row).ToString()], v_worksheet_src.Name);
                                                    v_worksheet.Tables[0].TableStyle = OfficeOpenXml.Table.TableStyles.None;
                                                    v_worksheet.Tables[0].ShowFilter = true;
                                                    // passando informação para demais configurações
                                                    v_datastart = int.Parse(v_options[2]);
                                                    // passando informação para SejExcel
                                                    v_worksheet.Cells["A1"].Value = v_options[2];
                                                    break;
                                                case "TD":
                                                    v_worksheet.Cells[v_options[3]].LoadFromDataTable(this.CreatePivotTable(v_table, v_options[1], v_options[2]), true, OfficeOpenXml.Table.TableStyles.Medium23);
                                                    v_worksheet.Tables[v_table.TableName.Replace(' ', '_') + "_PIVOT"].ShowTotal = true;
                                                    v_offset = v_options[1].Split(';')[0].Split(',').Length;
                                                    for (int j = 0; j < v_options[1].Split(';')[1].Split(',').Length; j++)
                                                        v_worksheet.Tables[v_table.TableName.Replace(' ', '_') + "_PIVOT"].Columns[j + v_offset].TotalsRowFunction = OfficeOpenXml.Table.RowFunctions.Sum;
                                                    break;
                                                case "FC":
                                                    var v_rule = v_worksheet.ConditionalFormatting.AddExpression(new OfficeOpenXml.ExcelAddress(v_options[3].Split(':')[0] + (v_datastart + 1).ToString() + ":" + v_options[3].Split(':')[1] + (v_table.Rows.Count + v_datastart).ToString()));
                                                    v_rule.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                                                    v_rule.Style.Fill.BackgroundColor.Color = System.Drawing.ColorTranslator.FromHtml(v_options[2]);
                                                    v_rule.Formula = v_options[1];
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }

                                        k++;
                                    }
                                    while (v_line != null);
                                }
                            }
                        }
                    }
                }

                v_package_dst.Save();
            }

            return v_dstname;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Salva todos os relatórios em arquivos separados.
        /// </summary>
        /// <param name="p_filenames">Lista de nomes de arquivos, que deve possuir o mesmo número de elementos.</param>
        /// <param name="p_compress">Gerar arquivo ZIP com todos os arquivos PDF.</param>
        /// <param name="p_outfilename">Nome do arquivo ZIP de saída.</param>
        public void SaveSplitted(System.Collections.Generic.List <string> p_filenames, bool p_compress, string p_outfilename)
        {
            Spartacus.ThirdParty.ZipStorer v_zipstorer;
            Spartacus.Utils.Cryptor        v_cryptor;
            string v_encrypted;

            Spartacus.Reporting.Report v_report;
            double v_perc, v_percstep, v_lastperc;

            try
            {
                if (p_compress)
                {
                    v_cryptor = new Spartacus.Utils.Cryptor("spartacus");

                    v_zipstorer            = Spartacus.ThirdParty.ZipStorer.Create(p_outfilename, "Generated with ZipStorer (by Jaime Olivares) embedded in Spartacus (by William Ivanski)");
                    v_zipstorer.EncodeUTF8 = true;

                    v_perc     = 0.0;
                    v_percstep = 100.0 / (double)this.v_reports.Count;
                    v_lastperc = v_percstep;

                    for (int k = 0; k < this.v_reports.Count; k++)
                    {
                        v_encrypted = v_cryptor.RandomString() + ".pdf";

                        v_report = this.v_reports[k];

                        v_report.v_perc     = v_perc;
                        v_report.v_percstep = v_percstep;
                        v_report.v_lastperc = v_lastperc;

                        v_report.Save(v_encrypted);
                        if (v_report.v_table.Rows.Count > 0)
                        {
                            v_zipstorer.AddFile(Spartacus.ThirdParty.ZipStorer.Compression.Deflate, v_encrypted, p_filenames[k], "");
                            (new System.IO.FileInfo(v_encrypted)).Delete();
                        }

                        v_perc      = v_lastperc;
                        v_lastperc += v_percstep;
                    }

                    v_zipstorer.Close();
                }
                else
                {
                    v_perc     = 0.0;
                    v_percstep = 100.0 / (double)this.v_reports.Count;
                    v_lastperc = v_percstep;

                    for (int k = 0; k < this.v_reports.Count; k++)
                    {
                        v_report = this.v_reports[k];

                        v_report.v_perc     = v_perc;
                        v_report.v_percstep = v_percstep;
                        v_report.v_lastperc = v_lastperc;

                        v_report.Save(p_filenames[k]);

                        v_perc      = v_lastperc;
                        v_lastperc += v_percstep;
                    }
                }
            }
            catch (Spartacus.Reporting.Exception e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Reporting.Exception("Erro ao gerar o pacote PDF de saída.", e);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Renderiza uma imagem no Bloco.
        /// Essa imagem precisa vir de um arquivo em disco.
        /// </summary>
        /// <param name="p_object">Objeto a ser renderizado.</param>
        /// <param name="p_posx">Posição X.</param>
        /// <param name="p_posy">Posição Y.</param>
        /// <param name="p_rightmargin">Margem direita.</param>
        /// <param name="p_pdf">Objeto PDF.</param>
        /// <param name="p_page">Página onde o objeto será renderizado.</param>
        private void RenderImage(Spartacus.Reporting.Object p_object, double p_posx, double p_posy, double p_rightmargin, PDFjet.NET.PDF p_pdf, PDFjet.NET.Page p_page)
        {
            PDFjet.NET.Image v_image;
            System.IO.FileInfo v_info;
            char[] v_ch;
            string[] v_temp;
            Spartacus.Utils.Cryptor v_cryptor;
            string v_path;

            if (p_object.v_pdfobject == null)
            {
                v_ch = new char[1];
                v_ch [0] = '.';

                v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                try
                {
                    v_path = v_cryptor.Decrypt(p_object.v_value);
                }
                catch (System.Exception)
                {
                    v_path = p_object.v_value;
                }

                v_info = new System.IO.FileInfo(v_path);
                if (v_info.Exists)
                {
                    v_temp = v_path.Split(v_ch);
                    switch (v_temp[v_temp.Length - 1].ToUpper())
                    {
                        case "BMP":
                            v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.BMP);
                            break;
                        case "JPG":
                            v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.JPG);
                            break;
                        case "JPEG":
                            v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.JPG);
                            break;
                        case "PNG":
                            v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.PNG);
                            break;
                        case "JET":
                            v_image = new PDFjet.NET.Image(p_pdf, new System.IO.FileStream(v_path, System.IO.FileMode.Open, System.IO.FileAccess.Read), PDFjet.NET.ImageType.JET);
                            break;
                        default:
                            v_image = null;
                            break;
                    }

                    if (v_image != null)
                    {
                        switch (p_object.v_align)
                        {
                            case Spartacus.Reporting.FieldAlignment.LEFT:
                                v_image.SetPosition(p_posx + p_object.v_posx, p_posy + p_object.v_posy);
                                break;
                            case Spartacus.Reporting.FieldAlignment.RIGHT:
                                v_image.SetPosition(p_page.GetWidth() - p_rightmargin - v_image.GetWidth(), p_posy + p_object.v_posy);
                                break;
                            case Spartacus.Reporting.FieldAlignment.CENTER:
                                v_image.SetPosition(p_posx + ((p_page.GetWidth() - p_rightmargin - p_posx) / 2) - (v_image.GetWidth() / 2), p_posy + p_object.v_posy);
                                break;
                            default:
                                break;
                        }
                        v_image.DrawOn(p_page);

                        p_object.v_pdfobject = v_image;
                    }
                }
            }
            else
                ((PDFjet.NET.Image)p_object.v_pdfobject).DrawOn(p_page);
        }