public ActionResult Return(string orderId) { PGResponse oPgResp = new PGResponse(); EncryptionUtil lEncUtil = new EncryptionUtil(); string respcd = null; string respmsg = null; string astrResponseData = null; string strMerchantId, astrFileName = null; string strKey = null; string strDigest = null; string astrsfaDigest = null; strMerchantId = "96084546"; astrFileName = "c://key//96084546.key"; if (Request.ServerVariables["REQUEST_METHOD"] == "POST") { astrResponseData = Request.Form["DATA"]; strDigest = Request.Form["EncryptedData"]; astrsfaDigest = lEncUtil.getHMAC(astrResponseData, astrFileName, strMerchantId); if (strDigest.Equals(astrsfaDigest)) { oPgResp.getResponse(astrResponseData); respcd = oPgResp.RespCode; respmsg = oPgResp.RespMessage; if(Int32.Parse(respcd) == 0) { var order = _orderService.GetOrderById(Int32.Parse(orderId)); if (_orderProcessingService.CanMarkOrderAsPaid(order)) { _orderProcessingService.MarkOrderAsPaid(order); } //Thank you for shopping with us. Your credit card has been charged and your transaction is successful return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }); } return Content("Transaction Decline"); } else { return RedirectToAction("Index", "Home", new { area = "" }); } } else { return RedirectToAction("Index", "Home", new { area = "" }); } }
public ActionResult ReturnDistributedOrder(string orderId) { PGResponse oPgResp = new PGResponse(); EncryptionUtil lEncUtil = new EncryptionUtil(); string respcd = null; string respmsg = null; string astrResponseData = null; string strMerchantId, astrFileName = null; string strKey = null; string strDigest = null; string astrsfaDigest = null; strMerchantId = "96084546"; astrFileName = "c://key//96084546.key"; if (Request.ServerVariables["REQUEST_METHOD"] == "POST") { astrResponseData = Request.Form["DATA"]; strDigest = Request.Form["EncryptedData"]; astrsfaDigest = lEncUtil.getHMAC(astrResponseData, astrFileName, strMerchantId); if (strDigest.Equals(astrsfaDigest)) { oPgResp.getResponse(astrResponseData); respcd = oPgResp.RespCode; respmsg = oPgResp.RespMessage; if(Int32.Parse(respcd) == 0) { var orderTransactinDetail = _orderService.GetOrderByTxnId(new Guid(orderId)); var order = _orderService.GetOrderById(orderTransactinDetail.OrderId); orderTransactinDetail.PaymentStatusId = (int)PaymentStatus.Paid; decimal amountpaid = 0; foreach (var paymentInfo in order.OrderTransactionDetailItems) { if (paymentInfo.PaymentStatusId == (int)PaymentStatus.Paid) amountpaid = amountpaid + paymentInfo.TransactionAmount; } order.TotalTransactionAmount = amountpaid; if (order.OrderStatus == Core.Domain.Orders.OrderStatus.Booked || order.OrderStatus == Core.Domain.Orders.OrderStatus.Confirmed) { order.OrderStatus = Core.Domain.Orders.OrderStatus.OrderPaymentComplete; } _orderService.UpdateOrder(order); _orderService.UpdateOrderTransactionDetail(orderTransactinDetail); //Thank you for shopping with us. Your credit card has been charged and your transaction is successful return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }); } else { return Content("Transaction Declined"); } } else { return RedirectToAction("Index", "Home", new { area = "" }); } } else { return RedirectToAction("Index", "Home", new { area = "" }); } }
public void RemoveBridge() { try { if (!ValidateParameters()) { return; } _bridgeService = new NCBridgeRPCService(Server); if (Port == -1) { _bridgeService.Port = _bridgeService.UseTcp ? BridgeConfigurationManager.NCacheTcpPort : BridgeConfigurationManager.NCacheHttpPort; } else { _bridgeService.Port = Port; } _bridgeService.ServerName = Server; _bridgeServer = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30)); BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId); byte[] userId = null; byte[] paswd = null; if (UserId != string.Empty && Password != string.Empty) { userId = EncryptionUtil.Encrypt(UserId); paswd = EncryptionUtil.Encrypt(Password); } if (bridgeConfig.GetBridgeNodeList().Count == 2) { _bridgeServer.UnRegisterBridge(BridgeId); if (bridgeConfig.BridgeNodes.Contains(_bridgeServer + ",")) { bridgeConfig.BridgeNodes = bridgeConfig.BridgeNodes.Replace(_bridgeServer + ",", ""); } else { bridgeConfig.BridgeNodes = bridgeConfig.BridgeNodes.Replace("," + _bridgeServer, ""); } bridgeConfig.BridgeActive = bridgeConfig.BridgeNodes; NCBridgeRPCService _bridge = new NCBridgeRPCService(bridgeConfig.BridgeActive); IBridgeServer _server = _bridge.GetBridgeServer(TimeSpan.FromSeconds(30)); _server.UnRegisterBridge(BridgeId); } else { _bridgeServer.UnRegisterBridge(BridgeId); } bridgeConfig.BridgeNodes = ""; //updating target cache config if (bridgeConfig.TargetCacheConfigList != null) { foreach (TargetCacheCofiguration targetCacheConfig in bridgeConfig.TargetCacheConfigList) { try { if (targetCacheConfig != null) { foreach (string server in targetCacheConfig.Servers.Split(',')) { NCacheRPCService NCache = new NCacheRPCService(server);; ICacheServer cacheServer = null; cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); string cacheID = targetCacheConfig.CacheID.ToString(); CacheServerConfig serverConfig = cacheServer.GetCacheConfiguration(cacheID); if (serverConfig.Bridge != null) { serverConfig.Bridge = null; } serverConfig.ConfigVersion++; cacheServer.ConfigureBridgeToCache(serverConfig, userId, paswd, false); } } } catch (Exception ex) { OutputProvider.WriteErrorLine(ex.Message); return; } } } OutputProvider.WriteLine("Bridge removed."); } catch (Exception e) { OutputProvider.WriteErrorLine("Bridge not registered on server.\n"); OutputProvider.WriteErrorLine("Error: " + e.Message); return; } }
/// <summary> /// socket read byte array. /// </summary> /// <param name="context"></param> /// <param name="message"></param> public override void ChannelRead(IChannelHandlerContext context, object message) { var packet = message as PacketRequest <IMessage>; if (packet == null) { return; } PacketResponse <IMessage> packetResponse = null; try { switch (packet.CommandId) { //获取雇员信息 case 1001: //解析 var requestDTO = packet.Body as TestRequestDTO; //回复 var response = new PacketResponse <TestResponseDTO>(); response.CommandId = 1001; var errorResponse = new TestResponseDTO { Code = 400, Message = "Illegal message parsing failed!!!" }; if (requestDTO == null) { response.Body = errorResponse; } else { var hashVal = requestDTO.HashValue; //var uid = requestDTO.Account; //var pwd = requestDTO.Passworld; var nonce = requestDTO.Nonce; var sign = requestDTO.Sign; var time = requestDTO.ValidateTime; var isVerification = EncryptionUtil.Verification(hashVal, nonce, sign, time); if (isVerification) { response.Body = new TestResponseDTO { Code = 200, Employees = new List <string> { "zhang san", "li si", "wang wu", "zhao liu" } }; } else { response.Body = errorResponse; } if (!isVerification) { context.WriteAndFlushAsync(packetResponse); context.CloseAsync(); } } context.WriteAndFlushAsync(packetResponse); break; } } catch (Exception ex) { Console.WriteLine($"Server request read error { ex.Message }"); } }
private void ConveyToRegisteredNodes() { 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 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)); config.ConfigVersion++; cacheServer.ConfigureBridgeToCache(config, userId, paswd, true); cacheServer.HotApplyBridgeReplicator(CacheName, false); } } /* 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(CacheId.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; * 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(CacheId, false); * * } * catch (Exception ex) * { * OutputProvider.WriteErrorLine("Failed to Create Cache on '{0}'. ", NCache.ServerName); * OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message); * * ToolsUtil.LogEvent(ex.Message, "Add Bridge Cache Base"); * } * 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(CacheId, false); * * } * catch (Exception ex) * { * OutputProvider.WriteErrorLine("Failed to Create Cache on '{0}'. ", NCache.ServerName); * OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message); * * ToolsUtil.LogEvent(ex.Message, "BridgeCacheBase"); * NCache.Dispose(); * return; * } * finally * { * cacheServer.Dispose(); * } * } * } */ }
public ActionResult Index(string phone, string sso_data, string sso_auth, string callrecid) { //return View(new ParaCallCenterIndex //{ // Phone = "13683459249", // SSO_data = new SSOData{Name="admin",OperatorId = "1"} // //SSO_auth = sso_auth, // //SSO_data = model, // //Callrecid = callrecid //}); //var str = "phone=18965017897&sso_auth=79d9cfc395bb99f05dad903eb8b55366&sso_data=%257B%2522clgNumber%2522%253A%25228010%2522%252C%2522company%2522%253A%2522pskj%2522%252C%2522crmaccount%2522%253Anull%252C%2522crmpwd%2522%253Anull%252C%2522groupid%2522%253A%25221%2522%252C%2522name%2522%253A%25228017%2522%252C%2522operatorid%2522%253A%25228017%2522%252C%2522password%2522%253A%25228017%2522%252C%2522ts%2522%253A%25221376361153%2522%257D&callrecid=00018629416751546&calloutid=0&area=%E7%A6%8F%E5%BB%BA%E7%9C%81%E7%A6%8F%E5%B7%9E%E5%B8%82&accnum=888888&ivrnode=1&websid= 7777"; //var test =HttpUtility.UrlDecode(str); ////var test1 = HttpUtility.UrlDecodeToBytes(str); //var test2 = HttpUtility.UrlDecode(test); SSOData model; try { model = new JavaScriptSerializer().Deserialize <SSOData>(HttpUtility.UrlDecode(sso_data)); } catch (Exception ex) { SysLog.Instance.Error(LogStatus.系统日志来源.后台, ex.Message + "\n\rQueryString:" + Request.QueryString, LogStatus.系统日志目标类型.用户, 0, ex); throw; } //log var ip = HttpContext.Request.ServerVariables["REMOTE_ADDR"]; //if(!ip.StartsWith("192.168.10")) //SysLog.Instance.Info(LogStatus.系统日志来源.后台, Request.QueryString.ToString(),LogStatus.系统日志目标类型.用户,0, ip);//marked for ip recorded /* authencation * sso_auth 认证参数。统一小写。MD5(key+sso_data) * MD5(key+sso_data)==model.SSO_auth */ //var hashCode = EncryptionUtil.MD5Encrypt(Key + HttpUtility.UrlDecode(sso_data)); // var hashCode = EncryptionUtil.MD5Encrypt(Key + HttpUtility.UrlEncode(sso_data)); var hashCode = EncryptionUtil.EncryptWithMd5(Key + HttpUtility.UrlEncode(sso_data)); if (sso_auth == hashCode) { if (model.Name.ToLower() == "admin") { Response.Charset = Encoding.UTF8.WebName; Response.StatusCode = 401; Response.Write("<h1> admin 用户被拒绝</h1>"); Response.End(); SysLog.Instance.Warn(LogStatus.系统日志来源.后台, "呼叫中心登录:" + model.Name + " 拒绝", LogStatus.系统日志目标类型.用户, 0, -1); return(null); } var result = AdminAuthenticationBo.Instance.Login(model.Name); //var result = AdminAuthenticationBo.Instance.Login("admin"); //admin to demo if (!result.Status) { SysLog.Instance.Warn(LogStatus.系统日志来源.后台, "呼叫中心登录:" + model.Name + " " + result.Status + "," + result.Message, LogStatus.系统日志目标类型.用户, 0, -1); //Response.Write("<script>alert('" + result .Message+ "!');</script>"); Response.Charset = Encoding.UTF8.WebName; Response.StatusCode = 401; Response.Write("<h1>" + result.Message + "</h1>"); Response.End(); return(null); } else { SysLog.Instance.Info(LogStatus.系统日志来源.后台, "呼叫中心登录:" + model.Name + "(" + result.Data.UserName + ")" + " " + result.Message, LogStatus.系统日志目标类型.用户, result.Data.SysNo, result.Data.SysNo); } } else { //not authorized //return Redirect("/Shared/Error404"); //return new HttpStatusCodeResult(HttpStatusCode.Unauthorized); //Response.Write("<script>alert('" + result .Message+ "!');</script>"); SysLog.Instance.Warn(LogStatus.系统日志来源.后台, "SSO_auth消息验证失败hashcode:" + hashCode + "\n\rQueryString:" + Request.QueryString, LogStatus.系统日志目标类型.用户, -1, -1); Response.Write(string.Format("<h1>SSO_auth消息验证失败sso_auth:{0} hashcode:{1}</h1>", sso_auth, hashCode)); Response.End(); return(null); } //retrieve the data needed //sysno from crcustomer by phone--which is the account in customer var cus = CrCustomerBo.Instance.GetCrCustomer(phone); if (cus != null) { ViewBag.cusSysNo = cus.SysNo; ViewBag.cusAccount = model.Name; } return(View(new ParaCallCenterIndex { Phone = phone, SSO_auth = sso_auth, SSO_data = model, Callrecid = callrecid })); }
public void AddDeviceSpecificInfo(BILog log) { string deviceAdvertisingId = this.GetDeviceAdvertisingId(); log.AddParam("google_advertising_id", EncryptionUtil.EncryptString(deviceAdvertisingId)); }
public async Task UpdatePassword(int userId, string newPassword) { newPassword = EncryptionUtil.Encrypt(newPassword); await _userRepository.UpdatePassword(userId, newPassword); }
private static void NewMethod3() { StudyOnlineEntities entities = new StudyOnlineEntities(); DateTime now = DateTime.Now; for (int i = 1; i <= 150; i++) { //创建帐号 NimUser nimuser = new NimUser() { Accid = Guid.NewGuid().ToString().Replace("-", ""), Category = 0, IsActive = 1, IsEnable = 1, Username = String.Format("CFFD{0:D3}", i), Password = EncryptionUtil.Md5Encode("00000000"), CreateDate = now, NimUserEx = new NimUserEx() { Coins = 600 } }; //同步云信 String json = NimUtil.UserCreate(nimuser.Accid, null, null, null); Answer a = JsonConvert.DeserializeObject <Answer>(json); if (a.code == 200) { nimuser.Token = a.info.token; } //保存数据 entities.NimUser.Add(nimuser); Console.WriteLine("帐号:{0},密码:{2},学币:{1},accid={3},token={4}", nimuser.Username, nimuser.NimUserEx.Coins, nimuser.Password, nimuser.Accid, nimuser.Token); } entities.SaveChanges(); }
private void AddLucenePattern() { if (!ValidateParameters()) { return; } System.IO.FileInfo fInfo = 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 { fInfo = new System.IO.FileInfo(FilePath); } catch (Exception e) { successFull = false; string message = string.Format("Could not load file \"" + FilePath + "\". {0}", e.Message); OutputProvider.WriteErrorLine("Error: {0}", message); return; } if (serverConfig.CacheSettings.LuceneSettings == null) { serverConfig.CacheSettings.LuceneSettings = new Alachisoft.NCache.Config.Dom.LuceneSettings(); } if (fInfo.Extension != ".txt") { successFull = false; string message = string.Format("\"" + FilePath + "\" is not a Text file. {0}"); OutputProvider.WriteErrorLine("Error: {0}", message); return; } if (serverConfig.CacheSettings.LuceneSettings.Patterns == null) { serverConfig.CacheSettings.LuceneSettings.Patterns = new Patterns(); } if (serverConfig.CacheSettings.LuceneSettings.Patterns.Providers != null) { prov = serverConfig.CacheSettings.LuceneSettings.Patterns.Providers; } serverConfig.CacheSettings.LuceneSettings.Patterns.Providers = GetPatterns(GetProvider(prov, fInfo)); 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 Lucene Pattern 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 Lucene Pattern '{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 Lucene Pattern on node '{0}' to cache '{1}'.", serverName, CacheName); cacheServer.RegisterCache(CacheName, serverConfig, "", true, userId, paswd, false); } catch (Exception ex) { OutputProvider.WriteErrorLine("Failed to Add Lucene Pattern on '{0}'. ", serverName); OutputProvider.WriteErrorLine("Error Detail: '{0}'. ", ex.Message); successFull = false; } finally { NCache.Dispose(); } } } } catch (Exception e) { successFull = false; OutputProvider.WriteErrorLine("Failed to Add Lucene Pattern on node '{0}'. ", NCache.ServerName); OutputProvider.WriteErrorLine("Error : {0}", e.Message); } finally { NCache.Dispose(); if (successFull && !IsUsage) { OutputProvider.WriteLine("Patterns file successfully added"); } } }
/// <summary> /// The main entry point for the tool. /// </summary> public void AddBridgeCache() { try { if (!ValidateParameters()) { return; } _bridgeService = new NCBridgeRPCService(BridgeServer); if (Port == -1) { _bridgeService.Port = _bridgeService.UseTcp ? BridgeConfigurationManager.NCacheTcpPort : BridgeConfigurationManager.NCacheHttpPort; } else { _bridgeService.Port = Port; } if (!string.IsNullOrEmpty(BridgeServer)) { _bridgeService.ServerName = BridgeServer; } _bridgeServer = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30)); NCacheRPCService nService = new NCacheRPCService(CacheServer); cacheServer = nService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); //********************************** 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; } 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("Adding Cache To Bridge '{0}' on {1}:{2}.", BridgeId, _bridgeService.ServerName, _bridgeService.Port); Alachisoft.NCache.Bridging.Configuration.BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(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.CacheAlias = Alias; // set the Alias, null if name is different. Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig = cacheServer.GetNewConfiguration(CacheName); string servers = String.Empty; foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes()) { servers += node.IpAddress + ","; } servers = servers.Remove(servers.Length - 1); targtCacheConfig.Servers = servers; targtCacheConfig.IsConnected = true; if (State.Equals(BridgeCacheStateParam.Active)) { if (!VerifyBridgeMasterCache(BridgeId, false, bridgeConfig)) { targtCacheConfig.IsMaster = true; } targtCacheConfig.Status = BridgeCacheStateParam.Active.ToString(); } else { targtCacheConfig.Status = BridgeCacheStateParam.Passive.ToString(); } ToolsUtil.VerifyBridgeConfigurations(bridgeConfig, BridgeId); List <TargetCacheCofiguration> previouslyAddedCaches = bridgeConfig.TargetCacheConfigList; if (previouslyAddedCaches.Count <= 1) { //checking validations regarding bridge foreach (TargetCacheCofiguration pCache in previouslyAddedCaches) { if (pCache.CacheID.ToLower().Equals(targtCacheConfig.CacheID.ToLower())) { OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error:No Same Cache Can be Added Twice ", BridgeId); return; } if (pCache.Status.Equals("passive")) { OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error:No both bridge caches can be passive ", BridgeId); return; } } } else { OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error:No More than 2 caches can be add at a time ", BridgeId); return; } // //Adding Bridge to config.ncconf BridgeConfig bridgeConf = new BridgeConfig(); bridgeConf.CacheAlias = Alias; bridgeConf.Id = BridgeId; if (config != null) { bridgeConf.Servers = bridgeConfig.BridgeNodes; bridgeConf.Port = bridgeConfig.BridgePort; bridgeConf.Status = State.ToString(); } config.Bridge = bridgeConf; 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); Alachisoft.NCache.Config.NewDom.CacheServerConfig nConfig = cacheServer.GetNewConfiguration(CacheName); foreach (Address node in nConfig.CacheDeployment.Servers.GetAllConfiguredNodes()) { NCache.ServerName = node.IpAddress.ToString(); ICacheServer server = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); server.ConfigureBridgeToCache(config, userId, paswd, true); server.HotApplyBridgeReplicator(CacheName, false); } ConveyToRegisteredNodes(); char [] separater = { ',' }; bridgeConfig.TargetCacheConfigList.Add(targtCacheConfig); // write in all bridge nodes bridge.nconnf file bridgeConfig.DeploymentVersion++; foreach (string bridgeIp in bridgeConfig.BridgeNodes.Split(separater).ToList()) { _bridgeService = new NCBridgeRPCService(bridgeIp); _bridgeServer = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30)); _bridgeServer.RegisterBridge(bridgeConfig, true, true); } OutputProvider.WriteLine("{0} successfully added to BridgeID {1}", CacheName, BridgeId); } catch (SecurityException e) { OutputProvider.WriteErrorLine("Failed to Add Cache to bridge '{0}'. Error: {1} ", BridgeId, e.Message); } catch (Exception e) { OutputProvider.WriteErrorLine("Failed to Add 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(); } } }
/* * 验证是否注册 * * errorCode=1001,提示用户,点击关闭软件(需要注册) * * errorCode=1002,提示用户,可以继续试用(非静默试用) * * errorCode=1003,不提示用户,继续试用(静默试用) * */ public BaseResult isReg() { BaseResult baseResult = new BaseResult(); baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "未知"; //1.获取数据库信息,并验证数据完整性 Cfg2 cfg2 = cfg2Bll.get(1); string machineCode = MachineCodeUtil.GetMachineCodeString(); //3.注册码是否存在,存在则验证 if (!string.IsNullOrWhiteSpace(cfg2.rg3)) { if (RegCodeUtil.isRightOfRegCode(cfg2.rg3, machineCode)) { baseResult.result = true; baseResult.errorCode = 0; baseResult.message = "注册码正确"; return(baseResult); } else { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "注册码无效"; return(baseResult); } } //4.验证数据库注册日期是否存在,不存在则填写 if (!string.IsNullOrWhiteSpace(cfg2.sd)) { if (cfg2.sd == "sgfdo_fdgrexfhtreKUFSSA") { //第一次打开软件 TimeSpan ts1 = DateTime.Now - DateTime.Parse("1970-1-1"); int regDay = (int)Math.Floor(ts1.TotalDays); cfg2.sd = EncryptionUtil.encode(regDay.ToString(), machineCode); cfg2.cd = cfg2.sd; if (string.IsNullOrWhiteSpace(cfg2.ld)) { int limitDay = regDay + 30; cfg2.ld = EncryptionUtil.encode(limitDay.ToString(), machineCode); } string validateCode1 = RegCodeUtil.generateValidateCode(cfg2, machineCode); cfg2.validateCode = validateCode1; cfg2 = cfg2Bll.update(cfg2); baseResult.result = false; baseResult.errorCode = 1003; baseResult.message = "第一次打开软件"; return(baseResult); } } else { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "注册日期异常(空),试用结束"; return(baseResult); } //2.数据完整性校验 if (RegCodeUtil.validate(cfg2, machineCode) == false) { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "数据完整性校验失败"; return(baseResult); } //5.1 获取开始时间 string sdStr = EncryptionUtil.decode(cfg2.sd, machineCode); if (!DataUtil.isInt(sdStr)) { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "注册日期异常(非整数),试用结束"; return(baseResult); } else if (Int32.Parse(sdStr) < 0) { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "注册日期异常(小于0),试用结束"; return(baseResult); } int sd = DataUtil.ToInt(sdStr); //5.2获取数据库中截止日期 string ldStr = EncryptionUtil.decode(cfg2.ld, machineCode); int ld = DataUtil.ToInt(ldStr); //5.3获取数据库中当前时间 string cdStr_old = EncryptionUtil.decode(cfg2.cd, machineCode); int cd_old = DataUtil.ToInt(cdStr_old); //5.4 获取当前时间,并比较 TimeSpan ts2 = DateTime.Now - DateTime.Parse("1970-1-1"); int cd = (int)Math.Floor(ts2.TotalDays); if (cd_old > cd) { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "计算机时间异常,试用结束"; return(baseResult); } //6.注册日期>截止日期,试用结束 if (cd > ld) { baseResult.result = false; baseResult.errorCode = 1001; baseResult.message = "试用结束"; return(baseResult); } //7. 更新当前日期 cfg2.cd = EncryptionUtil.encode(cd.ToString(), machineCode); string validateCode2 = RegCodeUtil.generateValidateCode(cfg2, machineCode); cfg2.validateCode = validateCode2; cfg2 = cfg2Bll.update(cfg2); //8. 剩余试用天数,当restDays<10,则弹窗提示 int restDays = ld - cd; if (restDays < 10) { baseResult.result = false; baseResult.errorCode = 1002; baseResult.message = restDays + " 天后,试用结束"; return(baseResult); } baseResult.result = false; baseResult.errorCode = 1003; baseResult.message = restDays + " 天后,试用结束"; return(baseResult); //baseResult.result = false; //baseResult.errorCode = 1002; //baseResult.message = restDays + " 天后,试用结束"; //return baseResult; }
private void ConfigJwtAuthentication(IServiceCollection services) { var symmetricKey = Convert.FromBase64String(EncryptionUtil.ToBase64Encode("123456abcdefqwer")); services.AddAuthentication(x => { x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(symmetricKey), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; x.Events = new JwtBearerEvents() { OnAuthenticationFailed = async context => { Console.WriteLine("ABCDDDDDDDDDDDDDDDDDDD"); var apiErrorMessage = new ApiErrorMessage(); var statusCode = HttpStatusCode.Unauthorized; if (context.Exception is SecurityTokenExpiredException) { apiErrorMessage.ErrorCode = (int)ErrorCodeEnum.ACCESS_TOKEN_IS_EXPIRED; apiErrorMessage.ErrorMessage = ErrorMessageConstant.ACCESS_TOKEN_IS_EXPIRED; } else { apiErrorMessage.ErrorCode = (int)ErrorCodeEnum.ACCESS_TOKEN_IS_INVALID; apiErrorMessage.ErrorMessage = ErrorMessageConstant.ACCESS_TOKEN_IS_INVALID; statusCode = (HttpStatusCode.Forbidden); } var apiResponseException = new ApiResponseException() { ErrorMessages = new List <ApiErrorMessage> { apiErrorMessage }, StatusCode = statusCode }; var apiResponse = new ApiSingleResponse <string>() { Data = null, Errors = apiResponseException.ErrorMessages }; context.Response.StatusCode = (int)statusCode; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonSerializer.Serialize(apiResponse, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); } }; }); }
public void RemoveBridgeNode() { try { _bridgeService = new NCBridgeRPCService(Server); if (!ValidateParameters()) { return; } _bridgeServer = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30)); BridgeConfiguration bridgeConfig = _bridgeServer.GetBridgeConfiguration(BridgeId); if (!ToolsUtil.VerifyBridgeConfigurations(bridgeConfig, BridgeId)) { OutputProvider.WriteErrorLine("Error: Configuration mismatch."); return; } byte[] userId = null; byte[] paswd = null; if (UserId != string.Empty && Password != string.Empty) { userId = EncryptionUtil.Encrypt(UserId); paswd = EncryptionUtil.Encrypt(Password); } if (DeleteBridgeNode == Server) { _bridgeServer.UnRegisterBridge(BridgeId); } else { NCBridgeRPCService _removeBridgeService = new NCBridgeRPCService(DeleteBridgeNode); IBridgeServer _removeServer = _removeBridgeService.GetBridgeServer(TimeSpan.FromSeconds(30)); _removeServer.UnRegisterBridge(BridgeId); } if (bridgeConfig != null) { if (bridgeConfig.GetBridgeNodeList().Count == 1) { bridgeConfig.BridgeNodes = ""; } else if (bridgeConfig.BridgeNodes.Contains(DeleteBridgeNode + ",")) { bridgeConfig.BridgeNodes = bridgeConfig.BridgeNodes.Replace(DeleteBridgeNode + ",", ""); } else { bridgeConfig.BridgeNodes = bridgeConfig.BridgeNodes.Replace("," + DeleteBridgeNode, ""); } if (bridgeConfig.GetBridgeNodeList().Count == 0) { bridgeConfig.BridgeActive = string.Empty; } else { bridgeConfig.BridgeActive = bridgeConfig.BridgeNodes; } bridgeConfig.DeploymentVersion++; if (bridgeConfig.GetBridgeNodeList().Count > 0 && !string.IsNullOrEmpty(bridgeConfig.BridgeNodes)) { NCBridgeRPCService _bridge = new NCBridgeRPCService(bridgeConfig.BridgeActive); IBridgeServer _server = _bridge.GetBridgeServer(TimeSpan.FromSeconds(30)); _server.RegisterBridge(bridgeConfig, true, false); } //updating target cache config if (bridgeConfig.TargetCacheConfigList != null) { foreach (TargetCacheCofiguration targetCacheConfig in bridgeConfig.TargetCacheConfigList) { try { if (targetCacheConfig != null) { foreach (string server in targetCacheConfig.Servers.Split(',')) { NCacheRPCService NCache = new NCacheRPCService(server);; ICacheServer cacheServer = null; cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); string cacheID = targetCacheConfig.CacheID.ToString(); CacheServerConfig serverConfig = cacheServer.GetCacheConfiguration(cacheID); if (serverConfig.Bridge != null) { serverConfig.Bridge.Servers = bridgeConfig.BridgeNodes; } serverConfig.ConfigVersion++; cacheServer.ConfigureBridgeToCache(serverConfig, userId, paswd, false); } } } catch (Exception ex) { OutputProvider.WriteErrorLine(ex.Message); return; } } } } OutputProvider.WriteLine("Bridge node" + DeleteBridgeNode.ToString() + " removed successfully from Bridge " + BridgeId); } catch (Exception e) { OutputProvider.WriteErrorLine("Bridge not registered on server.\n"); OutputProvider.WriteErrorLine(e.Message); return; } }
private X509Certificate2 GetCertificateFromStore() { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); var certCollection = store.Certificates; var currentCerts = certCollection.Find(X509FindType.FindByThumbprint, EncryptionUtil.GetCertThumbprint(), false); return(currentCerts.Count == 0 ? null : currentCerts[0]); } finally { store.Close(); } }