public MyUserLoginArgs(Exception error, MyUserInfo userInfo, bool alreadyLoggedIn)
     : this()
 {
     Error = error;
     UserInfo = userInfo;
     AlreadyLoggedIn = alreadyLoggedIn;
 }
Beispiel #2
0
		public static void RunExample(String[] arg)
		{
			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();
			
				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				//Add AES128 as default cipher in the session config store
				System.Collections.Hashtable config=new System.Collections.Hashtable();
				config.Add("cipher.s2c", "aes128-cbc,3des-cbc");
				config.Add("cipher.c2s", "aes128-cbc,3des-cbc");
				session.setConfig(config);

				//Connect to remote SSH server
				session.connect();			

				//Open a new Shell channel on the SSH session
				Channel channel=session.openChannel("shell");

				//Redirect standard I/O to the SSH channel
				channel.setInputStream(Console.OpenStandardInput());
				channel.setOutputStream(Console.OpenStandardOutput());

				//Connect the channel
				channel.connect();

				Console.WriteLine("-- Shell channel is connected using the {0} cipher", 
					session.getCipher());

				//Wait till channel is closed
				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}

				//Disconnect from remote server
				channel.disconnect();
				session.disconnect();			

			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
        public static void Main(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                //Get the private key filename from the user
                Console.WriteLine("Please choose your private key file...");
                String file = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)");
                Console.WriteLine("You chose "+file+".");

                //Add the identity file to JSch
                jsch.addIdentity(file);

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Open a new Shell channel on the SSH session
                Channel channel=session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                //Wait till channel is closed
                while(!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                OpenFileDialog chooser = new OpenFileDialog();
                chooser.Title ="Choose your privatekey(ex. ~/.ssh/id_dsa)";
                //chooser.setFileHidingEnabled(false);
                DialogResult returnVal = chooser.ShowDialog();
                if(returnVal == DialogResult.OK)
                {
                    Console.WriteLine("You chose "+
                        chooser.FileName+".");
                    jsch.addIdentity(chooser.FileName
                        //			 , "passphrase"
                        );
                }
                else
                {
                    Console.WriteLine("Error getting key file...");
                    return;
                }
                InputForm inForm = new InputForm();
                inForm.Text = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName+"@localhost";

                if (inForm.PromptForInput())
                {
                    String host = inForm.textBox1.Text;
                    String user=host.Substring(0, host.IndexOf('@'));
                    host=host.Substring(host.IndexOf('@')+1);

                    Session session=jsch.getSession(user, host, 22);

                    // username and passphrase will be given via UserInfo interface.
                    UserInfo ui=new MyUserInfo();
                    session.setUserInfo(ui);
                    session.connect();

                    Channel channel=session.openChannel("shell");

                    channel.setInputStream(Console.OpenStandardInput());
                    channel.setOutputStream(Console.OpenStandardOutput());

                    channel.connect();
                }
                inForm.Close();

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #5
0
 /// <summary>
 /// 构造方法
 /// </summary>
 /// <param name="host"></param>
 /// <param name="user"></param>
 /// <param name="pwd"></param>
 public SftpHelper(string host, string user, string pwd)
 {
     string[] arr = host.Split(':');
     string ip = arr[0];
     int port = 22;
     if (arr.Length > 1) port = Int32.Parse(arr[1]);
     JSch jsch = new JSch();
     m_session = jsch.getSession(user, ip, port);
     MyUserInfo ui = new MyUserInfo();
     ui.setPassword(pwd);
     m_session.setUserInfo(ui);
 }
Beispiel #6
0
		public static void RunExample(String[] arg)
		{
			int port;

			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();

				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);
				session.connect();

				//Get from user the remote host and remote host port
				String foo = InputForm.GetUserInput("Enter host and port", "host:port");
				host=foo.Substring(0, foo.IndexOf(':'));
				port=int.Parse(foo.Substring(foo.IndexOf(':')+1));

				Console.WriteLine("System.{in,out} will be forwarded to "+
					host+":"+port+".");
				Channel channel=session.openChannel("direct-tcpip");
				((ChannelDirectTCPIP)channel).setInputStream(Console.OpenStandardInput());
				((ChannelDirectTCPIP)channel).setOutputStream(Console.OpenStandardOutput());
				((ChannelDirectTCPIP)channel).setHost(host);
				((ChannelDirectTCPIP)channel).setPort(port);
				channel.connect();

				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}
				channel.disconnect();
				session.disconnect();
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
		}
        public static void Main(String[] arg)
        {
            int port;

            try
            {
                //Create a new JSch instance
                JSch jsch=new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                //Get from user the local port, remote host and remote host port
                String foo = InputForm.GetUserInput("Enter -L port:host:hostport","port:host:hostport");
                int lport=int.Parse(foo.Substring(0, foo.IndexOf(':')));
                foo=foo.Substring(foo.IndexOf(':')+1);
                String rhost=foo.Substring(0, foo.IndexOf(':'));
                int rport=int.Parse(foo.Substring(foo.IndexOf(':')+1));

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                Console.WriteLine("localhost:"+lport+" -> "+rhost+":"+rport);

                //Set port forwarding on the opened session
                session.setPortForwardingL(lport, rhost, rport);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #8
0
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                OpenFileDialog chooser = new OpenFileDialog();
                chooser.Title = "Choose your known_hosts(ex. ~/.ssh/known_hosts)";
                //chooser.setFileHidingEnabled(false);
                DialogResult returnVal = chooser.ShowDialog();
                if(returnVal == DialogResult.OK)
                {
                    Console.WriteLine("You chose "+
                        chooser.FileName+".");
                    jsch.setKnownHosts(chooser.FileName);
                }
                else
                {
                    Console.WriteLine("Error getting host file...");
                    return;
                }

                HostKeyRepository hkr=jsch.getHostKeyRepository();
                HostKey[] hks=hkr.getHostKey();
                if(hks!=null)
                {
                    Console.WriteLine("Host keys in "+hkr.getKnownHostsRepositoryID());
                    for(int i=0; i<hks.Length; i++)
                    {
                        HostKey hk=hks[i];
                        Console.WriteLine(hk.getHost()+" "+
                            hk.getType()+" "+
                            hk.getFingerPrint(jsch));
                    }
                    Console.WriteLine("");
                }

                InputForm inForm = new InputForm();
                inForm.Text = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName+"@localhost";

                if (inForm.PromptForInput())
                {
                    String host = inForm.textBox1.Text;
                    String user=host.Substring(0, host.IndexOf('@'));
                    host=host.Substring(host.IndexOf('@')+1);

                    Session session=jsch.getSession(user, host, 22);

                    // username and password will be given via UserInfo interface.
                    UserInfo ui=new MyUserInfo();
                    session.setUserInfo(ui);

                    session.connect();

                    HostKey hk=session.getHostKey();
                    Console.WriteLine("HostKey: "+
                        hk.getHost()+" "+
                        hk.getType()+" "+
                        hk.getFingerPrint(jsch));

                    Channel channel=session.openChannel("shell");

                    channel.setInputStream(Console.OpenStandardInput());
                    channel.setOutputStream(Console.OpenStandardOutput());

                    channel.connect();
                }
                inForm.Close();

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
        /// <summary>Page_Load</summary>
        /// <param name="sender">object</param>
        /// <param name="e">EventArgs</param>
        protected async void Page_Load(object sender, EventArgs e)
        {
            string code  = Request.QueryString["code"];
            string state = Request.QueryString["state"];

            try
            {
                string response = "";

                if (state == this.State) // CSRF(XSRF)対策のstateの検証は重要
                {
                    response = await OAuth2AndOIDCClient.GetAccessTokenByCodeAsync(
                        new Uri("http://localhost:63359/MultiPurposeAuthSite/OAuth2BearerToken"),
                        OAuth2AndOIDCParams.ClientID, OAuth2AndOIDCParams.ClientSecret,
                        HttpUtility.HtmlEncode("http://localhost:9999/WebForms_Sample/Aspx/Auth/OAuthAuthorizationCodeGrantClient.aspx"), code);

                    // 汎用認証サイトはOIDCをサポートしたのでid_tokenを取得し、検証可能。
                    Base64UrlTextEncoder        base64UrlEncoder = new Base64UrlTextEncoder();
                    Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(response);

                    string        sub    = "";
                    string        nonce  = "";
                    List <string> roles  = null;
                    List <string> scopes = null;
                    JObject       jobj   = null;

                    // access_tokenの検証
                    if (JwtToken.Verify(dic["access_token"], out sub, out roles, out scopes, out jobj))
                    {
                        // id_tokenの検証
                        if (IdToken.Verify(dic["id_token"], "", "", "", out sub, out nonce, out jobj) && nonce == this.Nonce)
                        {
                            // ログインに成功
                            // /userinfoエンドポイントにアクセスする場合
                            response = await OAuth2AndOIDCClient.GetUserInfoAsync(
                                new Uri("http://localhost:63359/MultiPurposeAuthSite/userinfo"), dic["access_token"]);

                            FormsAuthentication.RedirectFromLoginPage(sub, false);
                            MyUserInfo ui = new MyUserInfo(sub, Request.UserHostAddress);
                            UserInfoHandle.SetUserInformation(ui);

                            return;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                }


                // ログインに失敗
                Response.Redirect("../Start/login.aspx");
            }
            finally
            {
                this.ClearExLoginsParams();
            }
        }
Beispiel #10
0
        public static void Main(String[] arg)
        {
            if(arg.Length!=2)
            {
                Console.WriteLine("usage: java ScpFrom user@remotehost:file1 file2");
                return;
            }

            try
            {
                String user=arg[0].Substring(0, arg[0].IndexOf('@'));
                arg[0]=arg[0].Substring(arg[0].IndexOf('@')+1);
                String host=arg[0].Substring(0, arg[0].IndexOf(':'));
                String rfile=arg[0].Substring(arg[0].IndexOf(':')+1);
                String lfile=arg[1];

                String prefix=null;
                if(Directory.Exists(lfile))
                {
                    prefix=lfile+Path.DirectorySeparatorChar;
                }

                JSch jsch=new JSch();
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                // exec 'scp -f rfile' remotely
                String command="scp -f "+rfile;
                Channel channel=session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs=channel.getOutputStream();
                Stream ins=channel.getInputStream();

                channel.connect();

                byte[] buf=new byte[1024];

                // send '\0'
                buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();

                while(true)
                {
                    int c=checkAck(ins);
                    if(c!='C')
                    {
                        break;
                    }

                    // read '0644 '
                    ins.Read(buf, 0, 5);

                    int filesize=0;
                    while(true)
                    {
                        ins.Read(buf, 0, 1);
                        if(buf[0]==' ')break;
                        filesize=filesize*10+(buf[0]-'0');
                    }

                    String file=null;
                    for(int i=0;;i++)
                    {
                        ins.Read(buf, i, 1);
                        if(buf[i]==(byte)0x0a)
                        {
                            file=Util.getString(buf, 0, i);
                            break;
                        }
                    }

                    //Console.WriteLine("filesize="+filesize+", file="+file);

                    // send '\0'
                    buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();

                    // read a content of lfile
                    FileStream fos=File.OpenWrite(prefix==null ?
                    lfile :
                        prefix+file);
                    int foo;
                    while(true)
                    {
                        if(buf.Length<filesize) foo=buf.Length;
                        else foo=filesize;
                        ins.Read(buf, 0, foo);
                        fos.Write(buf, 0, foo);
                        filesize-=foo;
                        if(filesize==0) break;
                    }
                    fos.Close();

                    byte[] tmp=new byte[1];

                    if(checkAck(ins)!=0)
                    {
                        Environment.Exit(0);
                    }

                    // send '\0'
                    buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();
                }
                Environment.Exit(0);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public async Task<ActionResult>  Create(RegisterViewModel userViewModel, string RoleId, [Bind(Include="Name")] ApplicationUser kUser, string[] selectedKPIs)
        {
          
            if(selectedKPIs != null)
            {
                kUser.KPIs = new List<KPI>();
                foreach(var kpi in selectedKPIs){
                    var kpiToAdd = context.KPIs.Find(int.Parse(kpi));
                    kUser.KPIs.Add(kpiToAdd);

                }
            }
            
            if (ModelState.IsValid)
            {
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var userinfo = new MyUserInfo()
                {
                    FirstName = userViewModel.FirstName,
                    LastName = userViewModel.LastName
                };
                var user = new ApplicationUser();
                user.UserName = userViewModel.UserName;
                user.Email = userViewModel.Email;
                user.MyUserInfo = userinfo;
                var adminresult =  UserManager.Create(user, userViewModel.Password);
         
                context.Users.Add(user);
                context.SaveChanges();
              
    
                //Add User Admin to Role Admin
                if (adminresult.Succeeded)
                {
                    if (!String.IsNullOrEmpty(RoleId))
                    {
                        //Find Role Admin
                        var role = await RoleManager.FindByIdAsync(RoleId);
                        var result = await UserManager.AddToRoleAsync(user.Id, role.Name);
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First().ToString());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First().ToString());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                    return View();

                }
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                return View();
            }
        }
Beispiel #12
0
 /// <summary>コンストラクタ</summary>
 /// <param name="screenId">スクリーンID</param>
 /// <param name="controlId">コントロールID</param>
 /// <param name="methodName">メソッド名</param>
 /// <param name="actionType">アクションタイプ</param>
 /// <param name="user">ユーザ情報</param>
 /// <remarks>
 /// コンストラクタは継承されないので、派生先で呼び出す必要がある。
 /// ※ コンストラクタの実行順は、基本クラス→派生クラスの順
 /// ※ VB.NET では、MyBase.New() を派生クラスのコンストラクタから呼ぶ。
 /// 自由に利用できる。
 /// </remarks>
 public MyParameterValue(string screenId, string controlId, string methodName, string actionType, MyUserInfo user)
     : base(screenId, controlId, methodName, actionType)
 {
     // ユーザ情報
     this._user = user;
 }
        public static void Main(String[] arg)
        {
            try
            {
                //Get the "known hosts" filename from the user
                Console.WriteLine("Please select your 'known_hosts' from the poup window...");
                String file = InputForm.GetFileFromUser("Choose your known_hosts(ex. ~/.ssh/known_hosts)");
                Console.WriteLine("You chose "+file+".");
                //Create a new JSch instance
                JSch jsch=new JSch();
                //Set the known hosts file
                jsch.setKnownHosts(file);

                //Get the KnownHosts repository from JSchs
                HostKeyRepository hkr=jsch.getHostKeyRepository();

                //Print all known hosts and keys
                HostKey[] hks=hkr.getHostKey();
                HostKey hk;
                if(hks!=null)
                {
                    Console.WriteLine();
                    Console.WriteLine("Host keys in "+hkr.getKnownHostsRepositoryID()+":");
                    for(int i=0; i<hks.Length; i++)
                    {
                        hk=hks[i];
                        Console.WriteLine(hk.getHost()+" "+
                            hk.getType()+" "+
                            hk.getFingerPrint(jsch));
                    }
                    Console.WriteLine("");
                }

                //Now connect to the remote server...

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Print the host key info
                //of the connected server:
                hk=session.getHostKey();
                Console.WriteLine("HostKey: "+
                    hk.getHost()+" "+
                    hk.getType()+" "+
                    hk.getFingerPrint(jsch));

                //Open a new Shell channel on the SSH session
                Channel channel=session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                Console.WriteLine("-- Shell channel is connected using the {0} cipher",
                    session.getCipher());

                //Wait till channel is closed
                while(!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #14
0
        private void sftp_login()
        {
            JSch jsch = new JSch();

            host = ((frmMain)this.Tag).ftpHost();
            UN = ((frmMain)this.Tag).ftpUser();
            port = ((frmMain)this.Tag).ftpPort();

            Session session = jsch.getSession(UN, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);

            session.setPort(port);

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpc = (ChannelSftp)channel;
        }
Beispiel #15
0
        public static void RunExample(String[] arg)
        {
            try
            {
                //Create a new JSch instance
                JSch jsch = new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");

                String host = InputForm.GetUserInput("Enter username@hostname",
                                                     Environment.UserName + "@localhost");

                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                //Create a new SSH session
                Session session = jsch.getSession(user, host, 22);

                String proxy = InputForm.GetUserInput("Enter proxy server",
                                                      "hostname:port");

                string proxy_host = proxy.Substring(0, proxy.IndexOf(':'));
                int    proxy_port = int.Parse(proxy.Substring(proxy.IndexOf(':') + 1));

                session.setProxy(new ProxyHTTP(proxy_host, proxy_port));

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Open a new Shell channel on the SSH session
                Channel channel = session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                Console.WriteLine("-- Shell channel is connected using the {0} cipher",
                                  session.getCipher());

                //Wait till channel is closed
                while (!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        // 2009/09/01 & 2009/09/25-start

        /// <summary>ユーザ情報を取得する</summary>
        private void GetUserInfo()
        {
            // メンバへセット
            this.UserInfo = MyBaseController.GetUserInfo2();
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var UserManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));
            var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context.Get <ApplicationDbContext>()));

            // Configure validation logic for usernames
            UserManager.UserValidator = new UserValidator <ApplicationUser>(UserManager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            var myinfo = new MyUserInfo()
            {
                FirstName = "Fulano",
                LastName  = "Silva"
            };
            string roleAdministrador = "Administrador";
            string senha             = "123456";

            //Create Role Admin if it does not exist
            if (!RoleManager.RoleExists(roleAdministrador))
            {
                var roleresult = RoleManager.Create(new IdentityRole(roleAdministrador));
            }

            //Create User=Admin with password=123456
            var usuario = new ApplicationUser();

            usuario.UserName   = "******";
            usuario.HomeTown   = "Cuiabá";
            usuario.MyUserInfo = myinfo;
            usuario.Email      = "*****@*****.**";
            var adminresult = UserManager.Create(usuario, senha);

            //Add User Admin to Role Admin
            if (adminresult.Succeeded)
            {
                var result = UserManager.AddToRole(usuario.Id, roleAdministrador);
            }


            // Configure validation logic for passwords
            UserManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
            };

            // Configure user lockout defaults
            UserManager.UserLockoutEnabledByDefault          = true;
            UserManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            UserManager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            UserManager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            UserManager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            UserManager.EmailService = new EmailService();
            UserManager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                UserManager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(UserManager);
        }
Beispiel #18
0
        /// <summary>
        ///生成商品文案
        /// </summary>
        /// <param name="userid">The userid.</param>
        /// <param name="taskid">The taskid.</param>
        /// <param name="templateText">The template text.</param>
        /// <param name="data">The data.</param>
        /// <param name="group">The group.</param>
        /// <returns>true if XXXX, false otherwise.</returns>
        private bool BuildShareText(string loginToken, int userid, int taskid, string templateText, List <GoodsModel> data, weChatGroupModel group, string appkey, string appsecret, out JoinGoodsList joinList, Action <weChatShareTextModel> result = null, bool isJoinImage = false)
        {
            joinList = null;
            if (data == null)
            {
                return(false);
            }
            weChatShareTextModel share = new weChatShareTextModel()
            {
                userid = userid,
                taskid = taskid,
                status = -1,
                title  = group.title
            };

            if (isJoinImage)
            {
                joinList = new JoinGoodsList();
            }

            List <int> ids = new List <int>();

            List <JoinGoodsInfo> imageList = new List <JoinGoodsInfo>();

            foreach (var item in data)
            {
                if (item.goodsPrice - item.couponPrice <= 0)
                {
                    continue;
                }
                string url = GlobalConfig.couponUrl;
                url           += "?src=ht_hot&activityId=" + item.couponId;
                url           += "&itemId=" + item.goodsId.Replace("=", "");
                url           += "&pid=" + (string.IsNullOrEmpty(group.pid) ? "mm_33648229_22032774_73500078" : group.pid);
                item.shareLink = url;
                string shortUrl = string.Empty;
                //将淘口令改成pid,2017-04-07 修改,淘口令改到分享时生产
                string tpwd = (string.IsNullOrEmpty(group.pid) ? "mm_33648229_22032774_73500078" : group.pid);// "[二合一淘口令]";// HotTaoApiService.Instance.taobao_wireless_share_tpwd_create(item.goodsMainImgUrl, item.shareLink, item.goodsName, appkey, appsecret);
                string text = templateText;

                if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(tpwd))
                {
                    if (text.Contains("[商品标题]"))
                    {
                        text = text.Replace("[商品标题]", item.goodsName);
                    }
                    if (text.Contains("[商品价格]"))
                    {
                        text = text.Replace("[商品价格]", item.goodsPrice.ToString());
                    }
                    if (text.Contains("[券后价格]"))
                    {
                        text = text.Replace("[券后价格]", (item.goodsPrice - item.couponPrice).ToString());
                    }
                    if (text.Contains("[来源]"))
                    {
                        text = text.Replace("[来源]", item.goodsSupplier);
                    }
                    if (text.Contains("[销量]"))
                    {
                        text = text.Replace("[销量]", item.goodsSalesAmount.ToString());
                    }
                    if (text.Contains("[优惠券价格]"))
                    {
                        text = text.Replace("[优惠券价格]", item.couponPrice.ToString());
                    }
                    if (text.Contains("[分隔符]"))
                    {
                        text = text.Replace("[分隔符]", "-----------------");
                    }
                    if (text.Contains("[简介描述]"))
                    {
                        text = text.Replace("[简介描述]", string.IsNullOrEmpty(item.goodsIntro) ? "" : item.goodsIntro);
                    }

                    if (text.Contains("[商品地址]"))
                    {
                        text = text.Replace("[商品地址]", item.goodsDetailUrl);
                    }

                    if (text.Contains("[优惠券地址]"))
                    {
                        text = text.Replace("[优惠券地址]", item.couponUrl);
                    }
                }
                else
                {
                    share.status = 2;
                }
                share.goodsid = Convert.ToInt32(item.id);
                share.text    = text;
                share.tpwd    = tpwd;
                share.field1  = item.goodslocatImgPath;

                if (isJoinImage)
                {
                    string _url = GlobalConfig.couponUrl;
                    _url += "?src=ht_hot&activityId=" + item.couponId;
                    _url += "&itemId=" + item.goodsId.Replace("=", "");
                    _url += "&pid=" + tpwd;
                    var _tpwd = "";
                    share.field2 = _tpwd;

                    bool isLogin = true;

                    Tuple <string, string> resultTuple = TaobaoHelper.GetGaoYongToken(item.goodsDetailUrl, item.goodsId, tpwd, MyUserInfo.GetTbToken(), MyUserInfo.cookies, out isLogin);
                    string shareText = "";
                    if (resultTuple != null)
                    {
                        if (isLogin)
                        {
                            shareText = resultTuple.Item1;
                        }
                    }
                    //商品数据
                    joinList.collectionGoodsList.Add(new CollectionGoods()
                    {
                        goodsId           = item.goodsId,
                        goodsName         = item.goodsName,
                        price             = item.goodsPrice,
                        discountAmount    = item.couponPrice,
                        goodsPromotionUrl = _url,
                        goodsPrimaryImg   = item.goodsMainImgUrl,
                        shareText         = shareText
                    });
                    //图片
                    joinList.ImageList.Add(new JoinGoodsInfo()
                    {
                        GoodsName   = item.goodsName,
                        GoodsPrice  = item.goodsPrice,
                        CouponPrice = item.couponPrice,
                        imagePath   = item.goodslocatImgPath,
                        GoodsIntro  = item.goodsIntro
                    });
                }
                share.field6 = isJoinImage ? 1 : 0;
                share.field3 = group.id.ToString();
                AddUserWechatSharetext(share);
                result?.Invoke(share);
            }
            if (isJoinImage)
            {
                joinList.TaskId = taskid;
                joinList.id     = Convert.ToInt32(group.id);
            }
            return(true);
        }
Beispiel #19
0
        /// <summary>ロード イベント</summary>
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // ddlDap
            this.ddlDap.Items.Add(new ComboBoxItem("SQL Server / SQL Client", "SQL"));
            this.ddlDap.Items.Add(new ComboBoxItem("Multi-DB / OLEDB.NET", "OLE"));
            this.ddlDap.Items.Add(new ComboBoxItem("Multi-DB / ODCB.NET", "ODB"));
            this.ddlDap.Items.Add(new ComboBoxItem("Oracle / ODP.NET", "ODP"));
            this.ddlDap.Items.Add(new ComboBoxItem("DB2 / DB2.NET", "DB2"));
            this.ddlDap.Items.Add(new ComboBoxItem("HiRDB / HiRDB-DP", "HIR"));
            this.ddlDap.Items.Add(new ComboBoxItem("MySQL Cnn/NET", "MCN"));
            this.ddlDap.Items.Add(new ComboBoxItem("PostgreSQL / Npgsql", "NPS"));
            this.ddlDap.SelectedIndex = 0;

            // ddlMode1
            this.ddlMode1.Items.Add(new ComboBoxItem("個別Dao", "individual"));
            this.ddlMode1.Items.Add(new ComboBoxItem("共通Dao", "common"));
            this.ddlMode1.Items.Add(new ComboBoxItem("自動生成Dao(更新のみ)", "generate"));
            this.ddlMode1.SelectedIndex = 0;

            // ddlMode2
            this.ddlMode2.Items.Add(new ComboBoxItem("静的クエリ", "static"));
            this.ddlMode2.Items.Add(new ComboBoxItem("動的クエリ", "dynamic"));
            this.ddlMode2.SelectedIndex = 0;

            // ddlIso
            this.ddlIso.Items.Add(new ComboBoxItem("ノットコネクト", "NC"));
            this.ddlIso.Items.Add(new ComboBoxItem("ノートランザクション", "NT"));
            this.ddlIso.Items.Add(new ComboBoxItem("ダーティリード", "RU"));
            this.ddlIso.Items.Add(new ComboBoxItem("リードコミット", "RC"));
            this.ddlIso.Items.Add(new ComboBoxItem("リピータブルリード", "RR"));
            this.ddlIso.Items.Add(new ComboBoxItem("シリアライザブル", "SZ"));
            this.ddlIso.Items.Add(new ComboBoxItem("スナップショット", "SS"));
            this.ddlIso.Items.Add(new ComboBoxItem("デフォルト", "DF"));
            this.ddlIso.SelectedIndex = 1;

            // WSでは使用しない(設定できないので)。
            this.ddlIso.IsEnabled = false;

            // ddlExRollback
            this.ddlExRollback.Items.Add(new ComboBoxItem("正常時", "-"));
            this.ddlExRollback.Items.Add(new ComboBoxItem("業務例外", "Business"));
            this.ddlExRollback.Items.Add(new ComboBoxItem("システム例外", "System"));
            this.ddlExRollback.Items.Add(new ComboBoxItem("その他、一般的な例外", "Other"));
            this.ddlExRollback.Items.Add(new ComboBoxItem("業務例外への振替", "Other-Business"));
            this.ddlExRollback.Items.Add(new ComboBoxItem("システム例外への振替", "Other-System"));
            this.ddlExRollback.SelectedIndex = 0;

            // ddlOrderColumn
            this.ddlOrderColumn.Items.Add(new ComboBoxItem("c1", "c1"));
            this.ddlOrderColumn.Items.Add(new ComboBoxItem("c2", "c2"));
            this.ddlOrderColumn.Items.Add(new ComboBoxItem("c3", "c3"));
            this.ddlOrderColumn.SelectedIndex = 0;

            // ddlOrderSequence
            this.ddlOrderSequence.Items.Add(new ComboBoxItem("ASC", "A"));
            this.ddlOrderSequence.Items.Add(new ComboBoxItem("DESC", "D"));
            this.ddlOrderSequence.SelectedIndex = 0;

            // ユーザ情報
            this.myUserInfo = new MyUserInfo("userName", Environment.MachineName);

            // 呼出し制御部品
            this.CallCtrl = new CallController("");

            // スレッドプール
            ThreadPool.SetMinThreads(10, 10); // 待機状態スレッド数
            ThreadPool.SetMaxThreads(10, 10); // 最大スレッド起動数
        }
 /// <summary>コンストラクタ</summary>
 public AuthParameterValue(string screenId, string controlId, string methodName, string actionType, MyUserInfo user, string password)
     : base(screenId, controlId, methodName, actionType, user)
 {
     // Baseのコンストラクタに引数を渡すために必要。
     // パスワードを設定する。
     this.Password = password;
 }
Beispiel #21
0
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch = new JSch();

                InputForm inForm = new InputForm();
                inForm.Text          = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName + "@localhost";

                if (!inForm.PromptForInput())
                {
                    Console.WriteLine("Cancelled");
                    return;
                }
                String host = inForm.textBox1.Text;
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                session.connect();

                Channel channel = session.openChannel("sftp");
                channel.connect();
                ChannelSftp c = (ChannelSftp)channel;

                Stream     ins  = Console.OpenStandardInput();
                TextWriter outs = Console.Out;

                ArrayList cmds = new ArrayList();
                byte[]    buf  = new byte[1024];
                int       i;
                String    str;
                int       level = 0;

                while (true)
                {
                    outs.Write("sftp> ");
                    cmds.Clear();
                    i = ins.Read(buf, 0, 1024);
                    if (i <= 0)
                    {
                        break;
                    }

                    i--;
                    if (i > 0 && buf[i - 1] == 0x0d)
                    {
                        i--;
                    }
                    //str=Util.getString(buf, 0, i);
                    //Console.WriteLine("|"+str+"|");
                    int s = 0;
                    for (int ii = 0; ii < i; ii++)
                    {
                        if (buf[ii] == ' ')
                        {
                            if (ii - s > 0)
                            {
                                cmds.Add(Util.getString(buf, s, ii - s));
                            }
                            while (ii < i)
                            {
                                if (buf[ii] != ' ')
                                {
                                    break;
                                }
                                ii++;
                            }
                            s = ii;
                        }
                    }
                    if (s < i)
                    {
                        cmds.Add(Util.getString(buf, s, i - s));
                    }
                    if (cmds.Count == 0)
                    {
                        continue;
                    }

                    String cmd = (String)cmds[0];
                    if (cmd.Equals("quit"))
                    {
                        c.disconnect(); // c.quit();
                        break;
                    }
                    if (cmd.Equals("exit"))
                    {
                        c.disconnect(); // .exit();
                        break;
                    }
                    if (cmd.Equals("rekey"))
                    {
                        session.rekey();
                        continue;
                    }
                    if (cmd.Equals("compression"))
                    {
                        if (cmds.Count < 2)
                        {
                            outs.WriteLine("compression level: " + level);
                            continue;
                        }
                        try
                        {
                            level = int.Parse((String)cmds[1]);
                            Hashtable config = new Hashtable();
                            if (level == 0)
                            {
                                config.Add("compression.s2c", "none");
                                config.Add("compression.c2s", "none");
                            }
                            else
                            {
                                config.Add("compression.s2c", "zlib,none");
                                config.Add("compression.c2s", "zlib,none");
                            }
                            session.setConfig(config);
                        }
                        catch {}                       //(Exception e){}
                        continue;
                    }
                    if (cmd.Equals("cd") || cmd.Equals("lcd"))
                    {
                        if (cmds.Count < 2)
                        {
                            continue;
                        }
                        String path = (String)cmds[1];
                        try
                        {
                            if (cmd.Equals("cd"))
                            {
                                c.cd(path);
                            }
                            else
                            {
                                c.lcd(path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
                    {
                        if (cmds.Count < 2)
                        {
                            continue;
                        }
                        String path = (String)cmds[1];
                        try
                        {
                            if (cmd.Equals("rm"))
                            {
                                c.rm(path);
                            }
                            else if (cmd.Equals("rmdir"))
                            {
                                c.rmdir(path);
                            }
                            else
                            {
                                c.mkdir(path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
                    {
                        if (cmds.Count != 3)
                        {
                            continue;
                        }
                        String path = (String)cmds[2];
                        int    foo  = 0;
                        if (cmd.Equals("chmod"))
                        {
                            byte[] bar = Util.getBytes((String)cmds[1]);
                            int    k;
                            for (int j = 0; j < bar.Length; j++)
                            {
                                k = bar[j];
                                if (k < '0' || k > '7')
                                {
                                    foo = -1; break;
                                }
                                foo <<= 3;
                                foo  |= (k - '0');
                            }
                            if (foo == -1)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            try{ foo = int.Parse((String)cmds[1]); }
                            catch {}                           //(Exception e){continue;}
                        }
                        try
                        {
                            if (cmd.Equals("chgrp"))
                            {
                                c.chgrp(foo, path);
                            }
                            else if (cmd.Equals("chown"))
                            {
                                c.chown(foo, path);
                            }
                            else if (cmd.Equals("chmod"))
                            {
                                c.chmod(foo, path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("pwd") || cmd.Equals("lpwd"))
                    {
                        str  = (cmd.Equals("pwd")?"Remote":"Local");
                        str += " working directory: ";
                        if (cmd.Equals("pwd"))
                        {
                            str += c.pwd();
                        }
                        else
                        {
                            str += c.lpwd();
                        }
                        outs.WriteLine(str);
                        continue;
                    }
                    if (cmd.Equals("ls") || cmd.Equals("dir"))
                    {
                        String path = ".";
                        if (cmds.Count == 2)
                        {
                            path = (String)cmds[1];
                        }
                        try
                        {
                            ArrayList vv = c.ls(path);
                            if (vv != null)
                            {
                                for (int ii = 0; ii < vv.Count; ii++)
                                {
                                    object obj = vv[ii];
                                    if (obj is ChannelSftp.LsEntry)
                                    {
                                        outs.WriteLine(vv[ii]);
                                    }
                                }
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("lls") || cmd.Equals("ldir"))
                    {
                        String path = ".";
                        if (cmds.Count == 2)
                        {
                            path = (String)cmds[1];
                        }
                        try
                        {
                            //java.io.File file=new java.io.File(path);
                            if (!File.Exists(path))
                            {
                                outs.WriteLine(path + ": No such file or directory");
                                continue;
                            }
                            if (Directory.Exists(path))
                            {
                                String[] list = Directory.GetDirectories(path);
                                for (int ii = 0; ii < list.Length; ii++)
                                {
                                    outs.WriteLine(list[ii]);
                                }
                                continue;
                            }
                            outs.WriteLine(path);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                        continue;
                    }
                    if (cmd.Equals("get") ||
                        cmd.Equals("get-resume") || cmd.Equals("get-append") ||
                        cmd.Equals("put") ||
                        cmd.Equals("put-resume") || cmd.Equals("put-append")
                        )
                    {
                        if (cmds.Count != 2 && cmds.Count != 3)
                        {
                            continue;
                        }
                        String p1 = (String)cmds[1];
                        //	  String p2=p1;
                        String p2 = ".";
                        if (cmds.Count == 3)
                        {
                            p2 = (String)cmds[2];
                        }
                        try
                        {
                            SftpProgressMonitor monitor = new MyProgressMonitor();
                            if (cmd.StartsWith("get"))
                            {
                                int mode = ChannelSftp.OVERWRITE;
                                if (cmd.Equals("get-resume"))
                                {
                                    mode = ChannelSftp.RESUME;
                                }
                                else if (cmd.Equals("get-append"))
                                {
                                    mode = ChannelSftp.APPEND;
                                }
                                c.get(p1, p2, monitor, mode);
                            }
                            else
                            {
                                int mode = ChannelSftp.OVERWRITE;
                                if (cmd.Equals("put-resume"))
                                {
                                    mode = ChannelSftp.RESUME;
                                }
                                else if (cmd.Equals("put-append"))
                                {
                                    mode = ChannelSftp.APPEND;
                                }
                                c.put(p1, p2, monitor, mode);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
                    {
                        if (cmds.Count != 3)
                        {
                            continue;
                        }
                        String p1 = (String)cmds[1];
                        String p2 = (String)cmds[2];
                        try
                        {
                            if (cmd.Equals("rename"))
                            {
                                c.rename(p1, p2);
                            }
                            else
                            {
                                c.symlink(p1, p2);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("stat") || cmd.Equals("lstat"))
                    {
                        if (cmds.Count != 2)
                        {
                            continue;
                        }
                        String    p1    = (String)cmds[1];
                        SftpATTRS attrs = null;
                        try
                        {
                            if (cmd.Equals("stat"))
                            {
                                attrs = c.stat(p1);
                            }
                            else
                            {
                                attrs = c.lstat(p1);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        if (attrs != null)
                        {
                            outs.WriteLine(attrs);
                        }
                        else
                        {
                        }
                        continue;
                    }
                    if (cmd.Equals("version"))
                    {
                        outs.WriteLine("SFTP protocol version " + c.version());
                        continue;
                    }
                    if (cmd.Equals("help") || cmd.Equals("?"))
                    {
                        outs.WriteLine(help);
                        continue;
                    }
                    outs.WriteLine("unimplemented command: " + cmd);
                }
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #22
0
		public static void RunExample(String[] arg)
		{
			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();
			
				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				
				String host = InputForm.GetUserInput("Enter username@hostname",
											Environment.UserName+"@localhost");
				
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);
				
				String proxy=InputForm.GetUserInput("Enter proxy server",
					"hostname:port");

				string proxy_host=proxy.Substring(0, proxy.IndexOf(':'));
				int proxy_port=int.Parse(proxy.Substring(proxy.IndexOf(':')+1));

				session.setProxy(new ProxyHTTP(proxy_host, proxy_port));

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				//Connect to remote SSH server
				session.connect();			

				//Open a new Shell channel on the SSH session
				Channel channel=session.openChannel("shell");

				//Redirect standard I/O to the SSH channel
				channel.setInputStream(Console.OpenStandardInput());
				channel.setOutputStream(Console.OpenStandardOutput());

				//Connect the channel
				channel.connect();

				Console.WriteLine("-- Shell channel is connected using the {0} cipher", 
					session.getCipher());

				//Wait till channel is closed
				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}

				//Disconnect from remote server
				channel.disconnect();
				session.disconnect();			

			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
		}
 /// <summary>コンストラクタ</summary>
 public AsyncProcessingServiceParameterValue(string screenId, string controlId, string methodName, string actionType, MyUserInfo user)
     : base(screenId, controlId, methodName, actionType, user)
 {
     // Baseのコンストラクタに引数を渡すために必要。
 }
Beispiel #24
0
        public static void Main(String[] arg)
        {
            if (arg.Length != 2)
            {
                Console.WriteLine("usage: java ScpTo file1 user@remotehost:file2");
                Environment.Exit(-1);
            }

            try
            {
                String lfile = arg[0];
                String user  = arg[1].Substring(0, arg[1].IndexOf('@'));
                arg[1] = arg[1].Substring(arg[1].IndexOf('@') + 1);
                String host  = arg[1].Substring(0, arg[1].IndexOf(':'));
                String rfile = arg[1].Substring(arg[1].IndexOf(':') + 1);

                JSch    jsch    = new JSch();
                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();


                // exec 'scp -t rfile' remotely
                String  command = "scp -p -t " + rfile;
                Channel channel = session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs = channel.getOutputStream();
                Stream ins  = channel.getInputStream();

                channel.connect();

                byte[] tmp = new byte[1];

                if (checkAck(ins) != 0)
                {
                    Environment.Exit(0);
                }

                // send "C0644 filesize filename", where filename should not include '/'

                int filesize = (int)(new FileInfo(lfile)).Length;
                command = "C0644 " + filesize + " ";
                if (lfile.LastIndexOf('/') > 0)
                {
                    command += lfile.Substring(lfile.LastIndexOf('/') + 1);
                }
                else
                {
                    command += lfile;
                }
                command += "\n";
                byte[] buff = Util.getBytes(command);
                outs.Write(buff, 0, buff.Length); outs.Flush();

                if (checkAck(ins) != 0)
                {
                    Environment.Exit(0);
                }

                // send a content of lfile
                FileStream fis = File.OpenRead(lfile);
                byte[]     buf = new byte[1024];
                while (true)
                {
                    int len = fis.Read(buf, 0, buf.Length);
                    if (len <= 0)
                    {
                        break;
                    }
                    outs.Write(buf, 0, len); outs.Flush();
                    Console.Write("#");
                }

                // send '\0'
                buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();
                Console.Write(".");

                if (checkAck(ins) != 0)
                {
                    Environment.Exit(0);
                }
                Console.WriteLine("OK");
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #25
0
 /// <summary>コンストラクタ</summary>
 public _3TierParameterValue(string screenId, string controlId, string methodName, string actionType, MyUserInfo user)
     : base(screenId, controlId, methodName, actionType, user)
 {
     // Baseのコンストラクタに引数を渡すために必要。
 }
Beispiel #26
0
        ///SFTP Code Starting here
        ///hell yeah
        private void sftp_login()
        {
            JSch jsch = new JSch();

            String host = ftpHost();
            String user = ftpUser();

            Session session = jsch.getSession(user, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);

            session.setPort(ftpPort());

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpc = (ChannelSftp)channel;
            //sftpc = (ChannelSftp)channel;
        }
Beispiel #27
0
        /// <summary>Main</summary>
        static void Main(string[] args)
        {
            // コマンドラインをバラす関数がある。
            List <string> valsLst = null;
            Dictionary <string, string> argsDic = null;

            PubCmnFunction.GetCommandArgs('/', out argsDic, out valsLst);

            // 引数クラス値(B層実行用)
            string     screenId   = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string     controlId  = "-";
            string     actionType = "SQL"; // argsDic["/DAP"] + "%" + argsDic["/MODE1"] + "%" + argsDic["/MODE2"] + "%" + argsDic["/EXROLLBACK"];
            MyUserInfo myUserInfo = new MyUserInfo("userName", "ipAddress");

            // B層クラス
            LayerB layerB = new LayerB();

            // ↓B層実行:主キー値を全て検索(ORDER BY 主キー)-----------------------------------------------------

            // 引数クラスを生成
            VoidParameterValue selectPkListParameterValue = new VoidParameterValue(screenId, controlId, "SelectPkList", actionType, myUserInfo);

            // B層呼出し
            SelectPkListReturnValue selectPkReturnValue = (SelectPkListReturnValue)layerB.DoBusinessLogic(selectPkListParameterValue, DbEnum.IsolationLevelEnum.ReadCommitted);

            // 実行結果確認
            if (selectPkReturnValue.ErrorFlag == true)
            {
                // 結果(業務続行可能なエラー)
                string error = "ErrorMessageID:" + selectPkReturnValue.ErrorMessageID + "\r\n";
                error += "ErrorMessage:" + selectPkReturnValue.ErrorMessage + "\r\n";
                error += "ErrorInfo:" + selectPkReturnValue.ErrorInfo + "\r\n";

                Console.WriteLine(error);
                Console.ReadKey();
                return; //バッチ処理終了
            }

            // 戻り値取得
            ArrayList pkList = selectPkReturnValue.PkList;

            // ↑B層実行:主キー値を全て検索(ORDER BY 主キー)-----------------------------------------------------

            int recordCount      = pkList.Count;                                                                                      // 全レコード数
            int initialIndex     = 0;                                                                                                 // 処理開始インデックス ※ todo:リラン時に途中から再開する場合は初期値を変更する
            int transactionCount = Convert.ToInt32(Math.Ceiling(((double)(recordCount - initialIndex)) / INTERMEDIATE_COMMIT_COUNT)); // 更新B層実行回数

            for (int transactionIndex = 0; transactionIndex < transactionCount; transactionIndex++)
            {
                ArrayList subPkList;       // 主キー一覧(1トランザクション分)
                int       subPkStartIndex; // 主キー(1トランザクション分)の開始位置
                int       subPkCount;      // 主キー数(1トランザクション分)

                // 取り出す主キーの開始、数を取得
                subPkStartIndex = initialIndex + (transactionIndex * INTERMEDIATE_COMMIT_COUNT);
                if (subPkStartIndex + INTERMEDIATE_COMMIT_COUNT - 1 > recordCount - 1)
                {
                    subPkCount = (recordCount - initialIndex) % INTERMEDIATE_COMMIT_COUNT;
                }
                else
                {
                    subPkCount = INTERMEDIATE_COMMIT_COUNT;
                }

                // 主キー一覧(1トランザクション分)を取り出す
                subPkList = new ArrayList();
                subPkList.AddRange(pkList.GetRange(subPkStartIndex, subPkCount));

                // ↓B層実行:バッチ処理を実行(1トランザクション分)----------------------------------------------------

                // 引数クラスを生成
                ExecuteBatchProcessParameterValue executeBatchProcessParameterValue = new ExecuteBatchProcessParameterValue(screenId, controlId, "ExecuteBatchProcess", actionType, myUserInfo);
                executeBatchProcessParameterValue.SubPkList = subPkList;

                // B層呼出し
                VoidReturnValue executeBatchProcessReturnValue = (VoidReturnValue)layerB.DoBusinessLogic(executeBatchProcessParameterValue, DbEnum.IsolationLevelEnum.ReadCommitted);

                // 実行結果確認
                if (selectPkReturnValue.ErrorFlag == true)
                {
                    // 結果(業務続行可能なエラー)
                    string error = "ErrorMessageID:" + selectPkReturnValue.ErrorMessageID + "\r\n";
                    error += "ErrorMessage:" + selectPkReturnValue.ErrorMessage + "\r\n";
                    error += "ErrorInfo:" + selectPkReturnValue.ErrorInfo + "\r\n";

                    Console.WriteLine(error);
                    Console.ReadKey();
                    return; // バッチ処理終了
                }

                // ↑B層実行:バッチ処理を実行(1トランザクション分)----------------------------------------------------
            }
        }
Beispiel #28
0
		public static void RunExample(String[] arg)
		{
			try
			{
				JSch jsch=new JSch();

				InputForm inForm = new InputForm();
				inForm.Text = "Enter username@hostname";
				inForm.textBox1.Text = Environment.UserName+"@localhost"; 

				if (!inForm.PromptForInput())
				{
					Console.WriteLine("Cancelled");
					return;
				}
				String host = inForm.textBox1.Text;
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				session.connect();

				Channel channel=session.openChannel("sftp");
				channel.connect();
				ChannelSftp c=(ChannelSftp)channel;

				Stream ins=Console.OpenStandardInput();
				TextWriter outs=Console.Out;

				ArrayList cmds=new ArrayList();
				byte[] buf=new byte[1024];
				int i;
				String str;
				int level=0;

				while(true)
				{
					outs.Write("sftp> ");
					cmds.Clear();
					i=ins.Read(buf, 0, 1024);
					if(i<=0)break;

					i--;
					if(i>0 && buf[i-1]==0x0d)i--;
					//str=Util.getString(buf, 0, i);
					//Console.WriteLine("|"+str+"|");
					int s=0;
					for(int ii=0; ii<i; ii++)
					{
						if(buf[ii]==' ')
						{
							if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); }
							while(ii<i){if(buf[ii]!=' ')break; ii++;}
							s=ii;
						}
					}
					if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); }
					if(cmds.Count==0)continue;

					String cmd=(String)cmds[0];
					if(cmd.Equals("quit"))
					{
						c.quit();
						break;
					}
					if(cmd.Equals("exit"))
					{
						c.exit();
						break;
					}
					if(cmd.Equals("rekey"))
					{
						session.rekey();
						continue;
					}
					if(cmd.Equals("compression"))
					{
						if(cmds.Count<2)
						{
							outs.WriteLine("compression level: "+level);
							continue;
						}
						try
						{
							level=int.Parse((String)cmds[1]);
							Hashtable config=new Hashtable();
							if(level==0)
							{
								config.Add("compression.s2c", "none");
								config.Add("compression.c2s", "none");
							}
							else
							{
								config.Add("compression.s2c", "zlib,none");
								config.Add("compression.c2s", "zlib,none");
							}
							session.setConfig(config);
						}
						catch{}//(Exception e){}
						continue;
					}
					if(cmd.Equals("cd") || cmd.Equals("lcd"))
					{
						if(cmds.Count<2) continue;
						String path=(String)cmds[1];
						try
						{
							if(cmd.Equals("cd")) c.cd(path);
							else c.lcd(path);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
					{
						if(cmds.Count<2) continue;
						String path=(String)cmds[1];
						try
						{
							if(cmd.Equals("rm")) c.rm(path);
							else if(cmd.Equals("rmdir")) c.rmdir(path);
							else c.mkdir(path);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
					{
						if(cmds.Count!=3) continue;
						String path=(String)cmds[2];
						int foo=0;
						if(cmd.Equals("chmod"))
						{
							byte[] bar=Util.getBytes((String)cmds[1]);
							int k;
							for(int j=0; j<bar.Length; j++)
							{
								k=bar[j];
								if(k<'0'||k>'7'){foo=-1; break;}
								foo<<=3;
								foo|=(k-'0');
							}
							if(foo==-1)continue;
						}
						else
						{
							try{foo=int.Parse((String)cmds[1]);}
							catch{}//(Exception e){continue;}
						}
						try
						{
							if(cmd.Equals("chgrp")){ c.chgrp(foo, path); }
							else if(cmd.Equals("chown")){ c.chown(foo, path); }
							else if(cmd.Equals("chmod")){ c.chmod(foo, path); }
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("pwd") || cmd.Equals("lpwd"))
					{
						str=(cmd.Equals("pwd")?"Remote":"Local");
						str+=" working directory: ";
						if(cmd.Equals("pwd")) str+=c.pwd();
						else str+=c.lpwd();
						outs.WriteLine(str);
						continue;
					}
					if(cmd.Equals("ls") || cmd.Equals("dir"))
					{
						String path=".";
						if(cmds.Count==2) path=(String)cmds[1];
						try
						{
							ArrayList vv=c.ls(path);
							if(vv!=null)
							{
								for(int ii=0; ii<vv.Count; ii++)
								{
									object obj = vv[ii];
									if(obj is ChannelSftp.LsEntry)
										outs.WriteLine(vv[ii]);
								}
							}
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("lls") || cmd.Equals("ldir"))
					{
						String path=".";
						if(cmds.Count==2) path=(String)cmds[1];
						try
						{
							//java.io.File file=new java.io.File(path);
							if(!File.Exists(path))
							{
								outs.WriteLine(path+": No such file or directory");
								continue; 
							}
							if(Directory.Exists(path))
							{
								String[] list=Directory.GetDirectories(path);
								for(int ii=0; ii<list.Length; ii++)
								{
									outs.WriteLine(list[ii]);
								}
								continue;
							}
							outs.WriteLine(path);
						}
						catch(Exception e)
						{
							Console.WriteLine(e);
						}
						continue;
					}
					if(cmd.Equals("get") || 
						cmd.Equals("get-resume") || cmd.Equals("get-append") || 
						cmd.Equals("put") || 
						cmd.Equals("put-resume") || cmd.Equals("put-append")
						)
					{
						if(cmds.Count!=2 && cmds.Count!=3) continue;
						String p1=(String)cmds[1];
						//	  String p2=p1;
						String p2=".";
						if(cmds.Count==3)p2=(String)cmds[2];
						try
						{
							SftpProgressMonitor monitor=new MyProgressMonitor();
							if(cmd.StartsWith("get"))
							{
								int mode=ChannelSftp.OVERWRITE;
								if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; }
								else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; } 
								c.get(p1, p2, monitor, mode);
							}
							else
							{ 
								int mode=ChannelSftp.OVERWRITE;
								if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; }
								else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; } 
								c.put(p1, p2, monitor, mode); 
							}
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
					{
						if(cmds.Count!=3) continue;
						String p1=(String)cmds[1];
						String p2=(String)cmds[2];
						try
						{
							if(cmd.Equals("rename")) c.rename(p1, p2);
							else c.symlink(p1, p2);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("stat") || cmd.Equals("lstat"))
					{
						if(cmds.Count!=2) continue;
						String p1=(String)cmds[1];
						SftpATTRS attrs=null;
						try
						{
							if(cmd.Equals("stat")) attrs=c.stat(p1);
							else attrs=c.lstat(p1);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						if(attrs!=null)
						{
							outs.WriteLine(attrs);
						}
						else
						{
						}
						continue;
					}
					if(cmd.Equals("version"))
					{
						outs.WriteLine("SFTP protocol version "+c.version());
						continue;
					}
					if(cmd.Equals("help") || cmd.Equals("?"))
					{
						outs.WriteLine(help);
						continue;
					}
					outs.WriteLine("unimplemented command: "+cmd);
				}
				session.disconnect();
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}			
		}
Beispiel #29
0
        //Logging in to the client
        private void btnLogin_Click(object sender, EventArgs e)
        {
            btnCreate.Enabled   = false;
            btnLogin.Enabled    = false;
            txtUsername.Enabled = false;
            txtPassword.Enabled = false;
            bool            authorized = false;
            MySqlConnection conn       = new MySqlConnection();
            JSch            jsch       = new JSch();
            string          host       = "secs.oakland.edu";
            string          user       = "******";
            string          pass       = "******";
            int             sshPort    = 22;
            Session         session    = jsch.getSession(user, host, sshPort);

            session.setHost(host);
            session.setPassword(pass);
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);
            try
            {
                session.connect();
                session.setPortForwardingL(3306, "localhost", 3306);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                txtUsername.Enabled = true;
                txtPassword.Enabled = true;
                btnLogin.Enabled    = true;
                btnCreate.Enabled   = true;
            }


            if (session.isConnected())
            {
                try
                {
                    string dbhost     = "localhost";
                    string dbuser     = "******";
                    string dbpass     = "******";
                    string dbdatabase = "iafram";
                    string connStr    = String.Format("server={0};user id={1};password={2}; database={3}; pooling=false",
                                                      dbhost, dbuser, dbpass, dbdatabase);
                    conn = new MySqlConnection(connStr);
                    conn.Open();
                    conn.ChangeDatabase(dbdatabase);

                    string query = "SELECT COUNT(*) ";
                    query += "FROM cse337_project ";
                    query += "WHERE username = "******" AND password = "******"/" + CommonFunctions.FileNameSafe(DateTime.Now.ToLongTimeString()));
                    Main m = new Main(txtUsername.Text, currentDirectory, dl);
                    m.ShowDialog();
                    dl.CloseFile();
                    m = null;
                    btnLogin.Enabled    = true;
                    btnCreate.Enabled   = true;
                    txtUsername.Enabled = true;
                    txtPassword.Enabled = true;
                    this.Visible        = true;
                }
                else
                {
                    MessageBox.Show("Incorrect username/password combination.");
                    btnLogin.Enabled    = true;
                    txtUsername.Enabled = true;
                    txtPassword.Enabled = true;
                }
            }
        }
Beispiel #30
0
        //Creating new user
        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnLogin.Enabled    = false;
            btnCreate.Enabled   = false;
            txtUsername.Enabled = false;
            txtPassword.Enabled = false;
            bool            exist   = false;
            MySqlConnection conn    = new MySqlConnection();
            JSch            jsch    = new JSch();
            string          host    = "secs.oakland.edu";
            string          user    = "******";
            string          pass    = "******";
            int             sshPort = 22;
            Session         session = jsch.getSession(user, host, sshPort);

            session.setHost(host);
            session.setPassword(pass);
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);
            try
            {
                session.connect();
                session.setPortForwardingL(3306, "localhost", 3306);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                txtUsername.Enabled = true;
                txtPassword.Enabled = true;
                btnLogin.Enabled    = true;
                btnCreate.Enabled   = true;
            }
            if (session.isConnected())
            {
                try
                {
                    string dbhost     = "localhost";
                    string dbuser     = "******";
                    string dbpass     = "******";
                    string dbdatabase = "iafram";
                    string connStr    = String.Format("server={0};user id={1};password={2}; database={3}; pooling=false",
                                                      dbhost, dbuser, dbpass, dbdatabase);
                    conn = new MySqlConnection(connStr);
                    conn.Open();
                    conn.ChangeDatabase(dbdatabase);

                    string query = "SELECT COUNT(*) ";
                    query += "FROM cse337_project ";
                    query += "WHERE username = "******" AND password = "******"INSERT INTO cse337_project ";
                        query += "(username, password) ";
                        query += "VALUES (" + quote + txtUsername.Text + quote + ", " + quote + txtPassword.Text + quote + ")";
                        command.CommandText = query;
                        command.ExecuteNonQuery();
                        //MySqlDataReader dataReader = command.ExecuteReader();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    session.disconnect();
                }
                finally
                {
                    conn.Close();
                }
                session.disconnect();

                if (exist)
                {
                    MessageBox.Show("Profile already exists.");
                    btnLogin.Enabled    = true;
                    btnCreate.Enabled   = true;
                    txtUsername.Enabled = true;
                    txtPassword.Enabled = true;
                }
                else
                {
                    MessageBox.Show("New profile created.");
                    btnLogin.Enabled    = true;
                    btnCreate.Enabled   = true;
                    txtUsername.Enabled = true;
                    txtPassword.Enabled = true;
                }
            }
        }
Beispiel #31
0
        private void sftp_login()
        {
            JSch jsch = new JSch();

            String host = tHost.Text;
            String user = tUsername.Text;

            Session session = jsch.getSession(user, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);

            session.setPort(Convert.ToInt32(nPort.Value));

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpc = (ChannelSftp)channel;
        }
Beispiel #32
0
        public async Task <ActionResult> OAuth2AuthorizationCodeGrantClient(string code, string state)
        {
            try
            {
                string response = "";

                if (state == this.State) // CSRF(XSRF)対策のstateの検証は重要
                {
                    response = await OAuth2AndOIDCClient.GetAccessTokenByCodeAsync(
                        new Uri("https://localhost:44300/MultiPurposeAuthSite/token"),
                        OAuth2AndOIDCParams.ClientID, OAuth2AndOIDCParams.ClientSecret,
                        HttpUtility.HtmlEncode("http://localhost:58496/Home/OAuth2AuthorizationCodeGrantClient"), code);

                    // 汎用認証サイトはOIDCをサポートしたのでid_tokenを取得し、検証可能。
                    //Base64UrlTextEncoder base64UrlEncoder = new Base64UrlTextEncoder();
                    Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(response);

                    // id_tokenの検証コード
                    if (dic.ContainsKey("id_token"))
                    {
                        string  sub   = "";
                        string  nonce = "";
                        JObject jobj  = null;

                        if (IdToken.Verify(dic["id_token"], dic["access_token"],
                                           code, state, out sub, out nonce, out jobj) && nonce == this.Nonce)
                        {
                            // ログインに成功

                            // /userinfoエンドポイントにアクセスする場合
                            response = await OAuth2AndOIDCClient.GetUserInfoAsync(
                                new Uri("https://localhost:44300/MultiPurposeAuthSite/userinfo"), dic["access_token"]);

                            // 認証情報を作成する。
                            List <Claim> claims = new List <Claim>();
                            claims.Add(new Claim(ClaimTypes.Name, sub));

                            // 認証情報を保存する。
                            ClaimsIdentity  userIdentity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);

                            // サイン アップする。
                            await AuthenticationHttpContextExtensions.SignInAsync(
                                this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);

                            // 認証情報を保存する。
                            MyUserInfo ui = new MyUserInfo(sub, (new GetClientIpAddress()).GetAddress());
                            UserInfoHandle.SetUserInformation(ui);

                            return(this.Redirect(Url.Action("Index", "Home")));
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                }

                // ログインに失敗
                return(RedirectToAction("Login"));
            }
            finally
            {
                this.ClearExLoginsParams();
            }
        }
Beispiel #33
0
        public static void Main(String[] arg)
        {
            if (arg.Length != 2)
            {
                Console.WriteLine("usage: java ScpFrom user@remotehost:file1 file2");
                return;
            }

            try
            {
                String user = arg[0].Substring(0, arg[0].IndexOf('@'));
                arg[0] = arg[0].Substring(arg[0].IndexOf('@') + 1);
                String host  = arg[0].Substring(0, arg[0].IndexOf(':'));
                String rfile = arg[0].Substring(arg[0].IndexOf(':') + 1);
                String lfile = arg[1];

                String prefix = null;
                if (Directory.Exists(lfile))
                {
                    prefix = lfile + Path.DirectorySeparatorChar;
                }

                JSch    jsch    = new JSch();
                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                // exec 'scp -f rfile' remotely
                String  command = "scp -f " + rfile;
                Channel channel = session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs = channel.getOutputStream();
                Stream ins  = channel.getInputStream();

                channel.connect();

                byte[] buf = new byte[1024];

                // send '\0'
                buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();

                while (true)
                {
                    int c = checkAck(ins);
                    if (c != 'C')
                    {
                        break;
                    }

                    // read '0644 '
                    ins.Read(buf, 0, 5);

                    int filesize = 0;
                    while (true)
                    {
                        ins.Read(buf, 0, 1);
                        if (buf[0] == ' ')
                        {
                            break;
                        }
                        filesize = filesize * 10 + (buf[0] - '0');
                    }

                    String file = null;
                    for (int i = 0;; i++)
                    {
                        ins.Read(buf, i, 1);
                        if (buf[i] == (byte)0x0a)
                        {
                            file = Util.getString(buf, 0, i);
                            break;
                        }
                    }

                    //Console.WriteLine("filesize="+filesize+", file="+file);

                    // send '\0'
                    buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();

                    // read a content of lfile
                    FileStream fos = File.OpenWrite(prefix == null ?
                                                    lfile :
                                                    prefix + file);
                    int foo;
                    while (true)
                    {
                        if (buf.Length < filesize)
                        {
                            foo = buf.Length;
                        }
                        else
                        {
                            foo = filesize;
                        }
                        ins.Read(buf, 0, foo);
                        fos.Write(buf, 0, foo);
                        filesize -= foo;
                        if (filesize == 0)
                        {
                            break;
                        }
                    }
                    fos.Close();

                    byte[] tmp = new byte[1];

                    if (checkAck(ins) != 0)
                    {
                        Environment.Exit(0);
                    }

                    // send '\0'
                    buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();
                }
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() 
                { 
                    UserName = model.UserName,
                    Email = model.Email 
                    
                };
                var myInfo = new MyUserInfo() 
                { 
                    FirstName = model.FirstName, 
                    LastName = model.LastName, 
                    
                };
                user.MyUserInfo = myInfo;
                
                    
                var result = await UserManager.CreateAsync(user, model.Password);
                
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #35
0
        public static void Main(String[] arg)
        {
            if(arg.Length!=2)
            {
                Console.WriteLine("usage: java ScpTo file1 user@remotehost:file2");
                Environment.Exit(-1);
            }

            try
            {

                String lfile=arg[0];
                String user=arg[1].Substring(0, arg[1].IndexOf('@'));
                arg[1]=arg[1].Substring(arg[1].IndexOf('@')+1);
                String host=arg[1].Substring(0, arg[1].IndexOf(':'));
                String rfile=arg[1].Substring(arg[1].IndexOf(':')+1);

                JSch jsch=new JSch();
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                // exec 'scp -t rfile' remotely
                String command="scp -p -t "+rfile;
                Channel channel=session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs=channel.getOutputStream();
                Stream ins=channel.getInputStream();

                channel.connect();

                byte[] tmp=new byte[1];

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }

                // send "C0644 filesize filename", where filename should not include '/'

                int filesize=(int)(new FileInfo(lfile)).Length;
                command="C0644 "+filesize+" ";
                if(lfile.LastIndexOf('/')>0)
                {
                    command+=lfile.Substring(lfile.LastIndexOf('/')+1);
                }
                else
                {
                    command+=lfile;
                }
                command+="\n";
                byte[] buff = Util.getBytes(command);
                outs.Write(buff, 0, buff.Length); outs.Flush();

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }

                // send a content of lfile
                FileStream fis=File.OpenRead(lfile);
                byte[] buf=new byte[1024];
                while(true)
                {
                    int len=fis.Read(buf, 0, buf.Length);
                    if(len<=0) break;
                    outs.Write(buf, 0, len); outs.Flush();
                    Console.Write("#");
                }

                // send '\0'
                buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();
                Console.Write(".");

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }
                Console.WriteLine("OK");
                Environment.Exit(0);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #36
0
        /// <summary>三層データバインド用の引数クラスを生成</summary>
        /// <param name="tableName">テーブル名</param>
        /// <param name="methodName">メソッド名</param>
        /// <param name="myUserInfo">ユーザ情報</param>
        /// <returns>三層データバインド用の引数クラス</returns>
        protected _3TierParameterValue CreateParameter(string tableName, string methodName, MyUserInfo myUserInfo)
        {
            // 三層データバインド用の引数クラスを生成
            _3TierParameterValue parameterValue = new _3TierParameterValue(
                tableName + "ConditionalSearch", tableName + "TableAdapter", methodName,
                (string)HttpContext.Current.Session["DAP"], myUserInfo);

            // DBMS
            parameterValue.DBMSType = (DbEnum.DBMSType)HttpContext.Current.Session["DBMS"];

            // テーブル
            parameterValue.TableName = tableName;

            // 検索条件(Sessionはnullチェック不要)
            #region AND

            parameterValue.AndEqualSearchConditions =
                (Dictionary <string, object>)HttpContext.Current.Session["AndEqualSearchConditions"];

            parameterValue.AndLikeSearchConditions =
                (Dictionary <string, string>)HttpContext.Current.Session["AndLikeSearchConditions"];

            #endregion

            #region OR

            parameterValue.OrEqualSearchConditions =
                (Dictionary <string, object[]>)HttpContext.Current.Session["OrEqualSearchConditions"];

            parameterValue.OrLikeSearchConditions =
                (Dictionary <string, string[]>)HttpContext.Current.Session["OrLikeSearchConditions"];

            #endregion

            #region Else

            parameterValue.ElseWhereSQL =
                (string)HttpContext.Current.Session["ElseWhereSQL"];

            parameterValue.ElseSearchConditions =
                (Dictionary <string, object>)HttpContext.Current.Session["ElseSearchConditions"];

            #endregion

            return(parameterValue);
        }
Beispiel #37
0
        public static void RunExample(String[] arg)
        {
            try
            {
                //Get the "known hosts" filename from the user
                Console.WriteLine("Please select your 'known_hosts' from the poup window...");
                String file = InputForm.GetFileFromUser("Choose your known_hosts(ex. ~/.ssh/known_hosts)");
                Console.WriteLine("You chose " + file + ".");
                //Create a new JSch instance
                JSch jsch = new JSch();
                //Set the known hosts file
                jsch.setKnownHosts(file);

                //Get the KnownHosts repository from JSchs
                HostKeyRepository hkr = jsch.getHostKeyRepository();

                //Print all known hosts and keys
                HostKey[] hks = hkr.getHostKey();
                HostKey   hk;
                if (hks != null)
                {
                    Console.WriteLine();
                    Console.WriteLine("Host keys in " + hkr.getKnownHostsRepositoryID() + ":");
                    for (int i = 0; i < hks.Length; i++)
                    {
                        hk = hks[i];
                        Console.WriteLine(hk.getHost() + " " +
                                          hk.getType() + " " +
                                          hk.getFingerPrint(jsch));
                    }
                    Console.WriteLine("");
                }

                //Now connect to the remote server...

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                                  ("Enter username@hostname",
                                  Environment.UserName + "@localhost");
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                //Create a new SSH session
                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Print the host key info
                //of the connected server:
                hk = session.getHostKey();
                Console.WriteLine("HostKey: " +
                                  hk.getHost() + " " +
                                  hk.getType() + " " +
                                  hk.getFingerPrint(jsch));

                //Open a new Shell channel on the SSH session
                Channel channel = session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                Console.WriteLine("-- Shell channel is connected using the {0} cipher",
                                  session.getCipher());

                //Wait till channel is closed
                while (!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public async Task <ActionResult> Create(RegisterViewModel userViewModel, string RoleId, [Bind(Include = "Name")] ApplicationUser kUser, string[] selectedKPIs)
        {
            if (selectedKPIs != null)
            {
                kUser.KPIs = new List <KPI>();
                foreach (var kpi in selectedKPIs)
                {
                    var kpiToAdd = context.KPIs.Find(int.Parse(kpi));
                    kUser.KPIs.Add(kpiToAdd);
                }
            }

            if (ModelState.IsValid)
            {
                var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
                var userinfo    = new MyUserInfo()
                {
                    FirstName = userViewModel.FirstName,
                    LastName  = userViewModel.LastName
                };
                var user = new ApplicationUser();
                user.UserName   = userViewModel.UserName;
                user.Email      = userViewModel.Email;
                user.MyUserInfo = userinfo;
                var adminresult = UserManager.Create(user, userViewModel.Password);

                context.Users.Add(user);
                context.SaveChanges();


                //Add User Admin to Role Admin
                if (adminresult.Succeeded)
                {
                    if (!String.IsNullOrEmpty(RoleId))
                    {
                        //Find Role Admin
                        var role = await RoleManager.FindByIdAsync(RoleId);

                        var result = await UserManager.AddToRoleAsync(user.Id, role.Name);

                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First().ToString());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Id", "Name");
                            return(View());
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First().ToString());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                    return(View());
                }
                return(RedirectToAction("Index"));
            }
            else
            {
                ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name");
                return(View());
            }
        }