private void Start() { this.client = new SimpleClient("Unity1", "127.0.0.1", 4000); this.client.Replayer.OnNewActor += Replayer_OnNewActor; this.client.Login(); }
public void Export(PresentationInfo[] presentationInfos) { ExportPresentation exportPresentation = new ExportPresentation( DesignerClient.Instance.ClientConfiguration, DesignerClient.Instance.PresentationWorker, DesignerClient.Instance.StandalonePresentationWorker, this); using (SimpleClient<IDesignerService> client = new SimpleClient<IDesignerService>()) { client.Open(); exportPresentation.Export(presentationInfos, client.Channel); } }
private static void Main() { // configure IoC var dependencyInjectionConfiguration = new DependencyInjectionConfiguration(DependencyInjection.Container); dependencyInjectionConfiguration.Configure(); // some client logic var client = new SimpleClient(DependencyInjection.Container.Resolve<ApplesProvider>()); client.ShowApples(); // wait for key press Console.ReadKey(); }
public void Export() { ExportConfiguration exportConfiguration = new ExportConfiguration( DesignerClient.Instance.ClientConfiguration, DesignerClient.Instance.StandalonePresentationWorker, DesignerClient.Instance.PresentationWorker, SuccessMessage, ErrorMessage, GetFileNameForConfiguration); using (SimpleClient<IDesignerService> client = new SimpleClient<IDesignerService>()) { client.Open(); exportConfiguration.Export(client.Channel); } }
//public IClientConfiguration ClientConfiguration //{ //get { return _configuration; } //} public bool Initialize(IClientConfiguration configuration) { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { return false; } _configuration = configuration; return true; } }
public UserInfo FindSystemUser() { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } return _svc.Channel.FindSystemUser(); } }
static int Main (string [] args) { if (args.Length != 1) return 1; switch (args [0]) { case "client": SimpleClient client = new SimpleClient (); return client.Run (); case "server": SimpleServer server = new SimpleServer (); server.Run (); return 0; default: return 2; } }
async Task ProcessDotNettyMessage(object package) { var message = JsonConvert.DeserializeObject <ServiceMessage>(package as string); message.StampTwo.Visited = true; message.StampTwo.TimeNow = DateTime.UtcNow; await SimpleClient.SendAsync(message, this.Context, "Service3", LogError); // need to do this here in order to avoid a COM error in runtime //var client = new FabricClient(FabricClientRole.User); //var servicePartitionResolver = ServicePartitionResolver.GetDefault(); //var serviceUri = this.Context.CodePackageActivationContext.ApplicationName + "/" + "Service3"; //var partitionList = client.QueryManager.GetPartitionListAsync(new Uri(serviceUri)).GetAwaiter().GetResult(); //var destinationEndpoint = await SimpleClient.GetSocketEndpointAsync(new Uri(serviceUri), this.Context, partitionList); //await SimpleClient.SendAsync(message, destinationEndpoint.Item1, destinationEndpoint.Item2, LogError); }
public static void HandleStateMessage(SimpleClient client, StateMessage message) { var stateMessage = MessageReceiver.BuildStateMessage(message.stateType, message.data); Console.WriteLine($"\t State message received : {message.stateMessage}"); Console.WriteLine($"\t\t State type received : {message.stateType}"); if (stateMessage == null) { return; } switch (message.stateMessage) { case StateMessageEnum.SYS_SET_STATE: PacketManager.ParseStateHandler(client, stateMessage); break; } }
public void RespectsInheritance() { SimpleClient source = new SimpleClient("foo"); IEventRegistry registry = new EventRegistry(); registry.PublishEvents(source); EventSubscriber sub = new EventSubscriber(); Assert.IsFalse(sub.EventRaised, "Event raised"); source.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event raised"); registry.Subscribe(sub, typeof(ISimpleClient)); source.ClientMethodThatTriggersEvent(); Assert.IsTrue(sub.EventRaised, "Event Not Raised"); }
static void Main() { MyServer server = new MyServer(); server.AddService(new MySearchService()); server.Start(); var canalCliente = SimpleClient.Connect("localhost", 12345); MySearchClient cliente = new MySearchClient(canalCliente); SearchRequest req = new SearchRequest(); req.FileName = "*.bat"; var resp = cliente.Search(req); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormTeste()); }
public void AfterClientDisconnectTest() { ConnectedClient connectedClient; Host host = new Host(IPAddress.Any); host.AddAcceptor(9000, (con, conClient) => new CommandHandler(con, conClient)); try { host.Open(); using (SimpleClient client = new SimpleClient()) { client.Connect(); Assert.AreEqual(1, host.ConnectedClientCount); connectedClient = host.GetConnectedClientByID(client.ID); Assert.AreEqual(1, connectedClient.HandlerCount); using (HostEventListener eventWait = new HostEventListener(host)) { client.DisconnectAsync().Wait(); eventWait.SetStrategyUnlock(new UnlockIfRemoveLastHandler()); eventWait.Wait(); Assert.AreEqual(0, connectedClient.HandlerCount); eventWait.Reset(); eventWait.SetStrategyUnlock(new UnlockIfRemoveLastClient()); eventWait.Wait(); Assert.AreEqual(0, host.ConnectedClientCount); } } } finally { host.Close(); } }
public static void HandleTS_CS_ACCOUNT(SimpleClient client, TS_CS_ACCOUNT message) { string login = message.login.Replace("\0", ""); string password = message.password.Replace("\0", ""); AccountRecord record = AccountManager.Instance.GetAccountRecordByLogin(login); if (record == null) { client.Send(new TM_SC_RESULT(0, (ushort)ErrorLoginEnum.MSG_SERVER_NOT_EXIST)); return; } if (record.BanTime.HasValue && record.BanTime.Value > DateTime.Now) { client.Send(new TM_SC_RESULT(0, (ushort)ErrorLoginEnum.MSG_SERVER_DENIED)); return; } if (record.PasswordHash != password) { client.Send(new TM_SC_RESULT(0, (ushort)ErrorLoginEnum.MSG_SERVER_DENIED)); return; } SimpleClient clientAlreadyConnected = SimpleServer.ConnectedClients.FirstOrDefault(x => x.Account != null && x.Account.Username == login); if (clientAlreadyConnected != null) { client.Send(new TM_SC_RESULT(0, (ushort)ErrorLoginEnum.MSG_SERVER_ALREADY_EXIST)); clientAlreadyConnected.Disconnect(); return; } string sessionKey = new AsyncRandom().RandomString(32) + '\0'; client.Account = new Account(record, sessionKey); client.Send(new TM_SC_WE_LOGIN((int)ValidKeyEnum.IS_VALID, sessionKey, (int)client.Account.Role, 1)); AccountManager.Instance.AddTicketAccount(sessionKey, client.Account); }
static void Main(string[] args) { ChatMessage message = new ChatMessage(); message.From = "我是路人甲"; message.To = "我是路人乙"; message.Message = "这些年你过得可好?"; SimpleClient client = new SimpleClient("127.0.0.1", 8081); client.Connect(); client.OnSocketReceive += client_OnSocketReceive; client.Send(LitJson.JsonMapper.ToJson(message)); while (true) { client.Receive(); client.Send(Console.ReadLine()); } }
public static void HandleDeleteCharacterMessage(SimpleClient client, DeleteCharacterMessage message) { if (message.password == "111111") { CharacterManager.Instance.DeleteCharacter(client, message.characterId); } else { SendDeleteCharacterResultMessage(client, ErrorEnum.ERR_PASSWORD, message.characterId, 0); } SendCharactersListMessage(client, DateTime.UtcNow.GetUnixTimeStamp(), 0, (byte)client.Account.Characters.Count, 0, 0, client.Account.Characters.Where(x => !x.DeletedDate.HasValue).ToArray(), client.Account.Characters.Count(x => x.DeletedDate.HasValue), 0, 0, 0); foreach (var character in client.Account.Characters.Where(x => !x.DeletedDate.HasValue)) { SendCharacterSlotMessage(client, character, client.Account.Characters.Count(x => x.DeletedDate.HasValue)); } }
public void InitData(ISqlSugarClient sclient) { sclient.DbMaintenance.CreateDatabase(); //创建数据库 sclient.CodeFirst.InitTables(typeof(zCustomUser)); SimpleClient simpleClient = new SimpleClient(sclient); List <zCustomUser> userlist = new List <zCustomUser>() { new zCustomUser() { Name = "admin", AddTime = DateTime.Now, Gender = 1, pwd = "", state = 1 }, new zCustomUser() { Name = "bob", AddTime = DateTime.Now, Gender = 1, pwd = "", state = 1 } }; simpleClient.InsertRange(userlist); }
public void OpenConnection() { try { ServerConnection = new SimpleClient(); ClientConnection = new SimpleClient(); ServerConnection.Disconnected += ServerDisconnected; ServerConnection.DataReceived += ServerDataReceived; ServerConnection.Error += SocketError; ClientConnection.Disconnected += ClientDisconnected; ClientConnection.DataReceived += ClientDataReceived; ClientConnection.Error += SocketError; ClientConnection.Start(Sock); if (Client.Silent) { string address = Constants.LoginAddresses[Rnd.Next(0, Constants.LoginAddresses.Length)]; short port = (short)Constants.LoginPorts[Rnd.Next(0, Constants.LoginPorts.Length)]; ServerConnection.Start(address, port); } else { TicketEntry msg = TicketsManager.GetTicket(); Client.AccountName = msg.AccountName; Client.Network.Instance = msg.Instance; string address = Dns.GetHostAddresses(msg.ServerMsg.address)[Rnd.Next(0, Dns.GetHostAddresses(msg.ServerMsg.address).Length)].ToString(); short port = (short)msg.ServerMsg.ports[Rnd.Next(0, msg.ServerMsg.ports.Length)]; ServerConnection.Start(address, port); } } catch (Exception ex) { WindowManager.MainWindow.Logger.Error("[Network] " + ex.Message); } }
void OnGUI() { if (!showButton) { return; } if (GUI.Button(new Rect(100, 100, 100, 50), "Start sever")) { Application.targetFrameRate = 20; SimpleServer.Start("myAppId"); showButton = false; } if (GUI.Button(new Rect(100, 200, 100, 50), "Start client")) { Application.targetFrameRate = 60; SimpleClient.Connect("myAppId"); showButton = false; } }
public void StartSync(Socket client, bool game) { this.ClientIpEndPoint = client.RemoteEndPoint as IPEndPoint; this.Client = new SimpleClient(); this.Server = new SimpleClient(); this.Client.DataReceived += new EventHandler <SimpleClient.DataReceivedEventArgs>(this.OnClientDataReceived); this.Client.Disconnected += new EventHandler <SimpleClient.DisconnectedEventArgs>(this.OnClientDisconnected); this.Server.DataReceived += new EventHandler <SimpleClient.DataReceivedEventArgs>(this.OnServerDataReceived); this.Server.Disconnected += new EventHandler <SimpleClient.DisconnectedEventArgs>(this.OnServerDisconnected); this.Client.Start(client); if (!game) { this.Server.Start("63.34.214.78", (short)5555); } else { this.Game = true; this.Send((NetworkMessage) new ProtocolRequired(1912, 1912), NetworkDestinationEnum.Client); this.Send((NetworkMessage) new HelloGameMessage(), NetworkDestinationEnum.Client); } }
public static void ParseHandler(SimpleClient client, NetworkMessage message) { Action <object, SimpleClient, NetworkMessage> methodToInvok; if (message != null) { if (MethodHandlers.TryGetValue((ushort)message.MessageId, out methodToInvok)) { methodToInvok.Invoke(null, client, message); } else { client.logger.Warn(string.Format("Received non handled Packet : id = {0} -> {1}", message.MessageId, message)); } } else { client.logger.Error("Received empty packet !"); client.Disconnect(); } }
public override async Task Execute() { await Authorize(); var listResult = await SimpleClient.GetObservers(ObserverEntity.Users); if (!listResult.Success || listResult.Response == null) { Log.Debug(listResult); return; } foreach (var watched in listResult.Response) { var result = await SimpleClient.DeleteObserver(ObserverEntity.Users, watched.Key); Log.Debug(result); } UpdateAuthorization(); }
public static void HandleBS_CS_START_GAME(SimpleClient client, BS_CS_START_GAME message) { if (client.Character.RoomConnected.IsAllReady()) { Room room = client.Character.RoomConnected; if (room.MapId == 0) { room.MapId = (short)(Enum.GetValues(typeof(MapIdEnum)) as MapIdEnum[]).Shuffle().First(); } room.Clients.Send(new BM_SC_SELECT_MAP()); room.Clients.Send(new BM_SC_MAP_INFO(client.Character.RoomConnected.MapId)); string encryptionKey = new AsyncRandom().RandomString(16); room.Clients.Send(new BM_SC_START_GAME(encryptionKey, room.PlayersConnected.Select(x => x.GetPlayerGameInfoType()))); //Thread.Sleep(6000); client.Send(new BM_SC_PSB_LEADER_NAME(client.Character.RoomConnected.PlayersConnected.FirstOrDefault(x => x.IsLeader).Name)); } }
public override async Task Execute() { await Authorize(); if (string.IsNullOrEmpty(Id)) { return; } Guid g; if (Guid.TryParse(Id, out g)) { var result = await SimpleClient.DeleteApp(g); Log.Debug(result); } else { Log.Debug("Invalid app id specified"); } UpdateAuthorization(); }
public void PublishAllEventsMultipleSubscribersAndUnsubscribe() { IEventRegistry registry = new EventRegistry(); SimpleClient client = new SimpleClient("PublishAllEvents"); registry.PublishEvents(client); EventSubscriber sub = new EventSubscriber(); EventSubscriber sub2 = new EventSubscriber(); registry.Subscribe(sub); registry.Subscribe(sub2); client.ClientMethodThatTriggersEvent(); Assert.IsTrue(sub.EventRaised, "Event Not Raised"); Assert.IsTrue(sub2.EventRaised, "Event Not Raised"); Assert.AreEqual(1, sub.EventCount); Assert.AreEqual(1, sub2.EventCount); registry.Unsubscribe(sub2); client.ClientMethodThatTriggersEvent(); Assert.AreEqual(2, sub.EventCount); Assert.AreEqual(1, sub2.EventCount); }
private static async Task Main(string[] args) { // // Go here and login with your account to create an access key: https://console.aws.amazon.com/iam/home?#/security_credentials // //Uncomment this line if you want to use it against your own bucket using (S3Client client = SimpleClient.Create("MyKeyId", "MyAccessKey", AwsRegion.UsEast1)) { const string bucketName = "simple-s3-test"; const string objectName = "some-object"; //First we create the a bucket named "simple-s3-test". It might already be there, so we ignore if the request was not a success await client.CreateBucketAsync(bucketName).ConfigureAwait(false); //Upload and download an object using the normal API await UploadDownloadWithNormalApi(client, bucketName, objectName).ConfigureAwait(false); //Upload and download an object using the fluent API await UploadDownloadWithFluent(client, bucketName, objectName).ConfigureAwait(false); } }
public override async Task Execute() { await Authorize(); if (string.IsNullOrEmpty(Id)) { return; } Guid g; if (Guid.TryParse(Id, out g)) { var result = await SimpleClient.VehicleHistoryStates(g, Skip, Top, Fields); Log.Debug(result); } else { Log.Debug("Invalid Vehicle id specified"); } UpdateAuthorization(); }
public static void HandleCertifyMessage(SimpleClient client, CertifyMessage message) { GameAccount account; if (!CredentialsManager.Instance.CheckAccountValidity(out account, message.username, message.password)) { SendCertifyResultMessage(client, ErrorEnum.ERR_CERT_BAD_PASSWORD, (ErrorEnum)(((int)ErrorEnum.CERT_CHARGE_CERTIFY_FAILED) << 16)); client.Disconnect(); return; } if (!message.realVersion.GetVersionFromCompacted().IsUpToDate()) { SendCertifyResultMessage(client, ErrorEnum.ERR_CERT_VERSION, ErrorEnum.ERR_VERSION_TOO_LOW); client.Disconnect(); return; } if (SimpleServer.ConnectedClients.Exists(x => x.Account != null && x.Account.Record.Username == message.username)) { SendCertifyResultMessage(client, ErrorEnum.ERR_ACCOUNT_EXIST, ErrorEnum.ERR_ACCOUNT_EXIST); client.Disconnect(); return; } account.IP_Key = message.ip_key.ToString(); account.HDSN = message.hdsn; client.Account = account; client.Account.Characters.ForEach(x => x.Client = client); SendCertifyResultMessage(client); CharacterHandler.SendCharactersListMessage(client, DateTime.UtcNow.GetUnixTimeStamp(), 0, (byte)client.Account.Characters.Count, 0, 0, client.Account.Characters.Where(x => !x.DeletedDate.HasValue).ToArray(), client.Account.Characters.Count(x => x.DeletedDate.HasValue), 0, 0, 0); foreach (var character in client.Account.Characters.Where(x => !x.DeletedDate.HasValue)) { CharacterHandler.SendCharacterSlotMessage(client, character, client.Account.Characters.Count(x => x.DeletedDate.HasValue)); } }
/// <summary> /// 判断是否显示该项 /// </summary> /// <param name="temp"></param> /// <returns></returns> private static bool MaterialTypeBool(MaterialType temp, SimpleClient <MaterialType> db, int?curMaterialTypeID = null) { //跳过本身 if (temp.MaterialTypeID != curMaterialTypeID) { //父类不为空 while (temp.MaterialTypeRoot != null) { //父类等于当前类-返回false if (temp.MaterialTypeRoot == curMaterialTypeID) { return(false); } else { //不等于父类,继续查找父类 temp = db.GetById(temp.MaterialTypeRoot); } } return(true); } return(false); }
/// <summary> /// 更新用户和角色表关系 /// </summary> /// <param name="user"></param> /// <returns></returns> public bool SaveUserAndRole(User user) { var db = new SimpleClient(Db); #region 使用事务 var result = Db.Ado.UseTran(() => { user.LastErrTime = DateTime.Now; user.UpdateTime = DateTime.Now; db.Update(user); var userRole = Db.Queryable <UserRole>().Where(a => a.UserId == user.Id).First(); if (userRole != null) { userRole.RoleId = user.RoleId; userRole.ModifyTime = DateTime.Now; db.Update(userRole); } else { var userRoleEntity = new UserRole { IsDelete = false, UserId = user.Id, RoleId = user.RoleId, CreateTime = DateTime.Now, ModifyTime = DateTime.Now }; db.Insert(userRoleEntity); } }); #endregion return(result.IsSuccess); }
public void CommunicationObjectReceiveAndSendDataTest() { Host host = new Host(IPAddress.Any); host.AddAcceptor(9000, (con, conClient) => new CommandHandler(con, conClient)); host.AddAcceptor(9001, (con, conClient) => new DataTransferHandler(con, conClient)); try { host.Open(); using (SimpleClient client = new SimpleClient()) { client.Connect(); short commandCodeOld = 5; short errorCodeOld = 4; FileData fileDataOld = new FileData("fileName.txt", 1024); var receiveData = client.SendAndReceiveData(commandCodeOld, errorCodeOld, fileDataOld); short commandCodeNew = receiveData.Item1; short errorCodeNew = receiveData.Item2; FileData fileDataNew = receiveData.Item3; Assert.AreEqual(commandCodeOld, commandCodeNew); Assert.AreEqual(errorCodeOld, errorCodeNew); Assert.AreEqual(fileDataOld, fileDataNew); client.DisconnectAsync().Wait(); } } finally { host.Close(); } }
public void Init() { Debug.Log("Init RabbitmqManagementAPI"); SimpleClient simpleClient = this.gameObject.GetComponent <SimpleClient>(); if (simpleClient != null) { this.Connection = SimpleClient.GetConnection(simpleClient.Connection); if (this.Connection != null) { Debug.Log("Connected"); } else { Debug.Log("No Connection"); } } //this.connection = connection; //this.url = "http://" + connection.Username + ":" + connection.Password + "@" + connection.Host + ":" + connection.AmqpPort; //this.url = "http://" + connection.Host + ":" + connection.AmqpPort; //RabbitmqWebRequest request = new RabbitmqWebRequest(url, UnityWebRequest.kHttpVerbGET); }
public static void HandleBS_CS_CHANNEL_LEAVE(SimpleClient client, BS_CS_CHANNEL_LEAVE message) { client.Send(new BM_SC_CHANNEL_LEAVE(1)); client.Send(new ID_BZ_SC_ENTER_LOBBY(0)); }
public void Execute(AnalysisExecutionContext context) { _context = context; if (context.Results.Count <= 0) { context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Canceled, 0, 0, 0)); return; } MechanicalTurkSettings settings = context.CustomField as MechanicalTurkSettings; if (settings == null) { settings = new MechanicalTurkSettings(null, 3, new decimal(0.10), 300, 1800, 75); } string key = context.Key; string secret = context.Secret; MTurkConfig config = new MTurkConfig(_serviceURL, key, secret); SimpleClient client = new SimpleClient(config); List <QualificationRequirement> requirements = new List <QualificationRequirement>(); QualificationRequirement sucRequirement = new QualificationRequirement(); sucRequirement.QualificationTypeId = MTurkSystemQualificationTypes.ApprovalRateQualification; sucRequirement.IntegerValueSpecified = true; sucRequirement.IntegerValue = settings.PercentOfSuccess; sucRequirement.Comparator = Comparator.GreaterThanOrEqualTo; requirements.Add(sucRequirement); if (settings.Locale != null) { QualificationRequirement qualReq = new QualificationRequirement(); qualReq.LocaleValue = new Locale() { Country = settings.Locale }; qualReq.Comparator = Comparator.EqualTo; qualReq.QualificationTypeId = MTurkSystemQualificationTypes.LocaleQualification; requirements.Add(qualReq); } string hitType = string.Empty; try { if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; hitType = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return(hitType = client.RegisterHITType("Sentiment analysis", "Judge the sentiment expressed by the following text.", settings.TimeToApprove, settings.TimeToFinish, settings.Reward, "sentiment nlp", requirements)); }), null, out time) as string; Console.WriteLine("MechanicalTurk: HIT type for sentiment analysis has been created. HIT type ID is: {0} Execution time is: {1}", hitType, time.TotalMilliseconds); } else { hitType = client.RegisterHITType("Sentiment analysis", "Judge the sentiment expressed by the following text.", settings.TimeToApprove, settings.TimeToFinish, settings.Reward, "sentiment, nlp", requirements); } NotificationSpecification notification = new NotificationSpecification(); notification.Transport = NotificationTransport.Email; notification.EventType = new EventType[] { EventType.AssignmentReturned }; notification.Destination = settings.Email; notification.Version = "2006-05-05"; if (settings.Email != null) { client.SetHITTypeNotification(hitType, notification, true); } else { notification.Destination = "*****@*****.**"; client.SetHITTypeNotification(hitType, notification, false); } } catch (Exception ex) { AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, 0, 0); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) { return; } } string questionFile = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "SentimentTemplate.xml"); string template = File.ReadAllText(questionFile); QuestionForm formTemplate = QuestionUtil.DeserializeQuestionForm(template); int processed = 0; int failed = 0; foreach (KeyValuePair <string, ResultSet> document in context.Results) { formTemplate.Question[0].QuestionIdentifier = document.Key; formTemplate.Question[0].QuestionContent.Items[0] = Encoding.UTF8.GetString(Encoding.Default.GetBytes(document.Value.Source)); string question = QuestionUtil.SerializeQuestionForm(formTemplate); HIT hit = new HIT(); hit.Expiration = DateTime.Now.AddDays(1); hit.ExpirationSpecified = true; hit.HITGroupId = "SentimentAnalysis"; hit.HITTypeId = hitType; hit.MaxAssignments = settings.Assignments; hit.MaxAssignmentsSpecified = true; hit.Question = question; HIT serverHit = null; try { processed++; if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; serverHit = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return(client.CreateHIT(hit)); }), null, out time) as HIT; Console.WriteLine("MechanicalTurk: HIT {0} has been sent to Mechanical turk for processing. Execution time is: {1}", serverHit.HITId, time.TotalMilliseconds); } else { serverHit = client.CreateHIT(hit); } document.Value.AddOutput("MechanicalTurk", settings.Assignments, serverHit.HITId); AnalysisExecutionProgressEventArgs e = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Processed, context.Results.Count, processed, failed); context.OnExecutionProgress("MechanicalTurk", e); if (e.Cancel) { break; } } catch (Exception ex) { failed++; document.Value.AddOutput("MechanicalTurk", 0, "failed"); AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, processed, failed); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) { break; } } } context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Success, context.Results.Count, processed, failed)); }
public void NoPublishers() { IEventRegistry registry = new EventRegistry(); SimpleClient client = new SimpleClient("PublishAllEvents"); SimpleSubscriber sub = new SimpleSubscriber(); Assert.IsFalse(sub.EventRaised, "Event raised"); client.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event raised"); registry.Subscribe(sub); client.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event Raised"); }
public void PublishAllEventsSubscribeToNamedEvents() { IEventRegistry registry = new EventRegistry(); SimpleClient client = new SimpleClient("PublishAllEvents"); SimpleClient2 client2 = new SimpleClient2(); registry.PublishEvents(client); registry.PublishEvents(client2); EventSubscriber sub = new EventSubscriber(); EventSubscriber sub2 = new EventSubscriber(); Assert.IsFalse(sub.EventRaised, "Event raised"); Assert.IsFalse(sub2.EventRaised, "Event raised"); client.ClientMethodThatTriggersEvent(); client2.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event raised"); Assert.IsFalse(sub2.EventRaised, "Event raised"); registry.Subscribe(sub, typeof (SimpleClient)); registry.Subscribe(sub2, typeof (SimpleClient2)); client.ClientMethodThatTriggersEvent(); Assert.IsTrue(sub.EventRaised, "Event Not Raised"); Assert.IsFalse(sub2.EventRaised, "Event raised"); client2.ClientMethodThatTriggersEvent(); Assert.IsTrue(sub.EventRaised, "Event Not Raised"); Assert.IsTrue(sub2.EventRaised, "Event Not Raised"); }
static void Main(string[] args) { var options = new Options(); var ids = new[] { "20702362", "8791176", "19426582", "25969427", "19875072", "17413827", "4238394", "19999983", "24926433", "3771061", "3260133", "6969727", "7402881", "3189164", "5659077", "22838624", "7514760", "7293646", "4792995", "6264180", "18046522", "2662465", "4742592", "6246942", "25893775", "24050407", "21433818", "144350", "4413963", "19578541", "6046979", "3213902" }; if (!CommandLine.Parser.Default.ParseArguments(args, options)) return; Provider data = null; SimpleClient client = null; if (string.IsNullOrEmpty(options.HttpUrl)) { data = new Provider(); } else { client = new SimpleClient(options.HttpUrl); } var fSingle = string.IsNullOrEmpty(options.HttpUrl) ? new Func<string, string, string, Task<List<string>>>( async (appid, item, rel) => await data.Get(appid, item, rel)) : new Func<string, string, string, Task<List<string>>>( async (appid, item, rel) => await client.GetAsync(item, rel)); var runner = new TestRunner(options.ThreadCount, Console.Out); runner.SlaTarget = options.Sla; if (options.IstracingEnabled) runner.Log = LogManager.GetLogger("TestRunner"); runner.AddPlan(new TestPlan("warmup", options.IterationsCount, counter => { var res = fSingle(options.ApplicationId, ids[counter % 10], "vv").Result; if (res == null) throw new ArgumentNullException(); }) { IsWarmUp = true }); if (options.DoSingle) { runner.AddPlan("vv single", options.IterationsCount, counter => { var res = fSingle(options.ApplicationId, ids[counter % 10], "vv").Result; if (res == null) throw new ArgumentNullException(); }); } var i = fSingle("ozon", ids[0], "vv").Result; if (i == null) return; runner.Start(); var opts = ReportOptions.None; if (options.ReportTotals) opts = opts | ReportOptions.Totals; if (options.ReportSlowest) opts = opts | ReportOptions.Slowest; runner.Report(opts); }
public Label[] GetLabelStorage() { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } return _svc.Channel.GetLabelStorage(); } }
private LabelError LabelHandler(string proc, Label labelInfo) { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } Type channel = typeof(ILabelService); MethodInfo method = channel.GetMethod(proc, new Type[] { typeof(Label) }); object[] parameters = {labelInfo}; try { return (LabelError)method.Invoke(_svc.Channel, parameters); } catch (TargetInvocationException tiEx) { if (tiEx.InnerException is FaultException<LabelUsedInPresentationException>) { throw new LabelUsedInPresentationException(((FaultException<LabelUsedInPresentationException>)tiEx.InnerException).Detail.Message); } throw tiEx; } } }
public ISystemParameters LoadSystemParameters() { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } return _svc.Channel.LoadSystemParameters(); } }
public void SaveSystemParameters(ISystemParameters systemParameters) { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } try { _svc.Channel.SaveSystemParameters(systemParameters); } catch (FaultException Ex) { throw new SystemParametersSaveException(Ex.Message); } } }
private void bt_connect_Click(object sender, EventArgs e) { var newclient = new SimpleClient(); client = new ClientHost(newclient); client.name = tb_name.Text; client.AddFrame(new IdentificationFrame()); newclient.Start(tb_IP.Text, 400); Thread.Sleep(500); if (!newclient.Runing) MessageBox.Show("Connection Failed !"); }
private UserError UserHandler(string proc, UserInfo userInfo) { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } Type channel = typeof(IUserService); MethodInfo method = channel.GetMethod(proc, new Type[] { typeof(UserInfo)}); object[] parameters ={userInfo}; return (UserError)method.Invoke(_svc.Channel, parameters); } }
public void NoValidEventHandlersOrEventsToSubscribeto() { IEventRegistry registry = new EventRegistry(); SimpleClient client = new SimpleClient("PublishAllEvents"); NoEventSubscriber sub = new NoEventSubscriber(); registry.PublishEvents(client); Assert.IsFalse(sub.EventRaised, "Event raised"); client.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event raised"); registry.Subscribe(sub); client.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event Raised"); }
public void ToComplexEntity_WhenSimpleEntity_ExpectMapSuccess() { // Arrange var mockClaimsMapper = new Mock<IMapper<SimpleClaim, Claim>>(); var mockPropertyMapper = new Mock<IPropertyGetSettersTyped<Client>>(); mockClaimsMapper.Setup(r => r.ToComplexEntity(It.IsAny<IEnumerable<SimpleClaim>>())).Returns(new List<Claim> { new Claim("DEFAULT", "DEFAULT") }); mockPropertyMapper.Setup(r => r.GetSetters(It.IsAny<Type>())).Returns(new Dictionary<string, TypedSetter<Client>>()); var clientMappers = new ClientMappers<Client>(mockClaimsMapper.Object, mockPropertyMapper.Object); var secret = new Secret("Value", "Description", new DateTimeOffset(new DateTime(2016, 1, 1))) { Type = "Type" }; var simpleClient = new SimpleClient { Claims = new List<SimpleClaim>(), Enabled = true, AccessTokenType = AccessTokenType.Jwt, AbsoluteRefreshTokenLifetime = 1, AccessTokenLifetime = 1, AllowAccessToAllCustomGrantTypes = true, AllowAccessToAllScopes = true, AllowRememberConsent = true, EnableLocalLogin = true, AllowAccessTokensViaBrowser = true, LogoutSessionRequired = true, Flow = Flows.AuthorizationCode, AlwaysSendClientClaims = true, PrefixClientClaims = true, ClientSecrets = new List<Secret> { secret }, RefreshTokenExpiration = TokenExpiration.Absolute, RequireSignOutPrompt = true, RefreshTokenUsage = TokenUsage.OneTimeOnly, IdentityTokenLifetime = 1, SlidingRefreshTokenLifetime = 1, RequireConsent = true, AllowClientCredentialsOnly = true, IncludeJwtId = true, AuthorizationCodeLifetime = 1, UpdateAccessTokenClaimsOnRefresh = true, ClientName = "ClientName", LogoutUri = "LogoutUri", RedirectUris = new List<string>(), ClientUri = "ClientUri", AllowedCustomGrantTypes = new List<string>(), AllowedScopes = new List<string>(), ClientId = "ClientId", PostLogoutRedirectUris = new List<string>(), AllowedCorsOrigins = new List<string>(), IdentityProviderRestrictions = new List<string>(), LogoUri = "LogoUri" }; // Act var stopwatch = Stopwatch.StartNew(); var complexEntity = clientMappers.ToComplexEntity(simpleClient); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); Assert.That(complexEntity, Is.Not.Null); }
public void PublishAllEventsAndSubscribeToSome() { IEventRegistry registry = new EventRegistry(); SimpleClient client = new SimpleClient("PublishAllEventsAndSubscribeToSome"); registry.PublishEvents(client); EventSubscriber sub = new EventSubscriber(); OtherEventSubscriber sub2 = new OtherEventSubscriber(); Assert.IsFalse(sub.EventRaised, "Event raised"); Assert.IsFalse(sub2.EventRaised, "Event raised"); client.ClientMethodThatTriggersEvent(); Assert.IsFalse(sub.EventRaised, "Event raised"); client.ClientMethodThatTriggersEvent3(); Assert.IsFalse(sub2.EventRaised, "Event raised"); registry.Subscribe(sub); registry.Subscribe(sub2); client.ClientMethodThatTriggersEvent(); client.ClientMethodThatTriggersEvent3(); Assert.IsTrue(sub.EventRaised, "Event Not Raised"); Assert.IsTrue(sub2.EventRaised, "Event Not Raised"); }
private void CreateSimpleUser() { if (this.SimpleClient == null) { this.SimpleClient = new SimpleUser(this); } }
private static async Task RunSimpleTest() { var client = new SimpleClient(); await client.Run(); }
public void TestFixtureSetup() { var database = RedisHelpers.ConnectionMultiplexer.GetDatabase(); var claim1 = new SimpleClaim { Type = "Type1", Value = "Value1" }; var claim2 = new SimpleClaim { Type = "Type2", Value = "Value2" }; var client = new SimpleClient { Claims = new List<SimpleClaim> { claim1, claim2 }, DataBag = new Dictionary<string, object> { { "AppId", 12 } } }; var token = new SimpleToken { Claims = new List<SimpleClaim> { claim1, claim2 }, Client = client, Type = "Type", CreationTime = new DateTimeOffset(new DateTime(2016, 1, 1)), Version = 1, Issuer = "Issuer", Lifetime = 120, Audience = "Audience" }; var settings = new JsonSettingsFactory(new CustomMappersConfiguration { ClientMapper = CustomMapperFactory.CreateClientMapper<CustomClient>() }).Create(); var serialized = JsonConvert.SerializeObject(token, settings); database.StringSet("DEFAULT_THS_Existing", serialized); database.StringSet("DEFAULT_THS_Delete", serialized); }
public ErrorEnum CreateCharacter(SimpleClient client, CreateCharacterMessage message) { if (!m_nameCheckerRegex.IsMatch(message.name)) { return(ErrorEnum.ERR_NOCREATE); } if (IsCharacterNameExist(message.name)) { return(ErrorEnum.ERR_PLAYER_EXIST); } BreedRecord breed = BreedManager.Instance.GetBreedByJobId(message.job); if (breed == null) { return(ErrorEnum.ERR_NOCREATE); } CharacterRecord record = new CharacterRecord() { AccountId = client.Account.Id, Name = message.name, HD_MD5 = message.hd_md5, SceneId = breed.StartMap, Sex = message.sex == 1, X = breed.StartX, Y = breed.StartY, Z = breed.StartZ, Level = 1, Experience = 60, Job = breed.Job, Money = (uint)breed.StartMoney, HP = breed.StartHP, DamageTaken = 0, Strenght = breed.StartStrenght, Stamina = breed.StartStamina, Dexterity = breed.StartDexterity, Intelligence = breed.StartIntelligence, SPI = breed.StartSPI, HairMesh = message.hair_mesh, HairColor = (uint)message.hair_color, HeadMesh = message.head_mesh, City_Code = message.city_code, Constellation = message.constellation, Country = message.country, SN_Card = message.sn_card, Card_Type = message.card_type, HD_SN = message.hd_sn, Bin_Account = message.bin_account, BlockTime = DateTime.MinValue, DeletedDate = null }; var closets = message.closets.Select(x => new ClosetItemRecord() { ClosetItemId = x.id, Equipped = true, OwnerId = record.Id }); try { Database.Insert(record); foreach (var closet in closets) { Database.Insert(closet); } } catch { return(ErrorEnum.ERR_NOCREATE); } client.Character = new Character(record); client.Character.Client = client; client.Account.LoadRecord(); return(ErrorEnum.ERR_SUCCESS); }
public static void HandleBS_CS_ENTER_CHANNEL(SimpleClient client, BS_CS_ENTER_CHANNEL message) { client.Send(new BM_SC_ENTER_CHANNEL(1)); }
public void Request(AnalysisExecutionContext context) { _context = context; if (context.Results.Count <= 0) { context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Canceled, 0, 0, 0)); return; } if (!context.Results.Values.First().GetServices().Contains("MechanicalTurk")) { context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Canceled, 0, 0, 0)); return; } MechanicalTurkSettings settings = context.CustomField as MechanicalTurkSettings; if (settings == null) { settings = new MechanicalTurkSettings(null, 3, new decimal(0.10), 300, 1800, 75); } string key = context.Key; string secret = context.Secret; MTurkConfig config = new MTurkConfig(_serviceURL, key, secret); SimpleClient client = new SimpleClient(config); int failed = 0; int processed = 0; try { foreach (KeyValuePair <string, ResultSet> document in context.Results) { string id = document.Value.GetPolarity("MechanicalTurk"); double count = document.Value.GetScore("MechanicalTurk"); count = (double.IsNaN(count)) ? 0 : count; if (id == "negative" || id == "neutral" || id == "positive" || id == "failed" || id == "undefined") { continue; } IList <Assignment> assignments = null; if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; assignments = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return(client.GetAssignmentsForHIT(id, 1, true)); }), null, out time) as IList <Assignment>; Console.WriteLine("MechanicalTurk: Answers for {0} HIT have been received. Execution time is: {1}", id, time.TotalMilliseconds); } else { assignments = client.GetAssignmentsForHIT(id, 1, true); } if (assignments.Count < count) { processed++; continue; } double confidence = 0; IList <string> answers = DeserializeAnswers(assignments); string polarity = MergeSentimentPolarity(answers, out confidence); processed++; document.Value.AddOutput("MechanicalTurk", double.NaN, polarity, confidence); document.Value.AddReferencePolarity(polarity, "MechanicalTurk"); AnalysisExecutionProgressEventArgs e = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Processed, context.Results.Count, processed, failed); context.OnExecutionProgress("MechanicalTurk", e); if (e.Cancel) { break; } } } catch (Exception ex) { failed++; AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, processed, failed); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) { return; } } context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Success, context.Results.Count, processed, failed)); }
public PresentationInfoExt[] LoadPresentationWithOneSlide() { using (_svc = new SimpleClient<IAdministrationService>()) { try { _svc.Open(); } catch (Exception /*ex*/) { NoConnectionException error = new NoConnectionException(); throw error; } return _svc.Channel.LoadPresentationWithOneSlide(); } }