Esempio n. 1
0
        public void TestClientBrand(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ServerCredentials credentials = new ServerCredentials()
            {
                Address  = new Uri(url),
                Binding  = binding,
                UserName = user,
                Password = password
            };

            var underTest = new ClientBrand(credentials, repositoryId, remoteFolderPath);

            Assert.That(underTest.SetupServer(credentials), Is.True);

            foreach (string path in underTest.PathList)
            {
                DateTime date;
                Assert.That(underTest.GetFileDateTime(path, out date), Is.True);
                using (var stream = new MemoryStream()) {
                    Assert.That(underTest.GetFile(path, stream), Is.True);
                    Assert.That(stream.Length, Is.GreaterThan(0));
                }
            }
        }
Esempio n. 2
0
        /// <summary>Check for current application updates.</summary>
        /// <param name="credentials">Server credentials for private repository updates.</param>
        /// <param name="status">Update check status event.</param>
        public static void CheckForUpdates(ServerCredentials credentials, Action <UpdateCheckStatus, string> status)
        {
            if (status is null)
            {
                throw new ArgumentNullException(nameof(status));
            }

            Task.Run(async() =>
            {
                try
                {
                    var cts   = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                    var lines = await DoCheckForUpdates(credentials, cts.Token, status);
                    if (lines.Length == 1 && lines[0].ToLowerInvariant() == "uptodate")
                    {
                        status.Invoke(UpdateCheckStatus.UpToDate, string.Empty);
                        return;
                    }

                    status.Invoke(UpdateCheckStatus.UpdatesAvailable, lines.Join("\n"));
                }
                catch (UpdateException e)
                {
                    status.Invoke(e.Status, e.ToString());
                }
                catch (Exception e)
                {
                    status.Invoke(UpdateCheckStatus.Error, e.ToString());
                }
            });
        }
Esempio n. 3
0
        private async Task EnsureConnectUser(ServerCredentials credentials, CancellationToken cancellationToken)
        {
            if (ConnectUser != null && string.Equals(ConnectUser.Id, credentials.ConnectUserId, StringComparison.Ordinal))
            {
                return;
            }

            ConnectUser = null;

            if (!string.IsNullOrWhiteSpace(credentials.ConnectUserId) && !string.IsNullOrWhiteSpace(credentials.ConnectAccessToken))
            {
                try
                {
                    ConnectUser = await _connectService.GetConnectUser(new ConnectUserQuery
                    {
                        Id = credentials.ConnectUserId
                    }, credentials.ConnectAccessToken, cancellationToken).ConfigureAwait(false);

                    OnConnectUserSignIn(ConnectUser);
                }
                catch
                {
                    // Already logged at lower levels
                }
            }
        }
Esempio n. 4
0
        public void CreateMultipleServerCredentialsBasedOnTheGivenOne()
        {
            var userName            = "******";
            var originalUrl         = "https://demo.deutsche-wolke.de/wrongStuff";
            var password            = new Password(Guid.NewGuid().ToString());
            var originalCredentials = new ServerCredentials {
                Address  = new Uri(originalUrl),
                Password = password,
                Binding  = BindingType.Browser,
                UserName = userName
            };

            var list = originalCredentials.CreateFuzzyCredentials();

            Assert.That(list, Is.Not.Null);
            Assert.That(list, Is.Not.Empty);
            Assert.That(list.First().Credentials, Is.EqualTo(originalCredentials));
            Assert.That(list[1].Credentials.Address.ToString(), Is.EqualTo(originalCredentials.Address.ToString()));
            Assert.That(list[1].Credentials.Binding, Is.Not.EqualTo(originalCredentials.Binding));
            foreach (var entry in list)
            {
                Assert.That(entry.Credentials.Password.ToString(), Is.EqualTo(password.ToString()));
                Assert.That(entry.Credentials.UserName, Is.EqualTo(userName));
                Console.WriteLine(entry);
            }
        }
Esempio n. 5
0
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                try
                {
                    var serverCredentials = new ServerCredentials().GetServerCredentials(User.Identity.Name);


                    return(View(new MapView
                    {
                        ServerUp = new MineStat(serverCredentials.IP, (ushort)serverCredentials.Port).ServerUp,
                        MapUrl = serverCredentials.MapUrl
                    }));
                }
                catch (Exception e)
                {
                    return(ViewBag.Error = e.Message);
                }
            }
            else
            {
                return(Redirect("~/Account/Login"));
            }
        }
        private async Task <bool> SaveServerCreds(ServerCredentials configuration)
        {
            var tsc = new TaskCompletionSource <bool>();

            Deployment.Current.Dispatcher.BeginInvoke(async() =>
            {
                await Lock.WaitAsync();

                try
                {
                    var json = JsonConvert.SerializeObject(configuration);

                    await _storageService.WriteAllTextAsync(Constants.Settings.ServerCredentialSettings, json).ConfigureAwait(false);
                }
                finally
                {
                    Lock.Release();
                }

                Debug.WriteLine("SaveCreds, Server count: " + (configuration != null && configuration.Servers != null ? configuration.Servers.Count : 0));

                tsc.SetResult(true);
            });

            return(await tsc.Task);
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RemoteStorageClient"/>.
 /// </summary>
 /// <param name="address">Server address.</param>
 /// <param name="streaming">Data transfer via WCF Streaming.</param>
 public RemoteStorageClient(Uri address, bool streaming = true)
     : base(address, "remoteStorage")
 {
     _streaming        = streaming;
     Credentials       = new ServerCredentials();
     SecurityBatchSize = 1000;
 }
Esempio n. 8
0
        //[ValidateAntiForgeryToken]
        public async Task <ActionResult> ServerCredentials(ServerCredentials model)
        {
            using (var context = new ApplicationDbContext())
            {
                if (context.Set <ServerCredentials>().Any(x => x.Name == model.Name))
                {
                    context.Entry(model).State = EntityState.Modified;
                }
                else
                {
                    context.Entry(model).State = EntityState.Added;
                }
                try
                {
                    await context.SaveChangesAsync();
                }
                catch
                {
                    RedirectToAction("Index", new { Message = ManageMessageId.SaveError });
                }
            }


            return(RedirectToAction("Index", new { Message = ManageMessageId.Saved }));
        }
Esempio n. 9
0
        public void Login(ServerCredentials.LoginData loginData)
        {
            UserConfiguration userConfig = null;

            if (loginData != null)
            {
                while (loginData != null && userConfig == null)
                {
                    userConfig = UserManagement.TokenLogin(loginData.Token);
                    if (userConfig == null)
                    {
                        logger.Warn(String_Functions.UppercaseFirst(loginData.Username) + " Failed to Login... Retrying in 5 seconds");

                        Thread.Sleep(5000);

                        loginData = ServerCredentials.Read();
                    }
                }

                if (userConfig != null)
                {
                    logger.Info(String_Functions.UppercaseFirst(userConfig.Username) + " Logged in Successfully");
                }
            }

            CurrentUser = userConfig;
        }
Esempio n. 10
0
        public string CallRcon(string commandRcon, ServerCredentials serverCredentials)
        {
            var answer = "";

            try
            {
                using (var rcon = RCONClient.INSTANCE)
                {
                    if (serverCredentials != null)
                    {
                        rcon.setupStream(serverCredentials.IP, serverCredentials.RconPort, password: serverCredentials.Password);
                        answer = rcon.sendMessage(RCONMessageType.Command, commandRcon).RemoveColorCodes();

                        if (rcon.isInit == false)
                        {
                            answer = "Error: Server is offline!";
                        }
                        else if (rcon.ErrorMsg.Length > 0)
                        {
                            answer = rcon.ErrorMsg;
                        }
                    }
                    else
                    {
                        answer = "Error: Configure connection!";
                    }
                }
            }
            catch (Exception ex)
            {
                answer = ex.Message;
            }

            return(answer);
        }
Esempio n. 11
0
        private void SetCredentials(ServerCredentials credentials = null)
        {
            var serverCredentials = credentials ?? new ServerCredentials();

            SettingsPanel.Login    = serverCredentials.Login;
            SettingsPanel.Password = serverCredentials.Password;
        }
Esempio n. 12
0
        /// <nodoc/>
        internal void Start(int port, ServerServiceDefinition serverService)
        {
            var interceptor = new ServerInterceptor(m_loggingContext, m_invocationId);

            ServerCredentials serverCreds = null;

            if (GrpcSettings.EncryptionEnabled)
            {
                string certSubjectName = EngineEnvironmentSettings.CBBuildUserCertificateName;
                if (GrpcEncryptionUtil.TryGetPublicAndPrivateKeys(certSubjectName, out string publicCertificate, out string privateKey, out var _) &&
                    publicCertificate != null &&
                    privateKey != null)
                {
                    serverCreds = new SslServerCredentials(
                        new List <KeyCertificatePair> {
                        new KeyCertificatePair(publicCertificate, privateKey)
                    },
                        null,
                        SslClientCertificateRequestType.DontRequest);

                    Logger.Log.GrpcAuthTrace(m_loggingContext, $"Server-side SSL credentials is enabled.");
                }
                else
                {
                    Logger.Log.GrpcAuthWarningTrace(m_loggingContext, $"Could not extract public certificate and private key from '{certSubjectName}'. Server will be started without ssl.");
                }
            }
Esempio n. 13
0
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                try
                {
                    var credentials = new ServerCredentials();

                    var serverCredentials = credentials.GetServerCredentials(User.Identity.Name);
                    if (serverCredentials == null)
                    {
                        serverCredentials = credentials.CreateStock(User.Identity.Name);
                    }

                    var mineStat        = new MineStat(serverCredentials.IP, (ushort)serverCredentials.Port);
                    var statusViewModel = new StatusViewModel(serverCredentials, mineStat);

                    return(View(statusViewModel));
                }
                catch (Exception ex)
                {
                    ViewData["Error"] = "Error: " + ex.Message;

                    return(Redirect("~/Account/Login"));
                }
            }
            else
            {
                return(Redirect("~/Account/Login"));
            }
        }
Esempio n. 14
0
 public ProcessResult Do(ServerCredentials server)
 {
     return _sshCommand.Do(server, string.Format(@"7z.exe -y x -o{0} ""{1}{2}""",
                                                 _buildToolsDirectory,
                                                 server.HomeDirectory,
                                                 _buildToolsZip));
 }
Esempio n. 15
0
        public static Server StartServer(IList <ServerServiceDefinition> services, ServerCredentials serverCredentials, string host, int basePort, int count, out int port)
        {
            UseConsoleVerboseLogger();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.MaxSendMessageLength, int.MaxValue),
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, int.MaxValue),
            };

            for (var i = 0; i < count; i++)
            {
                var server = new Server(options);
                foreach (var service in services)
                {
                    server.Services.Add(service);
                }

                server.Ports.Add(host, basePort + i, serverCredentials);
                try
                {
                    server.Start();
                    port = basePort + i;
                    return(server);
                }
                catch (IOException ex) when(i < count - 1 &&
                                            ex.Message.IndexOf("Failed to bind port",
                                                               StringComparison.OrdinalIgnoreCase) >= 0)
                {
                }
            }

            throw new InvalidOperationException($"Failed to start server at {host} using port range [{basePort}-{basePort+count})");
        }
Esempio n. 16
0
        public async Task <ServerCredentials> GetServerCredentials()
        {
            if (_servers == null)
            {
                await _asyncLock.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (_servers == null)
                    {
                        try
                        {
                            _servers = _json.DeserializeFromFile <ServerCredentials>(Path);
                        }
                        catch (IOException)
                        {
                            _servers = new ServerCredentials();
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error reading saved credentials", ex);
                            _servers = new ServerCredentials();
                        }
                    }
                }
                finally
                {
                    _asyncLock.Release();
                }
            }
            return(_servers);
        }
Esempio n. 17
0
            public ClientBrand(ServerCredentials credentials, string repositoryId, string remoteFolderPath)
            {
                Dictionary <string, string> parameters = CmisUtils.GetCmisParameters(credentials);
                ISessionFactory             factory    = SessionFactory.NewInstance();
                IList <IRepository>         repos      = factory.GetRepositories(parameters);

                foreach (IRepository repo in repos)
                {
                    if (repo.Id == repositoryId)
                    {
                        this.repository = repo;
                        this.repoName   = repo.Name;
                    }
                }

                if (this.repository == null)
                {
                    throw new ArgumentException("No such repository for " + repositoryId);
                }

                this.session = this.repository.CreateSession();
                this.folder  = this.session.GetObjectByPath(remoteFolderPath) as IFolder;
                if (this.folder == null)
                {
                    throw new ArgumentException("No such folder for " + remoteFolderPath);
                }

                foreach (string name in this.nameList)
                {
                    this.pathList.Add((remoteFolderPath + "/" + name).Replace("//", "/"));
                }

                this.DeleteFiles();
                this.CreateFiles();
            }
Esempio n. 18
0
        /// <summary>
        /// Check if the CMIS server holds the client brand files
        /// </summary>
        /// <param name="credentials"></param>
        /// <returns>Whether the CMIS server holds the client brand files</returns>
        public bool TestServer(ServerCredentials credentials)
        {
            IRepository repo = this.GetRepo(credentials);

            if (repo == null)
            {
                return(false);
            }

            try {
                ISession session = repo.CreateSession();
                foreach (string path in this.PathList)
                {
                    try {
                        IDocument doc = session.GetObjectByPath(path) as IDocument;
                        if (doc == null)
                        {
                            return(false);
                        }
                    } catch (CmisObjectNotFoundException e) {
                        Logger.Debug(e.ErrorContent, e);
                        return(false);
                    }
                }
            } catch (Exception e) {
                Logger.Debug(e.Message, e);
                return(false);
            }

            return(true);
        }
Esempio n. 19
0
        public void GetRepositoriesTroughProxy(
            string cmisServerUrl,
            string cmisUser,
            string cmisPassword,
            string proxyUrl,
            string proxyUser,
            string proxyPassword)
        {
            if (string.IsNullOrEmpty(proxyUrl))
            {
                Assert.Ignore();
            }

            ServerCredentials credentials = new ServerCredentials {
                Address  = new Uri(cmisServerUrl),
                UserName = cmisUser,
                Password = cmisPassword
            };

            ProxySettings proxySettings = new ProxySettings();

            proxySettings.Selection     = string.IsNullOrEmpty(cmisServerUrl) ? ProxySelection.NOPROXY : ProxySelection.CUSTOM;
            proxySettings.Server        = new Uri(proxyUrl);
            proxySettings.LoginRequired = !string.IsNullOrEmpty(proxyUser);
            if (proxySettings.LoginRequired)
            {
                proxySettings.Username           = proxyUser;
                proxySettings.ObfuscatedPassword = Crypto.Obfuscate(proxyPassword);
            }

            HttpProxyUtils.SetDefaultProxy(proxySettings, true);

            Assert.That(credentials.GetRepositories(), Is.Not.Empty);
        }
        void ICredentialsProvider.Save(ServerCredentials credentials)
        {
            if (credentials is null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            lock (this)
            {
                var clone = credentials.Clone();

                if (!clone.AutoLogon)
                {
                    clone.Password = null;
                }

                Directory.CreateDirectory(Paths.CompanyPath);

                var file = Path.Combine(Paths.CompanyPath, _credentialsFile);

                clone.Save().Serialize(file);

                _credentials = clone;
            }
        }
Esempio n. 21
0
        public static void Main(string[] args)
        {
            ServerCredentials serverCredentials = null;
            var securityOption = Environment.GetEnvironmentVariable("GREETER_SERVER_SECURITY");

            switch (securityOption)
            {
            case "insecure":
                serverCredentials = ServerCredentials.Insecure;
                break;

            case "tls":
                serverCredentials = CreateSslServerCredentials(mutualTls: false);
                break;

            case "mtls":
                serverCredentials = CreateSslServerCredentials(mutualTls: true);
                break;

            default:
                throw new ArgumentException("Illegal security option.");
            }
            Console.WriteLine("Starting server with security: " + securityOption);

            Server server = new Server()
            {
                Services = { Greeter.BindService(new GreeterImpl()) },
                Ports    = { new ServerPort("0.0.0.0", Port, serverCredentials) },
            };

            server.Start();
            Console.WriteLine("Started server on port " + Port);

            server.ShutdownTask.Wait();
        }
        // ReSharper restore InconsistentlySynchronizedField

        bool ICredentialsProvider.TryLoad(out ServerCredentials credentials)
        {
            lock (this)
            {
                if (_credentials != null)
                {
                    credentials = _credentials.Clone();
                    return(IsValid);
                }

                var file = Path.Combine(Paths.CompanyPath, _credentialsFile);
                credentials = null;

                try
                {
                    if (File.Exists(file) || File.Exists(file.MakeLegacy()))
                    {
                        credentials = new ServerCredentials();
                        credentials.LoadIfNotNull(file.DeserializeWithMigration <SettingsStorage>());

                        _credentials = credentials.Clone();
                    }
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }

                return(IsValid);
            }
        }
        public void GetRepositories(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ServerCredentials credentials = new ServerCredentials()
            {
                Address  = new Uri(url),
                Binding  = binding,
                UserName = user,
                Password = password
            };

            var repos = credentials.GetRepositories();

            Assert.That(repos, Is.Not.Null.Or.Empty);

            foreach (var repo in repos)
            {
                Assert.That(string.IsNullOrEmpty(repo.Id), Is.False);
                Assert.That(string.IsNullOrEmpty(repo.Name), Is.False);
                Console.WriteLine(repo.ToString());
            }
        }
Esempio n. 24
0
        public void GetRepositories(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId)
        {
            ServerCredentials credentials = new ServerCredentials()
            {
                Address  = new Uri(url),
                UserName = user,
                Password = password
            };

            Dictionary <string, string> repos = CmisUtils.GetRepositories(credentials);

            foreach (KeyValuePair <string, string> pair in repos)
            {
                Assert.That(string.IsNullOrEmpty(pair.Key), Is.False);
                Assert.That(string.IsNullOrEmpty(pair.Value), Is.False);
            }

            Assert.NotNull(repos);
        }
        public static List <LoginCredentials> CreateFuzzyCredentials(this ServerCredentials normalCredentials)
        {
            var result = new List <LoginCredentials>();

            result.Add(new LoginCredentials {
                Credentials = normalCredentials
            });
            result.Add(new LoginCredentials {
                Credentials = new ServerCredentials {
                    Address  = new Uri(normalCredentials.Address.ToString()),
                    Password = new Password(normalCredentials.Password.ToString()),
                    Binding  = normalCredentials.Binding == BindingType.AtomPub ? BindingType.Browser : BindingType.AtomPub,
                    UserName = normalCredentials.UserName
                }
            });

            string[] bindings =
            {
                BindingType.Browser,
                BindingType.AtomPub
            };
            string[] browserSuffixes =
            {
                "/cmis/browser"
            };
            string[] atompubSuffixes =
            {
                "/cmis/atom11",
                "/cmis/atom"
            };

            // Extract protocol and server name or IP address
            string prefix = normalCredentials.Address.GetLeftPart(UriPartial.Authority);

            string[][] suffixes =
            {
                browserSuffixes,
                atompubSuffixes
            };

            for (int i = 0; i < bindings.Length; ++i)
            {
                // Create all suffixes
                for (int j = 0; j < suffixes[i].Length; ++j)
                {
                    string fuzzyUrl = prefix + suffixes[i][j];
                    result.Add(new LoginCredentials {
                        Credentials = new ServerCredentials {
                            Address  = new Uri(fuzzyUrl),
                            Binding  = bindings[i],
                            UserName = normalCredentials.UserName,
                            Password = new Password(normalCredentials.Password.ToString())
                        }
                    });
                }
            }

            return(result);
        }
Esempio n. 26
0
 public Task <ServerCredentials> GetServerCredentials()
 {
     if (cred == null)
     {
         cred = new ServerCredentials();
     }
     return(Task.FromResult(cred));
 }
Esempio n. 27
0
        public void DefaultConstructor()
        {
            var cred = new ServerCredentials();

            Assert.IsNull(cred.Address);
            Assert.IsNull(cred.UserName);
            Assert.IsNull(cred.Password);
        }
Esempio n. 28
0
 void IPersistable.Load(SettingsStorage storage)
 {
     Id          = storage.GetValue <string>("Id").To <Guid>();
     Credentials = storage.GetValue <SettingsStorage>("Credentials").Load <ServerCredentials>();
     UseLocal    = storage.GetValue <bool>("UseLocal");
     Path        = storage.GetValue <string>("Path");
     //IsAlphabetic = storage.GetValue<bool>("IsAlphabetic");
 }
Esempio n. 29
0
        private static Grpc.Core.Server StartServer([NotNull] MicroserverArguments arguments,
                                                    out IServiceHealth health)
        {
            // TODO: Move to ProSuite
            var healthService = new HealthServiceImpl();

            health = null;             // new ServiceHealth(healthService);

            int maxThreadCount = arguments.MaxParallel;

            if (maxThreadCount <= 0)
            {
                maxThreadCount = Environment.ProcessorCount - 1;
            }

            var taskScheduler = new StaTaskScheduler(maxThreadCount);

            var removeOverlapsServiceImpl = new RemoveOverlapsGrpcImpl(taskScheduler)
            {
                //Health = health
            };

            var advancedReshapeServiceImpl = new AdvancedReshapeGrpcImpl(taskScheduler);
            var changeAlongServiceImpl     = new ChangeAlongGrpcImpl(taskScheduler);

            //health.SetStatus(removeOverlapsServiceImpl.GetType(), true);

            ServerCredentials serverCredentials =
                GrpcServerUtils.GetServerCredentials(arguments.Certificate,
                                                     arguments.PrivateKeyFile);

            var oneGb = (int)Math.Pow(1024, 3);

            IList <ChannelOption> channelOptions = GrpcServerUtils.CreateChannelOptions(oneGb);

            var server =
                new Grpc.Core.Server(channelOptions)
            {
                Services =
                {
                    RemoveOverlapsGrpc.BindService(removeOverlapsServiceImpl),
                    ReshapeGrpc.BindService(advancedReshapeServiceImpl),
                    ChangeAlongGrpc.BindService(changeAlongServiceImpl)
                    //Health.BindService(healthService)
                },
                Ports =
                {
                    new ServerPort(arguments.HostName, arguments.Port, serverCredentials)
                }
            };

            server.Start();

            _msg.InfoFormat("Service is listening on host {0}, port {1}.", arguments.HostName,
                            arguments.Port);

            return(server);
        }
Esempio n. 30
0
 public DatabaseManagerServer(int port, BaseDatabase database, ServerCredentials credentials)
 {
     Database = database;
     Server   = new Server
     {
         Services = { DatabaseService.BindService(new DatabaseServiceImplement(database)) },
         Ports    = { new ServerPort("localhost", port, credentials) }
     };
 }
Esempio n. 31
0
        /// <summary>
        /// Save the credentials to <see cref="Paths.CompanyPath"/>.
        /// </summary>
        /// <param name="credentials">The class that contains a login and password to access the services https://stocksharp.com .</param>
        public static void SaveCredentials(this ServerCredentials credentials)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            credentials.SaveCredentials(credentials.AutoLogon);
        }
 public ProcessResult Do(ServerCredentials server)
 {
     const string winscp = @"winscp\winscp.com";
     const string keyfile = @"Key.ppk";
     var scpCmd = string.Format(@"{6}{0} /command ""open sftp://{1}@{2}:{3} -hostkey=""""{7}"""" -privatekey={6}{4}"" ""rm {5}"" ""put {6}{5}"" ""exit""",
                                winscp,
                                server.User,
                                server.Host,
                                server.Port,
                                keyfile,
                                _buildToolsZip,
                                _buildToolsDirectory,
                                 server.HostKey);
     return _command.Do(scpCmd);
 }
Esempio n. 33
0
        public AgarioClient()
        {
            Console.WriteLine(BitConverter.IsLittleEndian);
            state = new WorldState();
            credentials = Servers.GetFFAServer();

            Console.WriteLine("Server {0}", credentials.Server);
            Console.WriteLine("Key {0}", credentials.Key);

            var uri = "ws://" + credentials.Server;
            Console.WriteLine(uri);

            ws = new WebSocket(uri);

            ws.Origin = "http://agar.io";
            ws.OnOpen += OnOpen;
            ws.OnError += OnError;
            ws.OnMessage += OnMessageReceived;
            ws.OnClose += OnClose;
            ws.Connect();
        }
Esempio n. 34
0
 public static ServerCredentials MakePostRequest(string postData)
 {
     //Maybe we could use webclient but I didn't succeed making a correctly formated application/x-www-form-urlencoded post request
     WebRequest request = WebRequest.Create("http://m.agar.io/");
     request.Method = "POST";
     byte[] byteArray = Encoding.UTF8.GetBytes(postData);
     request.ContentType = "application/x-www-form-urlencoded";
     request.ContentLength = byteArray.Length;
     Stream dataStream = request.GetRequestStream();
     dataStream.Write(byteArray, 0, byteArray.Length);
     dataStream.Close();
     WebResponse response = request.GetResponse();
     Console.WriteLine(((HttpWebResponse)response).StatusDescription);
     dataStream = response.GetResponseStream();
     StreamReader reader = new StreamReader(dataStream);
     string result = reader.ReadToEnd();
     Console.WriteLine(result);
     var lines = result.Split('\n');
     var output = new ServerCredentials{ Server = lines[0], Key = lines[1] };
     reader.Close();
     dataStream.Close();
     response.Close();
     return output;
 }
Esempio n. 35
0
 void ShowLoginPage()
 {
     Header = CmisSync.Properties_Resources.Where;
     Description = "";
     AddressLabel = new NSTextField() {
         Alignment = NSTextAlignment.Left,
         BackgroundColor = NSColor.WindowBackground,
         Bordered = false,
         Editable = false,
         Frame = new RectangleF(190, 320, 196 + 196 + 16, 17),
         StringValue = Properties_Resources.EnterWebAddress,
         Font = UI.BoldFont
     };
     AddressTextField = new NSTextField() {
         Frame = new RectangleF(190, 290, 196 + 196 + 16, 22),
         Font = UI.Font,
         Delegate = new TextFieldDelegate(),
         StringValue = (Controller.PreviousAddress == null || String.IsNullOrEmpty(Controller.PreviousAddress.ToString())) ? "https://" : Controller.PreviousAddress.ToString()
     };
     AddressTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingHead;
     AddressHelpLabel = new NSTextField() {
         BackgroundColor = NSColor.WindowBackground,
         Bordered = false,
         TextColor = NSColor.DisabledControlText,
         Editable = false,
         Frame = new RectangleF(190, 265, 196 + 196 + 16, 17),
         Font = NSFontManager.SharedFontManager.FontWithFamily("Lucida Grande", NSFontTraitMask.Condensed, 0, 11),
     };
     NSTextField UserLabel = new NSTextField() {
         Alignment = NSTextAlignment.Left,
         BackgroundColor = NSColor.WindowBackground,
         Font = UI.BoldFont,
         Bordered = false,
         Editable = false,
         Frame = new RectangleF(190, 230, 196, 17),
         StringValue = Properties_Resources.User
     };
     NSTextField UserTextField = new NSTextField() {
         Font = UI.Font,
         StringValue = String.IsNullOrEmpty(Controller.saved_user) ? Environment.UserName : Controller.saved_user,
         Frame = new RectangleF(190, 200, 196, 22)
     };
     UserTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingHead;
     PasswordLabel = new NSTextField() {
         Alignment = NSTextAlignment.Left,
         BackgroundColor = NSColor.WindowBackground,
         Bordered = false,
         Editable = false,
         Frame = new RectangleF(190 + 196 + 16, 230, 196, 17),
         StringValue = Properties_Resources.Password,
         Font = UI.BoldFont
     };
     PasswordTextField = new NSSecureTextField() {
         Frame = new RectangleF(190 + 196 + 16, 200, 196, 22),
         Delegate = new TextFieldDelegate()
     };
     WarningTextField = new NSTextField() {
         BackgroundColor = NSColor.WindowBackground,
         Bordered = false,
         TextColor = NSColor.Red,
         Editable = false,
         Frame = new RectangleF(190, 30, 196 + 196 + 16, 160),
         Font = NSFontManager.SharedFontManager.FontWithFamily("Lucida Grande", NSFontTraitMask.Condensed, 0, 11),
     };
     WarningTextField.Cell.LineBreakMode = NSLineBreakMode.ByWordWrapping;
     ContinueButton = new NSButton() {
         Title = Properties_Resources.Continue,
         Enabled = false
     };
     CancelButton = new NSButton() {
         Title = Properties_Resources.Cancel
     };
     (AddressTextField.Delegate as TextFieldDelegate).StringValueChanged += CheckAddressTextField;
     ContinueButton.Activated += delegate
     {
         ServerCredentials credentials = null;
         InvokeOnMainThread(delegate {
             credentials = new ServerCredentials() {
                 UserName = UserTextField.StringValue,
                 Password = PasswordTextField.StringValue,
                 Address = new Uri(AddressTextField.StringValue)
             };
             ContinueButton.Enabled = false;
             CancelButton.Enabled = false;
         });
         Thread check = new Thread(() => {
             Tuple<CmisServer, Exception> fuzzyResult = CmisUtils.GetRepositoriesFuzzy(credentials);
             CmisServer cmisServer = fuzzyResult.Item1;
             if (cmisServer != null)
             {
                 Controller.repositories = cmisServer.Repositories;
             }
             else
             {
                 Controller.repositories = null;
             }
             InvokeOnMainThread(delegate {
                 if (Controller.repositories == null)
                 {
                     WarningTextField.StringValue = Controller.getConnectionsProblemWarning(fuzzyResult.Item1, fuzzyResult.Item2);
                     ContinueButton.Enabled = true;
                     CancelButton.Enabled = true;
                 }
                 else
                 {
                     Controller.Add1PageCompleted(cmisServer.Url, credentials.UserName, credentials.Password.ToString());
                 }
             });
         });
         check.Start();
     };
     CancelButton.Activated += delegate
     {
         Controller.PageCancelled();
     };
     ContentView.AddSubview(AddressLabel);
     ContentView.AddSubview(AddressTextField);
     ContentView.AddSubview(AddressHelpLabel);
     ContentView.AddSubview(UserLabel);
     ContentView.AddSubview(UserTextField);
     ContentView.AddSubview(PasswordLabel);
     ContentView.AddSubview(PasswordTextField);
     ContentView.AddSubview(WarningTextField);
     Buttons.Add(ContinueButton);
     Buttons.Add(CancelButton);
     Controller.CheckAddPage(AddressTextField.StringValue);
 }
Esempio n. 36
0
        private void ShowAdd1Page()
        {
            this.Present();
            Header = CmisSync.Properties_Resources.Where;

            VBox layout_vertical   = new VBox (false, 12);
            HBox layout_fields     = new HBox (true, 12);
            VBox layout_address    = new VBox (true, 0);
            HBox layout_address_help = new HBox(false, 3);
            VBox layout_user       = new VBox (true, 0);
            VBox layout_password   = new VBox (true, 0);

            // Address
            Label address_label = new Label()
            {
                UseMarkup = true,
                          Xalign = 0,
                          Markup = "<b>" + 
                              CmisSync.Properties_Resources.EnterWebAddress +
                              "</b>"
            };

            Entry address_entry = new Entry () {
                Text = (Controller.PreviousAddress == null || String.IsNullOrEmpty(Controller.PreviousAddress.ToString()))?"https://":Controller.PreviousAddress.ToString(),
                     ActivatesDefault = false
            };

            Label address_help_label = new Label()
            {
                Xalign = 0,
                       UseMarkup = true,
                       Markup = "<span foreground=\"#808080\" size=\"small\">" +
                           CmisSync.Properties_Resources.Help + ": " +
                           "</span>"
            };
            EventBox address_help_urlbox = new EventBox();
            Label address_help_urllabel = new Label()
            {
                Xalign = 0,
                       UseMarkup = true,
                       Markup = "<span foreground=\"blue\" underline=\"single\" size=\"small\">" +
                           CmisSync.Properties_Resources.WhereToFind +
                           "</span>"
            };
            address_help_urlbox.Add(address_help_urllabel);
            address_help_urlbox.ButtonPressEvent += delegate(object o, ButtonPressEventArgs args) {
                Process process = new Process();
                process.StartInfo.FileName  = "xdg-open";
                process.StartInfo.Arguments = "https://github.com/aegif/CmisSync/wiki/What-address";
                process.Start ();
            };
            address_help_urlbox.EnterNotifyEvent += delegate(object o, EnterNotifyEventArgs args) {
                address_help_urlbox.GdkWindow.Cursor = hand_cursor;
            };

            Label address_error_label = new Label()
            {
                Xalign = 0,
                UseMarkup = true,
                Markup = ""
            };
            address_error_label.Hide();

            // User
            Entry user_entry = new Entry () {
                Text = Controller.PreviousPath,
                     ActivatesDefault = false
            };

            if(String.IsNullOrEmpty(Controller.saved_user))
            {
                user_entry.Text = Environment.UserName;
            }
            else
            {
                user_entry.Text = Controller.saved_user;
            }

            // Password
            Entry password_entry = new Entry () {
                Visibility = false,
                ActivatesDefault = true
            };

            Controller.ChangeAddressFieldEvent += delegate (string text,
                    string example_text) {

                Application.Invoke (delegate {
                        address_entry.Text      = text;
                        });
            };

            Controller.ChangeUserFieldEvent += delegate (string text,
                    string example_text) {

                Application.Invoke (delegate {
                        user_entry.Text      = text;
                        });
            };

            Controller.ChangePasswordFieldEvent += delegate (string text,
                    string example_text) {

                Application.Invoke (delegate {
                        password_entry.Text      = text;
                        });
            };

            address_entry.Changed += delegate {
                string error = Controller.CheckAddPage(address_entry.Text);
                if (!String.IsNullOrEmpty(error)) {
                    address_error_label.Markup = "<span foreground=\"red\">" + CmisSync.Properties_Resources.ResourceManager.GetString(error, CultureInfo.CurrentCulture) + "</span>";
                    address_error_label.Show();
                } else {
                    address_error_label.Hide();
                }
            };

            // Address
            layout_address_help.PackStart(address_help_label, false, false, 0);
            layout_address_help.PackStart(address_help_urlbox, false, false, 0);
            layout_address.PackStart (address_label, true, true, 0);
            layout_address.PackStart (address_entry, true, true, 0);
            layout_address.PackStart (layout_address_help, true, true, 0);
//            layout_address.PackStart (address_error_label, true, true, 0);

            // User
            layout_user.PackStart (new Label () {
                    Markup = "<b>" + CmisSync.Properties_Resources.User + ":</b>",
                    Xalign = 0
                    }, true, true, 0);
            layout_user.PackStart (user_entry, false, false, 0);

            // Password
            layout_password.PackStart (new Label () {
                    Markup = "<b>" + CmisSync.Properties_Resources.Password + ":</b>",
                    Xalign = 0
                    }, true, true, 0);
            layout_password.PackStart (password_entry, false, false, 0);

            layout_fields.PackStart (layout_user);
            layout_fields.PackStart (layout_password);

//            layout_vertical.PackStart (new Label (""), false, false, 0);
            layout_vertical.PackStart (layout_address, false, false, 0);
            layout_vertical.PackStart (layout_fields, false, false, 0);
            layout_vertical.PackStart (address_error_label, true, true, 0);

            Add (layout_vertical);

            // Cancel button
            Button cancel_button = new Button (cancelText);

            cancel_button.Clicked += delegate {
                Controller.PageCancelled ();
            };

            // Continue button
            Button continue_button = new Button (continueText) {
                Sensitive = String.IsNullOrEmpty( Controller.CheckAddPage (address_entry.Text))
            };

            continue_button.Clicked += delegate {
                // Show wait cursor
                this.GdkWindow.Cursor = wait_cursor;

                // Try to find the CMIS server (asynchronous using a delegate)
                GetRepositoriesFuzzyDelegate dlgt =
                    new GetRepositoriesFuzzyDelegate(CmisUtils.GetRepositoriesFuzzy);
                ServerCredentials credentials = new ServerCredentials() {
                    UserName = user_entry.Text,
                    Password = password_entry.Text,
                    Address = new Uri(address_entry.Text)
                };
                IAsyncResult ar = dlgt.BeginInvoke(credentials, null, null);
                while (!ar.AsyncWaitHandle.WaitOne(100)) {
                    while (Application.EventsPending()) {
                        Application.RunIteration();
                    }
                }
                Tuple<CmisServer, Exception> result = dlgt.EndInvoke(ar);
                CmisServer cmisServer = result.Item1;
                if(cmisServer != null)
                {
                    Controller.repositories = cmisServer.Repositories;
                    address_entry.Text = cmisServer.Url.ToString();
                }
                else
                {
                    Controller.repositories = null;
                }
                // Hide wait cursor
                this.GdkWindow.Cursor = default_cursor;

                if (Controller.repositories == null)
                {
                    // Show warning
                    string warning = "";
                    string message = result.Item2.Message;
                    Exception e = result.Item2;
                    if (e is CmisPermissionDeniedException)
                    {
                        warning = Properties_Resources.LoginFailedForbidden;
                    }
                    else if (e is CmisServerNotFoundException)
                    {
                        warning = Properties_Resources.ConnectFailure;
                    }
                    else if (e.Message == "SendFailure" && cmisServer.Url.Scheme.StartsWith("https"))
                    {
                        warning = Properties_Resources.SendFailureHttps;
                    }
                    else if (e.Message == "TrustFailure")
                    {
                        warning = Properties_Resources.TrustFailure;
                    }
                    else
                    {
                        warning = message + Environment.NewLine + Properties_Resources.Sorry;
                    }
                    address_error_label.Markup = "<span foreground=\"red\">" + warning + "</span>";
                    address_error_label.Show();
                }
                else
                {
                    // Continue to folder selection
                    Controller.Add1PageCompleted(
                            new Uri(address_entry.Text), user_entry.Text, password_entry.Text);
                }
            };

            Controller.UpdateAddProjectButtonEvent += delegate (bool button_enabled) {
                Application.Invoke (delegate {
                    continue_button.Sensitive = button_enabled;
                    if(button_enabled) {
                        continue_button.SetFlag(Gtk.WidgetFlags.CanFocus);
                        continue_button.SetFlag(Gtk.WidgetFlags.CanDefault);
                        continue_button.GrabDefault();
                    }
                });
            };

            AddButton (cancel_button);
            AddButton (continue_button);

            Controller.CheckAddPage (address_entry.Text);
            address_entry.GrabFocus ();
        }
        partial void OnContinue (MonoMac.Foundation.NSObject sender)
        {
            ServerCredentials credentials = new ServerCredentials() {
                UserName = UserText.StringValue,
                Password = PasswordText.StringValue,
                Address = new Uri(AddressText.StringValue)
            };
            AddressText.Enabled = false;
            UserText.Enabled = false;
            PasswordText.Enabled = false;
            ContinueButton.Enabled = false;
            CancelButton.Enabled = false;

            Thread check = new Thread(() => {
                Tuple<CmisServer, Exception> fuzzyResult = CmisUtils.GetRepositoriesFuzzy(credentials);
                CmisServer cmisServer = fuzzyResult.Item1;
                if (cmisServer != null)
                {
                    Controller.repositories = cmisServer.Repositories;
                }
                else
                {
                    Controller.repositories = null;
                }
                InvokeOnMainThread(delegate {
                    if (Controller.repositories == null)
                    {
                        WarnText.StringValue = Controller.getConnectionsProblemWarning(fuzzyResult.Item1, fuzzyResult.Item2);
                        AddressText.Enabled = true;
                        UserText.Enabled = true;
                        PasswordText.Enabled = true;
                        ContinueButton.Enabled = true;
                        CancelButton.Enabled = true;
                    }
                    else
                    {
                        RemoveEvent();
                        Controller.Add1PageCompleted(cmisServer.Url, credentials.UserName, credentials.Password.ToString());
                    }
                });
            });
            check.Start();
        }