public void TestEncryptionUtilReturnsNullForNullInput()
        {
            EncryptionUtil encryptor      = new EncryptionUtil(this.publicCertificate);
            string         encryptedLogin = encryptor.Encrypt(null);

            Assert.IsNull(encryptedLogin);
        }
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                USER_Service userService      = new USER_Service();
                bool         userAlreadyExist = userService.FindUserByUserName(model.Username) != null ||
                                                userService.FindByEmail(model.Email) != null;
                if (userAlreadyExist)
                {
                    ModelState.AddModelError("", UiStrings.register_error_user_already_exists);
                    return(View(model));
                }

                model.Password = EncryptionUtil.Encrypt(model.Password);
                var  user         = new USER().CreateFromModel(model);
                bool isRegistered = new USER_Service().AddOrUpdateUser(user);

                if (isRegistered)
                {
                    SetCurrentUser(user.USERNAME, user.PK_ID_USER);
                    return(RedirectToAction("Index", "Home"));
                }
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return(View(model));
        }
Esempio n. 3
0
 private static void EncryptData(UserModel model)
 {
     model.Password = EncryptionUtil.Encrypt(model.Password);
     model.Notes.ForEach(x =>
     {
         x.Content = EncryptionUtil.Encrypt(x.Content);
     });
 }
Esempio n. 4
0
 public async Task Create(User user, TrackingContext context)
 {
     user.Password = EncryptionUtil.Encrypt(user.Password, true);
     user.Active   = true;
     user.ID       = Guid.NewGuid().ToString();
     context.User.Add(user);
     await context.SaveChangesAsync();
 }
Esempio n. 5
0
        public void TestEncryptionBoundary()
        {
            Assert.Null(EncryptionUtil.Encrypt(""));
            Assert.Null(EncryptionUtil.Decrypt(""));

            Assert.Null(EncryptionUtil.Encrypt(null));
            Assert.Null(EncryptionUtil.Decrypt((byte[])null));
        }
        public void TestValidEncryptDecrypt()
        {
            var login = "******";

            EncryptionUtil encryptor      = new EncryptionUtil(this.publicCertificate);
            string         encryptedLogin = encryptor.Encrypt(login);

            Assert.AreEqual(login, this.Decrypt(encryptedLogin));
        }
        public void TestEncryptionUtilCanProcessEmptyString()
        {
            var login = "";

            EncryptionUtil encryptor      = new EncryptionUtil(this.publicCertificate);
            string         encryptedLogin = encryptor.Encrypt(login);

            Assert.AreEqual(login, this.Decrypt(encryptedLogin));
        }
Esempio n. 8
0
        public void UpdatePassword(int id, string loginPwd)
        {
            string password = SQLUtil.TrimNull(loginPwd);

            if (password.Length > 0)
            {
                password = EncryptionUtil.Encrypt(password);
            }
            this.userDao.UpdatePassword(id, password);
        }
Esempio n. 9
0
        /// <summary>
        /// 获取邮件地址
        /// </summary>
        /// <param name="controller">controller</param>
        /// <param name="action">方法名称</param>
        /// <returns>邮件地址</returns>
        public string GetLink4Email(string controller, string action)
        {
            string baseUrl = GetBaseUrl();

            string token = EncryptionUtil.Encrypt(Url.Action(action, controller));

            string fullUrl = string.Format("{0}/{1}/{2}?token={3}", baseUrl.TrimEnd('/'), ConstDefinition.HOME_CONTROLLER, ConstDefinition.HOME_ACTION, token);

            return(fullUrl);
        }
Esempio n. 10
0
        public bool AddTaskByViewModel(CreateTaskViewModel model)
        {
            var user = new USER();

            if (model.FK_ID_USER == 0)
            {
                user.EMAIL     = model.ShortEditUserViewModel.Email;
                user.FIRSTNAME = model.ShortEditUserViewModel.Firstname;
                user.LASTNAME  = model.ShortEditUserViewModel.Lastname;
                user.USERNAME  = model.ShortEditUserViewModel.Username;
                user.PASSWORD  = EncryptionUtil.Encrypt(model.ShortEditUserViewModel.Password);
            }
            else
            {
                // On update les infos user
                user = UoW.USER_Repository.GetByID(model.FK_ID_USER);

                user.LASTNAME  = model.ShortEditUserViewModel.Lastname;
                user.FIRSTNAME = model.ShortEditUserViewModel.Firstname;
                user.EMAIL     = model.ShortEditUserViewModel.Email;
            }

            bool userEdited = new USER_Service().AddOrUpdateUser(user);

            // on créé la tache
            var task = new TASK();

            task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.A_FAIRE;

            task.IS_PAID = false;

            task.CreateFromModel(model);

            //Mise à jour du montant de la transaction
            var transaction = UoW.TRANSACTION_Repository.GetByID(model.TransactionId);

            // si l'utilisateur est nouveau on en crée une
            if (transaction == null)
            {
                transaction = new TRANSACTION
                {
                    DATE_TRANSACTION      = DateTime.Now,
                    FK_ID_USER            = user.PK_ID_USER,
                    PAYPAL_TRANSACTION_ID = DateTime.Now.Ticks
                };
            }

            transaction.PRICE += task.PRICE ?? 0;
            new TRANSACTION_Service().AddOrUpdateTransaction(transaction);

            task.FK_ID_TRANSACTION = model.TransactionId != 0 ? model.TransactionId : transaction.PK_ID_TRANSACTION;
            task.FK_ID_USER        = model.FK_ID_USER != 0 ? model.FK_ID_USER : user.PK_ID_USER;

            return(AddOrUpdateTask(task));
        }
Esempio n. 11
0
        public void TestEncryptStringInstance()
        {
            string encryptedHello = EncryptionUtil.Encrypt("hello");

            Assert.NotNull(encryptedHello);
            Assert.AreEqual("5ow9IiHrgxf70OPplWItuQ==", encryptedHello);

            string decryptedHello = EncryptionUtil.Decrypt(encryptedHello);

            Assert.AreEqual("hello", decryptedHello);
        }
Esempio n. 12
0
        public void TestEncryptNonSerializableObjectInstance()
        {
            Stranger parent = new Stranger {
                Name = "Hello", Orphan = new Orphan {
                    Name = "World"
                }
            };

            byte[] encryptedParent = EncryptionUtil.Encrypt(parent);

            Assert.Null(encryptedParent);
        }
Esempio n. 13
0
        private static void ValidatePassword(string password, UserDto userDto)
        {
            var comparePassword = EncryptionUtil.Encrypt(password);

            if (userDto == null || comparePassword != userDto.Password)
            {
                throw new HttpResponseException("Invalid e-mail or password")
                      {
                          Status = HttpStatusCode.Unauthorized
                      };
            }
        }
Esempio n. 14
0
        public void Can_Encrypt_With_Random_Salt(string value, string expected)
        {
            var appSettingsMock = new Mock <IOptions <AppSettings> >();

            appSettingsMock.Setup(ac => ac.Value).Returns(new AppSettings {
                Salt = "secret"
            });
            var encryptionUtil = new EncryptionUtil(appSettingsMock.Object);
            var encrypted      = encryptionUtil.Encrypt(value, true);

            Assert.NotEqual(expected, encrypted);
        }
Esempio n. 15
0
        public UserInfo RegisterUser(UserInfo info, int phoneVerifyID)
        {
            info.LoginPwd        = EncryptionUtil.Encrypt(info.LoginPwd);
            info.Role.ID         = UserRole.User;
            info.IsActive        = true;
            info.VerifyStatus.ID = BusinessObjects.Domain.VerifyStatus.Pending;

            info = this.userDao.AddUser(info);

            this.userDao.UpdatePhoneVerifyIsUsed(phoneVerifyID);

            return(info);
        }
Esempio n. 16
0
        public void CompleteExample()
        {
            var          mySecretText         = "This is my secret";
            const string completeExampleAlias = "CompleteExample";
            var          encryptedBundle      = EncryptionUtil.Encrypt(context, completeExampleAlias, mySecretText);

            Assert.False(mySecretText == encryptedBundle.EncryptedText);

            var decryptedText = EncryptionUtil.Decrypt(context, completeExampleAlias, encryptedBundle);

            Assert.True(mySecretText == decryptedText,
                        string.Format("Expect {0} but got {1}", mySecretText, decryptedText));
        }
Esempio n. 17
0
        public void TestEncryptObjectInstance()
        {
            Parent parent = new Parent {
                Name = "Hello", Child = new Child {
                    Name = "World"
                }
            };

            byte[] encryptedParent = EncryptionUtil.Encrypt(parent);

            Assert.NotNull(encryptedParent);
            Assert.IsTrue(encryptedParent.LongLength > 0);
            Assert.AreEqual(384, encryptedParent.LongLength);
        }
        public ActionResult LoginAuto(ShortEditUserViewModel model)
        {
            model.Password = string.IsNullOrWhiteSpace(model.Password) ? "" : EncryptionUtil.Encrypt(model.Password);
            var user = new USER_Service().LoginUser(model.Username, model.Password);

            if (user != null)
            {
                SetCurrentUser(user.USERNAME, user.PK_ID_USER);

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View(model));
            }
        }
Esempio n. 19
0
        public void TestDecryptValidEncryptedByteArray()
        {
            Parent parent = new Parent {
                Name = "Hello", Child = new Child {
                    Name = "World"
                }
            };

            byte[] encryptedParent = EncryptionUtil.Encrypt(parent);

            Parent decryptedParent = (Parent)EncryptionUtil.Decrypt(encryptedParent);

            Assert.NotNull(decryptedParent);
            Assert.AreEqual("Hello", decryptedParent.Name);
            Assert.AreEqual("World", decryptedParent.Child.Name);
        }
Esempio n. 20
0
        private void WriteToClientConf()
        {
            byte[] userId = null;
            byte[] paswd  = null;
            if (UserId != string.Empty && Password != string.Empty)
            {
                userId = EncryptionUtil.Encrypt(UserId);
                paswd  = EncryptionUtil.Encrypt(Password);
            }

            //writing to config.ncconf
            config.ConfigVersion++;
            cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
            cacheServer.HotApplyBridgeReplicator(CacheName, false);

            ConveyToRegisteredNodes();
        }
        public async Task <dynamic> ChangePassword([FromBody] Authencation obj)
        {
            if (string.IsNullOrEmpty(obj.OldPassword))
            {
                return(BadRequest());
            }
            obj.OldPassword = EncryptionUtil.Encrypt(obj.OldPassword, true);
            var objDB = userService.UserExistToChange(obj, _context);

            if (objDB == null)
            {
                throw new Exception(Contants.NOTFOUND);
            }
            objDB.Password = EncryptionUtil.Encrypt(obj.Password, true);
            await userService.Update(objDB, _context);

            return(NoContent());
        }
        public ActionResult Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            model.Password = string.IsNullOrWhiteSpace(model.Password) ? "" : EncryptionUtil.Encrypt(model.Password);
            var user = new USER_Service().LoginUser(model.Username, model.Password);

            if (user != null)
            {
                SetCurrentUser(user.USERNAME, user.PK_ID_USER);
                FlashMessage.Confirmation(UiStrings.login_message_disconnected);
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("", UiStrings.login_error_invalid_connexion);
                return(View(model));
            }
        }
Esempio n. 23
0
        public int SaveUser(UserInfo info)
        {
            string password = SQLUtil.TrimNull(info.LoginPwd);

            if (password.Length > 0)
            {
                password = EncryptionUtil.Encrypt(password);
            }

            info.LoginPwd = password;
            if (info.ID > 0)
            {
                this.userDao.UpdateUser(info);
            }
            else
            {
                info = this.userDao.AddUser(info);
            }

            return(info.ID);
        }
Esempio n. 24
0
        private void AddLuceneAnalyzer()
        {
            if (!ValidateParameters())
            {
                return;
            }

            System.Reflection.Assembly asm = null;
            Alachisoft.NCache.Config.Dom.LuceneDeployment[] prov = null;
            string       failedNodes = string.Empty;
            string       serverName  = string.Empty;
            ICacheServer cacheServer = null;
            bool         successFull = true;

            try
            {
                if (Port != -1)
                {
                    NCache.Port = Port;
                }

                if (Port == -1)
                {
                    NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                }
                if (Server != null && Server != string.Empty)
                {
                    NCache.ServerName = Server;
                }

                try
                {
                    cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                }
                catch (Exception e)
                {
                    successFull = false;
                    OutputProvider.WriteErrorLine("Error: NCache service could not be contacted on server.");
                    return;
                }

                if (cacheServer != null)
                {
                    serverName = cacheServer.GetClusterIP();
                    if (cacheServer.IsRunning(CacheName))
                    {
                        successFull = false;
                        throw new Exception(CacheName + " is Running on " + cacheServer.GetClusterIP() + "\nStop the cache first and try again.");
                    }
                    Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig = cacheServer.GetNewConfiguration(CacheName);


                    if (serverConfig == null)
                    {
                        successFull = false;
                        throw new Exception("Specified cache is not registered on the given server.");
                    }
                    ToolsUtil.VerifyClusterConfigurations(serverConfig, CacheName);
                    try
                    {
                        asm = System.Reflection.Assembly.LoadFrom(AssemblyPath);
                    }
                    catch (Exception e)
                    {
                        successFull = false;
                        string message = string.Format("Could not load assembly \"" + AssemblyPath + "\". {0}", e.Message);
                        OutputProvider.WriteErrorLine("Error: {0}", message);
                        return;
                    }

                    if (asm == null)
                    {
                        successFull = false;
                        throw new Exception("Could not load specified assembly.");
                    }

                    if (serverConfig.CacheSettings.LuceneSettings == null)
                    {
                        serverConfig.CacheSettings.LuceneSettings = new Alachisoft.NCache.Config.Dom.LuceneSettings();
                    }

                    System.Type type = asm.GetType(Class, true);

                    if (!type.IsSubclassOf(typeof(Analyzer)))
                    {
                        successFull = false;
                        OutputProvider.WriteErrorLine("Error: Specified class does not implement Analyzer.");
                        return;
                    }
                    else
                    {
                        if (serverConfig.CacheSettings.LuceneSettings.Analyzers == null)
                        {
                            serverConfig.CacheSettings.LuceneSettings.Analyzers           = new Analyzers();
                            serverConfig.CacheSettings.LuceneSettings.Analyzers.Providers = prov;
                        }
                        prov = serverConfig.CacheSettings.LuceneSettings.Analyzers.Providers;
                        serverConfig.CacheSettings.LuceneSettings.Analyzers.Providers = GetAnalyzers(GetProvider(prov, asm));
                    }

                    byte[] userId = null;
                    byte[] paswd  = null;
                    if (UserId != string.Empty && Password != string.Empty)
                    {
                        userId = EncryptionUtil.Encrypt(UserId);
                        paswd  = EncryptionUtil.Encrypt(Password);
                    }
                    serverConfig.ConfigVersion++;
                    if (serverConfig.CacheSettings.CacheType == "clustered-cache")
                    {
                        foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes())
                        {
                            NCache.ServerName = node.IpAddress.ToString();
                            try
                            {
                                cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                                if (cacheServer.IsRunning(CacheName))
                                {
                                    throw new Exception(CacheName + " is Running on " + serverName +
                                                        "\nStop the cache first and try again.");
                                }

                                OutputProvider.WriteLine("Adding Analyzer on node '{0}' to cache '{1}'.", node.IpAddress, CacheName);
                                cacheServer.RegisterCache(CacheName, serverConfig, "", true, userId, paswd, false);
                            }
                            catch (Exception ex)
                            {
                                OutputProvider.WriteErrorLine("Failed to Lucene Analyzer on node '{0}'. ", serverName);
                                OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message);
                                failedNodes = failedNodes + "/n" + node.IpAddress.ToString();
                                successFull = false;
                            }
                            finally
                            {
                                cacheServer.Dispose();
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            OutputProvider.WriteLine("Adding Analyzer on node '{0}' to cache '{1}'.", serverName, CacheName);
                            cacheServer.RegisterCache(CacheName, serverConfig, "", true, userId, paswd, false);
                        }
                        catch (Exception ex)
                        {
                            OutputProvider.WriteErrorLine("Failed to Lucene Analyzer on node '{0}'. ", serverName);
                            OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message);
                            successFull = false;
                        }
                        finally
                        {
                            NCache.Dispose();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                successFull = false;
                OutputProvider.WriteErrorLine("Failed to Lucene Analyzer on node '{0}'. ", NCache.ServerName);
                OutputProvider.WriteErrorLine("Error : {0}", e.Message);
            }
            finally
            {
                NCache.Dispose();
                if (successFull && !IsUsage)
                {
                    OutputProvider.WriteLine("Analyzer successfully added");
                }
            }
        }
Esempio n. 25
0
        public AccountEnquiryResponseData getAccountEnquiry(AccountEnquiryPayload accountEnquiryPayload, Credentials credentials)
        {
            AccountEnquiryResponseData altResult = new AccountEnquiryResponseData();

            if (!Config.isCredentialAvailable(credentials))
            {
                altResult.data   = new AccountEnquiryDto();
                altResult.status = SdkResponseCode.CredentialStatus;
                altResult.data.responseDescription = Config.emptyCredentialResponse;
                altResult.data.responseCode        = Config.emptyCredentialResponseCode;
                return(altResult);
            }
            else
            {
                try
                {
                    EnvironmentConfig           environmentConfig = new EnvironmentConfig();
                    Dictionary <string, string> getHashValues     = environmentConfig.getRitsEnvironment(credentials);
                    Dictionary <string, int>    getEnvTimeOut     = environmentConfig.getTimeOut(credentials);
                    EncryptionUtil enUtil = new EncryptionUtil();

                    string url          = getHashValues["ACCOUNT_ENQUIRY_URL"];
                    long   milliseconds = DateTime.Now.Ticks;
                    string requestId    = accountEnquiryPayload.RequestId;
                    string hash_string  = getHashValues["API_KEY"] + requestId + getHashValues["API_TOKEN"];
                    string hashed       = Config.SHA512(hash_string);
                    var    accountNo    = accountEnquiryPayload.AccountNo;
                    var    bankCode     = accountEnquiryPayload.BankCode;

                    //HEADERS
                    List <Header> headers = new List <Header>();
                    headers.Add(new Header {
                        header = "Content-Type", value = "application/json"
                    });
                    headers.Add(new Header {
                        header = "API_DETAILS_HASH", value = hashed
                    });
                    headers.Add(new Header {
                        header = "REQUEST_TS", value = Config.getTimeStamp()
                    });
                    headers.Add(new Header {
                        header = "REQUEST_ID", value = requestId
                    });
                    headers.Add(new Header {
                        header = "API_KEY", value = getHashValues["API_KEY"]
                    });
                    headers.Add(new Header {
                        header = "MERCHANT_ID", value = getHashValues["MERCHANT_ID"]
                    });

                    var body = new
                    {
                        accountNo = enUtil.Encrypt(accountNo, getHashValues["KEY"], getHashValues["IV"]),
                        bankCode  = enUtil.Encrypt(bankCode, getHashValues["KEY"], getHashValues["IV"])
                    };

                    try
                    {
                        var response = WebClientUtil.PostResponse(url, JsonConvert.SerializeObject(body), headers);
                        result = JsonConvert.DeserializeObject <AccountEnquiryResponseData>(response);
                    }
                    catch (Exception e1)
                    {
                        altResult.data                     = new AccountEnquiryDto();
                        altResult.status                   = SdkResponseCode.CredentialStatus;
                        altResult.data.responseCode        = SdkResponseCode.ERROR_WHILE_CONNECTING_CODE;
                        altResult.data.responseDescription = SdkResponseCode.ERROR_WHILE_CONNECTING;
                        Console.WriteLine("ERROR : {0} ", SdkResponseCode.ERROR_WHILE_CONNECTING);
                        return(altResult);
                    }
                }
                catch (Exception e2)
                {
                    altResult.data                     = new AccountEnquiryDto();
                    altResult.status                   = SdkResponseCode.CredentialStatus;
                    altResult.data.responseCode        = SdkResponseCode.ERROR_PROCESSING_REQUEST_CODE;
                    altResult.data.responseDescription = SdkResponseCode.ERROR_PROCESSING_REQUEST;
                    Console.WriteLine("ERROR : {0} ", SdkResponseCode.ERROR_PROCESSING_REQUEST);
                    return(altResult);
                }
                return(result);
            }
        }
Esempio n. 26
0
        private void ConveyToRegisteredNodes()
        {
            byte[] userId = null;
            byte[] paswd  = null;
            if (UserId != string.Empty && Password != string.Empty)
            {
                userId = EncryptionUtil.Encrypt(UserId);
                paswd  = EncryptionUtil.Encrypt(Password);
            }


            string pId = "";
            NewCacheRegisterationInfo info = cacheServer.GetNewUpdatedCacheConfiguration(CacheName.ToLower(), pId, CacheServer, true);
            // Now update the cache configurations on all the servers where the cache
            //is registered...
            IPAddress address;
            string    clusterIp;
            bool      reregister = false;

            config.ConfigVersion++;
            foreach (string serverName in info.AffectedNodes)
            {
                if (info.AffectedPartitions.Count > 0)
                {
                    foreach (string partId in info.AffectedPartitions)
                    {
                        try
                        {
                            NCache            = new NCacheRPCService(serverName);
                            NCache.ServerName = serverName;
                            if (!IPAddress.TryParse(NCache.ServerName, out address))
                            {
                                clusterIp = cacheServer.GetClusterIP();
                                if (clusterIp != null && clusterIp != string.Empty)
                                {
                                    NCache.ServerName = clusterIp;
                                }
                            }
                            reregister  = true;
                            cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                            cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
                            cacheServer.HotApplyBridgeReplicator(CacheName, false);
                        }
                        catch (Exception ex)
                        {
                            OutputProvider.WriteErrorLine("Failed to Create Cache on '{0}'. ", NCache.ServerName);
                            OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message);
                        }
                        finally
                        {
                            cacheServer.Dispose();
                        }
                    }
                }
                else
                {
                    try
                    {
                        NCache.ServerName = serverName;
                        if (!IPAddress.TryParse(NCache.ServerName, out address))
                        {
                            clusterIp = cacheServer.GetClusterIP();
                            if (clusterIp != null && clusterIp != string.Empty)
                            {
                                NCache.ServerName = clusterIp;
                            }
                        }
                        reregister  = true;
                        cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                        cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
                        cacheServer.HotApplyBridgeReplicator(CacheName, false);
                    }
                    catch (Exception ex)
                    {
                        OutputProvider.WriteErrorLine("Failed to Create Cache on '{0}'. ", NCache.ServerName);
                        OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message);


                        NCache.Dispose();
                        return;
                    }
                    finally
                    {
                        cacheServer.Dispose();
                    }
                }
            }

            /*
             *
             * byte[] userId = null;
             * byte[] paswd = null;
             * if (UserId != string.Empty && Password != string.Empty)
             * {
             *  userId = EncryptionUtil.Encrypt(UserId);
             *  paswd = EncryptionUtil.Encrypt(Password);
             * }
             * Alachisoft.NCache.Bridging.Configuration.BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId);
             * List<TargetCacheCofiguration> previouslyAddedCaches = bridgeConfig.TargetCacheConfigList;
             * char[] separater = { ',' };
             * foreach (TargetCacheCofiguration pCache in previouslyAddedCaches)
             * {
             *  if (pCache.CacheID.ToLower().Equals(CacheId.ToLower()))
             *  {
             *      //if exists than remove
             *      foreach (string server in pCache.Servers.Split(separater).ToList())
             *      {
             *          NCacheRPCService nNCache = new NCacheRPCService(server);
             *          cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
             *          cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
             *          cacheServer.HotApplyBridgeReplicator(CacheId, false);
             *
             *      }
             *  }
             *
             * }
             * */
        }
Esempio n. 27
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        public void RemoveBridgeCache()
        {
            try
            {
                _bridgeService = new NCBridgeRPCService(BridgeServer);
                _bridgeServer  = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));

                NCacheRPCService nService = new NCacheRPCService(CacheServer);
                cacheServer = nService.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                if (!ValidateParameters())
                {
                    return;
                }

                //**********************************
                config = cacheServer.GetCacheConfiguration(CacheName);
                if (config == null)
                {
                    OutputProvider.WriteErrorLine("Error : The cache'{0}' does not exist on server {1}:{2} .", CacheName, NCache.ServerName, NCache.Port);
                    return;
                }
                {
                    //OutputProvider.WriteErrorLine("Error : The Bidge {0} is running on {1} , please stop Bridge and try again .", BridgeId, NCache.ServerName);
                    //return;
                }
                if (config.CacheType.ToLower().Equals("local-cache"))
                {
                    OutputProvider.WriteLine("Local Cache cannot be added as a bridge cache");
                    return;
                }
                //cacheServer = GetCacheServers(config.Cluster.GetAllConfiguredNodes());

                if (_bridgeServer != null)
                {
                    try
                    {
                        OutputProvider.WriteLine("Removing Cache To Bridge '{0}' on {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                        Alachisoft.NCache.Bridging.Configuration.BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId);

                        ToolsUtil.VerifyBridgeConfigurations(bridgeConfig, BridgeId);
                        if (bridgeConfig == null)
                        {
                            OutputProvider.WriteErrorLine("No Bridge with Bridge ID '{0} exists' on Server {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port);
                            return;
                        }

                        TargetCacheCofiguration targtCacheConfig = new TargetCacheCofiguration();
                        targtCacheConfig.CacheID     = CacheName;
                        targtCacheConfig.Servers     = cacheServer.GetHostName();
                        targtCacheConfig.IsConnected = true;
                        {
                            if (!VerifyBridgeMasterCache(BridgeId, false, bridgeConfig))
                            {
                                targtCacheConfig.IsMaster = true;
                            }
                            targtCacheConfig.Status = BridgeCacheStateParam.Active.ToString();
                        }

                        List <TargetCacheCofiguration> previouslyAddedCaches = bridgeConfig.TargetCacheConfigList;
                        int removedCacheIndex = -1;
                        if (previouslyAddedCaches.Count >= 1)
                        {
                            int iteration = 0;
                            //checking validations regarding bridge
                            foreach (TargetCacheCofiguration pCache in previouslyAddedCaches)
                            {
                                //if exists than remove
                                if (pCache.CacheID.ToLower().Equals(CacheName.ToLower()))
                                {
                                    if (pCache.CacheAlias.ToLower().Equals(Alias.ToLower()) || string.IsNullOrEmpty(Alias))
                                    {
                                        removedCacheIndex = iteration;
                                        if (pCache.IsMaster)
                                        {
                                            OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: Master cache cannot be removed ", BridgeId);
                                            return;
                                        }
                                    }
                                }
                                if (pCache.Status.Equals("passive"))
                                {
                                    OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: No both bridge caches can be passive ", BridgeId);
                                    return;
                                }
                                iteration++;
                            }
                        }
                        else
                        {
                            OutputProvider.WriteErrorLine("Failed to Remove Cache There is currently no Cache Added in Bridge {0} ", BridgeId);
                            return;
                        }
                        //
                        if (removedCacheIndex >= 0)
                        {
                            bridgeConfig.TargetCacheConfigList.RemoveAt(removedCacheIndex);
                        }
                        else
                        {
                            OutputProvider.WriteErrorLine("Bridge Cache Does not exists with name{0} in Bridge '{1}'", CacheName, BridgeId);
                            return;
                        }
                        //Adding Bridge to config.ncconf

                        BridgeConfig bridgeConf = config.Bridge;

                        config.Bridge = null;

                        byte[] userId = null;
                        byte[] paswd  = null;
                        if (UserId != string.Empty && Password != string.Empty)
                        {
                            userId = EncryptionUtil.Encrypt(UserId);
                            paswd  = EncryptionUtil.Encrypt(Password);
                        }

                        //writing to config.ncconf
                        config.ConfigVersion++;
                        cacheServer.ConfigureBridgeToCache(config, userId, paswd, true);
                        cacheServer.HotApplyBridgeReplicator(CacheName, false);

                        ConveyToRegisteredNodes();


                        char[] separater = { ',' };
                        // write in all bridge nodes bridge.nconnf file
                        bool write = false;
                        foreach (string bridgeIp in bridgeConfig.BridgeNodes.Split(separater).ToList())
                        {
                            try{
                                _bridgeService = new NCBridgeRPCService(bridgeIp);
                                _bridgeServer  = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));


                                _bridgeServer.RegisterBridge(bridgeConfig, true, true);
                                write = true;
                                OutputProvider.WriteLine("Removed Bridge Cache {0} From Bridge {1}", CacheName, BridgeId);
                            }
                            catch (Exception e)
                            {
                                OutputProvider.WriteErrorLine("Removing Bridge Cache {0} From Bridge Server{1} Gives Error: {2}", bridgeConf, bridgeIp, e.Message);
                            }
                        }
                    }
                    catch (SecurityException e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                    catch (Exception e)
                    {
                        OutputProvider.WriteErrorLine("Failed to Remove Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error: {0}", e.Message);
            }
            finally
            {
                if (_bridgeService != null)
                {
                    _bridgeService.Dispose();
                }
                if (NCache != null)
                {
                    NCache.Dispose();
                }
            }
        }
        private void AddLuceneQueryIndexDefaults()
        {
            if (!ValidateParameters())
            {
                return;
            }
            bool        successful = true;
            AssemblyDef asm        = null;

            //ArrayList cc = new ArrayList();
            Alachisoft.NCache.Config.Dom.Class[] queryClasses = null;
            string failedNodes = string.Empty;
            string serverName  = string.Empty;

            try
            {
                if (Port == -1)
                {
                    NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                }
                if (Server != null && Server != string.Empty)
                {
                    NCache.ServerName = Server;
                }
                if (Port != -1)
                {
                    NCache.Port = Port;
                }
                try
                {
                    cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                }
                catch (Exception e)
                {
                    OutputProvider.WriteErrorLine("Error: NCache service could not be contacted on server.");
                    return;
                }

                ToolsUtil.VerifyClusterConfigurations(cacheServer.GetNewConfiguration(CacheName), CacheName);


                string extension = ".dll";
                if (cacheServer != null)
                {
                    serverName = cacheServer.GetClusterIP();
                    if (cacheServer.IsRunning(CacheName))
                    {
                        throw new Exception(CacheName + " is Running on " + serverName +
                                            "\nStop the cache first and try again.");
                    }

                    serverConfig = cacheServer.GetNewConfiguration(CacheName);
                    //ConfiguredCacheInfo[] configuredCaches = cacheServer.GetAllConfiguredCaches();

                    if (serverConfig == null)
                    {
                        throw new Exception("Specified cache is not registered on the given server.");
                    }

                    //if (! Unregister)
                    //{
                    try
                    {
                        asm = AssemblyDef.LoadFrom(AssemblyPath);

                        extension = Path.GetExtension(asm.FullName);
                    }
                    catch (Exception e)
                    {
                        string message = string.Format("Could not load assembly \"" + AssemblyPath + "\". {0}", e.Message);
                        OutputProvider.WriteErrorLine("Error : {0}", message);
                        successful = false;
                        return;
                    }

                    if (asm == null)
                    {
                        throw new Exception("Could not load specified Assembly");
                    }

                    TypeDef type = asm.GetType(Class);


                    if (serverConfig.CacheSettings.QueryIndices == null)
                    {
                        serverConfig.CacheSettings.QueryIndices         = new Alachisoft.NCache.Config.Dom.QueryIndex();
                        serverConfig.CacheSettings.QueryIndices.Classes = queryClasses;
                    }

                    queryClasses = serverConfig.CacheSettings.QueryIndices.Classes;

                    serverConfig.CacheSettings.QueryIndices.Classes = GetSourceClass(GetClass(queryClasses, asm));


                    byte[] userId = null;
                    byte[] paswd  = null;
                    if (UserId != string.Empty && Password != string.Empty)
                    {
                        userId = EncryptionUtil.Encrypt(UserId);
                        paswd  = EncryptionUtil.Encrypt(Password);
                    }
                    serverConfig.ConfigVersion++;
                    if (serverConfig.CacheSettings.CacheType == "clustered-cache")
                    {
                        foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes())
                        {
                            NCache.ServerName = node.IpAddress.ToString();
                            try
                            {
                                cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                                if (cacheServer.IsRunning(CacheName))
                                {
                                    throw new Exception(CacheName + " is Running on " + serverName +
                                                        "\nStop the cache first and try again.");
                                }

                                OutputProvider.WriteLine("Adding query indexes on node '{0}' to cache '{1}'.", node.IpAddress, CacheName);
                                cacheServer.RegisterCache(CacheName, serverConfig, "", true, userId, paswd, false);
                            }
                            catch (Exception ex)
                            {
                                OutputProvider.WriteErrorLine("Failed to Add Query Index on '{0}'. ", serverName);
                                OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message);
                                failedNodes = failedNodes + "/n" + node.IpAddress.ToString();
                                successful  = false;
                            }
                            finally
                            {
                                cacheServer.Dispose();
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            OutputProvider.WriteLine("Adding query indexes on node '{0}' to cache '{1}'.", serverName, CacheName);
                            cacheServer.RegisterCache(CacheName, serverConfig, "", true, userId, paswd, false);
                        }
                        catch (Exception ex)
                        {
                            OutputProvider.WriteErrorLine("Failed to Add Query Index on '{0}'. ", serverName);
                            OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message);
                            successful = false;
                        }
                        finally
                        {
                            cacheServer.Dispose();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error : {0}", e.Message);
                successful = false;
            }
            finally
            {
                NCache.Dispose();
                if (successful && !IsUsage)
                {
                    OutputProvider.WriteLine("Query indexes successfully added.");
                }
            }
        }
Esempio n. 29
0
        private void AutoStartCaches(object StateInfo)
        {
            try
            {
                if (_autoStartDelay > 0)
                {
                    Thread.Sleep(_autoStartDelay * 1000);
                }
                CacheServerConfig[] configCaches = CacheConfigManager.GetConfiguredCaches();

                if (configCaches != null && configCaches.Length > 0)
                {
                    foreach (CacheServerConfig cacheServerConfig in configCaches)
                    {
                        if (cacheServerConfig.AutoStartCacheOnServiceStartup && !cacheServerConfig.IsRunning && cacheServerConfig.InProc == false)
                        {
                            try
                            {
                                _nchost.CacheServer.StartCache(cacheServerConfig.Name.Trim(), EncryptionUtil.Encrypt(ServiceConfiguration.CacheUserName), EncryptionUtil.Encrypt(ServiceConfiguration.CacheUserPassword != null ? Protector.DecryptString(ServiceConfiguration.CacheUserPassword) : null));
                                //CacheServerModerator.StartCache(cacheServerConfig.Name.Trim(), userId, password);
                                // AppUtil.LogEvent(_cacheserver, "The cache  '" + cacheServerConfig.Name.Trim() + "' started successfully.", EventLogEntryType.Information, EventCategories.Information, EventID.CacheStart);

                                if (_cacheStartDelay > 0)
                                {
                                    Thread.Sleep(_cacheStartDelay * 1000);
                                }
                            }
                            catch (Exception ex)
                            {
                                //   AppUtil.LogEvent(_cacheserver, "Exception Message  '" + ex, EventLogEntryType.Information, EventCategories.Information, EventID.CacheStart);
                            }// all exceptions are logged in event logs. and are ignored here.
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //  AppUtil.LogEvent(_cacheserver, "An error occurred while auto-starting caches. " + ex.ToString(), EventLogEntryType.Error, EventCategories.Error, EventID.CacheStartError);
            }
        }
Esempio n. 30
0
        public bool Authencation(Authencation login, TrackingContext context)
        {
            string Password = EncryptionUtil.Encrypt(login.Password, true);

            return(context.User.Any(u => u.UserName == login.UserName && u.Password == Password && u.Active));
        }