static SqrlClientFacts() { var mock = new Mock<IIdentityStorageProvider>(); mock.Setup(x => x.Load(Name)).Returns(Data); Identity.StorageProvider = mock.Object; Identity = Identity.Open(Name, Password); }
public bool Equals(Identity id) { var tmcId = id as TmcClientIdentity; return tmcId != null && this.AppKey == tmcId.AppKey && this.GroupName == tmcId.GroupName; }
private Identity GetIdentiy() { var principal = ClaimsPrincipal.Current; Identity i = new Identity(); if (principal != null && principal.Identity != null) { i.IdentityName = principal.Identity.Name; i.IsAuthenticated = principal.Identity.IsAuthenticated; i.AuthenticationType = principal.Identity.AuthenticationType; } else { i.IsAuthenticated = false; } var claims = new List<ViewClaim>( from c in principal.Claims select new ViewClaim { Type = c.Type, Value = c.Value }); i.Claims = claims; return i; }
public void EqualityBetweenIdentityAndGuid() { var identity = new Identity(new Guid(IdentityTest.Guid1)); var guid = new Guid(IdentityTest.Guid1); Assert.AreEqual(identity, guid); }
public void CastToGuid() { var identity = new Identity(new Guid(IdentityTest.Guid1)); Guid guid = identity; Assert.AreEqual(identity, guid); }
public override void SetUp() { base.SetUp(); ctx = GetContext(); var principalResolver = scope.Resolve<IPrincipalResolver>(); var currentPrincipal = principalResolver.GetCurrent(); Assert.That(currentPrincipal, Is.Not.Null, "No current identity found - try syncidentities or setup the current identity correctly"); identity1 = ctx.Find<Identity>(currentPrincipal.ID); identity2 = ctx.GetQuery<Identity>().Where(i => i.ID != identity1.ID).First(); parent = ctx.Create<SecurityTestParent>(); parent.Name = "MyParent"; child1 = ctx.Create<SecurityTestChild>(); child1.Name = "Child1"; child1.Identity = identity1; child1.Parent = parent; child2 = ctx.Create<SecurityTestChild>(); child2.Name = "Child2"; child2.Identity = identity2; child2.Parent = parent; ctx.SubmitChanges(); }
public void DeleteData() { var ctx = scope.Resolve<IZetboxServerContext>(); ctx.GetQuery<Task>().ForEach(obj => ctx.Delete(obj)); ctx.SubmitChanges(); ctx = scope.Resolve<IZetboxServerContext>(); ctx.GetQuery<Projekt>().ForEach(obj => { obj.Mitarbeiter.Clear(); ctx.Delete(obj); }); ctx.SubmitChanges(); ctx = scope.Resolve<IZetboxServerContext>(); ctx.GetQuery<Mitarbeiter>().ForEach(obj => ctx.Delete(obj)); ctx.GetQuery<Kunde>().ForEach(obj => ctx.Delete(obj)); ctx.SubmitChanges(); ctx = scope.Resolve<IZetboxServerContext>(); if (identity1 != null) { var id = ctx.Find<Identity>(identity1.ID); id.Groups.Clear(); ctx.Delete(id); } if (identity2 != null) { var id = ctx.Find<Identity>(identity2.ID); id.Groups.Clear(); ctx.Delete(id); } if (identity3_low != null) { var id = ctx.Find<Identity>(identity3_low.ID); id.Groups.Clear(); ctx.Delete(id); } identity1 = null; identity2= null; identity3_low = null; ctx.SubmitChanges(); }
public Rule GetSetting(Identity id) { var settings = from r in SettingsDataStore.Items<Setting>() where r.I == id select r; return settings.First<Setting>(); }
public Feed Execute(Identity topicId) { Feed workingFeed; lock (lck) { workingFeed = feeds.Find(Query.EQ("TopicId", topicId.ToBson())) .SetSortOrder(SortBy.Descending("Updated")) .SetLimit(1).FirstOrDefault(); if (workingFeed == null || workingFeed.Entries.Count >= 10) { var newFeed = new Feed { TopicId = topicId, }; if(workingFeed != null) { newFeed.PreviousFeed = workingFeed.Id; feeds.Insert(newFeed); workingFeed.NextFeed = newFeed.Id; feeds.Save(workingFeed); }else { feeds.Insert(newFeed); } workingFeed = newFeed; } } return workingFeed; }
public FileInfo DownloadImage(string imageId, string outputPath, Identity identity) { RequestManager requestManager = new RequestManager(identity); var uri = string.Format("/v2/images/{0}/file", imageId); FileInfo result = requestManager.Download(imageId, outputPath,"glance"); return result; }
public IEnumerable<Topic> GetTopics(Identity groupId, int? skip = null, int? limit = null) { var cursor = topicsCollection.Find(QueryGetByGroup(groupId)); if (skip.HasValue) cursor.SetSkip(skip.Value); if (limit.HasValue) cursor.SetLimit(limit.Value); return cursor; }
public GangModel(Identity identity) { Gang = identity.Gang; Id = identity.Id; Valid = true; Identified = identity.Registered; }
public static void SetPasswordUI(Identity obj) { _vmf.CreateDialog(obj.Context, Strings.SetPasswordDlgTitle) .AddPassword("pwd", Strings.Password) .AddPassword("repeat", Strings.RepeatPassword) .Show(values => { var pwd = (string)values["pwd"]; var repeat = (string)values["repeat"]; if (string.IsNullOrEmpty(pwd)) { _vmf.ShowMessage(Strings.PasswordEmpty, Strings.SetPasswordDlgTitle); return; } if(pwd != repeat) { _vmf.ShowMessage(Strings.PasswordDoesNotMatch, Strings.SetPasswordDlgTitle); return; } obj.SetPassword(pwd); }); }
public IMongoQuery CreateQueryDocument(Identity topicId) { return Query.And( Query.NE("Callback", BsonNull.Value), Query.EQ("TargetKind", (int)TargetKind.Topic), Query.EQ("TargetId", topicId.ToBson())); }
public Instance CreateInstance(string instanceName, string imageId, string keypairName, string flavorId, Identity identity) { RequestManager requestManager = new RequestManager(identity); var uri = string.Format("/servers"); var bodyObject = new InstanceRequestBodyWrapper() { server = new InstanceRequestBody() { name = instanceName, imageRef = imageId, key_name = keypairName, flavorRef = flavorId, } }; System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string body = oSerializer.Serialize(bodyObject); JObject response = requestManager.Post(uri, body, "nova"); if (response != null) { var tempinstance = response["server"]; var instance = new Instance() { Id = tempinstance["id"].ToString(), }; return instance; } return null; }
public void TestToString() { Identity<uint> three = new Identity<uint>(typeof(Person), 3); Assert.AreEqual("[CSF.Patterns.DDD.Mocks.Entities.Person: 3]", three.ToString(), "Correct string representation"); }
public TestTransport(TestTransportFactory testTransportFactory, Identity identity, RoutingTable routingTable, PeerTable peerTable, InboundMessageDispatcher inboundMessageDispatcher) { this.testTransportFactory = testTransportFactory; this.identity = identity; this.routingTable = routingTable; this.peerTable = peerTable; this.inboundMessageDispatcher = inboundMessageDispatcher; }
public new Sage.Common.Syndication.FeedEntry GetFeedEntry(string id) { PostalAddressFeedEntry result; Account account = new Account(); Identity identity = new Identity(account.EntityName, id); AccountDocument accountDocument = (AccountDocument)_entity.GetDocument(identity, _emptyToken, _context.Config); if ((accountDocument.LogState == LogState.Deleted) || (accountDocument.addresses.documents.Count == 0)) { PostalAddressFeedEntry deletedPayload = new PostalAddressFeedEntry(); deletedPayload.UUID = GetUuid(id); deletedPayload.IsDeleted = true; return deletedPayload; } Document document = accountDocument.addresses.documents[0]; result = (PostalAddressFeedEntry)GetTransformedPayload(document); string taUuid = GetTradingAccountUuid(accountDocument.Id); #warning no reference for trading accounts exists in the contract return result; }
public Element(IElementSet set, int nElement) { Identity = new Identity(set.GetElementId(nElement)); int nV = set.GetVertexCount(nElement); int nF = set.GetFaceCount(nElement); X = new double[nV]; Y = new double[nV]; if (set.HasZ) Z = new double[nV]; if (set.HasM) M = new double[nV]; for (int n = 0; n < nV; ++n) { X[n] = set.GetVertexXCoordinate(nElement, n); Y[n] = set.GetVertexYCoordinate(nElement, n); if (set.HasZ) Z[n] = set.GetVertexZCoordinate(nElement, n); if (set.HasM) M[n] = set.GetVertexMCoordinate(nElement, n); } if (nF > 0) { Faces = new int[nF][]; for (int n = 0; n < nF; ++n) Faces[n] = set.GetFaceVertexIndices(nElement, n); } }
public FocusComposite(Identity id, string name, ICollection<ActivityList.Item> activities, ICollection<TaskList.Item> tasks, ICollection<NoteList.Item> notes) { Focus = id; Name = name; Activities = activities; Tasks = tasks; Notes = notes; }
public ActionResult Edit(string id) { var identity = new Identity(id); var entity = entityById.Get<Topic>(identity); if(entity == null) return new HttpStatusCodeResult(404); var model = new EditTopicModel(entity, groupsSortedByName.Execute()); return View(model); }
public HttpResponseMessage Update(Identity id, Facade.GroupPut group) { return ProcessPut(() => { var instance = group.ToModel(); updateGroupCommand.Execute(instance); }); }
// throws VisitFailure public virtual void testIdentity() { Identity id = new Identity(); Logger expected = new Logger(id, n0); IVisitable nodeReturned = logVisitor(id).visit(n0); Assertion.AssertEquals(expected, logger); Assertion.AssertEquals(n0, nodeReturned); }
public IMongoQuery QueryDuplicatedName(Identity? groupId, string topicName, Identity? excludeId = null) { var query = excludeId.HasValue ? Query.And(Query.EQ("Name", BsonString.Create(topicName)), Query.NE("_id", excludeId.Value.ToBson())) : Query.EQ("Name", BsonString.Create(topicName)); return Query.And(query, Query.EQ("GroupId", groupId.ToBson())); }
internal IdentityPropertyRules(Identity id) { SetGenderTargettingBitInfoType(id.Usr); SetAgeRangeTargetting(id.Usr); SetIsPromoterTargettingBitInfoType(id.Usr); SetDemographics(id.Demographics); }
public static AuthenticationResult SuccessWithSasToken(Identity identity, string token) { return new AuthenticationResult { Properties = AuthenticationProperties.SuccessWithSasToken(token), Identity = identity }; }
// Use this for initialization void Awake() { this.identity = this.gameObject.GetComponent<Identity> (); this.range = DataManager.Instance.unitDatas [identity.unitType].stats [Stat.Range]; this.atkDmg = DataManager.Instance.unitDatas [identity.unitType].stats [Stat.Attack]; um = gameObject.GetComponent<UnitMovement> (); animator = this.gameObject.GetComponent<Animator>(); }
public static AuthenticationResult SuccessWithDeviceKey(Identity identity, string keyValue) { return new AuthenticationResult { Identity = identity, Properties = AuthenticationProperties.SuccessWithDeviceKey(keyValue) }; }
public static AuthenticationResult SuccessWithDefaultCredentials(Identity identity) { return new AuthenticationResult { Identity = identity, Properties = AuthenticationProperties.SuccessWithDefaultCredentials() }; }
public EndpointProxy GetEndpoint(Identity target) { if (target.Equals(this.Identity)) throw new LinkException(Text.E_ID_DUPLICATE); foreach (EndpointProxy p in this._connected) if (p.Identity != null && p.Identity.Equals(target)) return p; return null; }
public VerifyTimeSoapClient(Identity identity, X509Certificate2 serverCert) : base(identity, serverCert) { base.Url = global::IntegraAfirmaNet.Properties.Settings.Default.VerifyTimeStampBinding; }
private void WriteContentsTo200408(XmlDictionaryWriter writer) { // Address writer.WriteStartElement(XD.AddressingDictionary.Address, XD.Addressing200408Dictionary.Namespace); if (IsAnonymous) { writer.WriteString(XD.Addressing200408Dictionary.Anonymous); } else if (IsNone) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.Format(SR.SFxNone2004)); } else { writer.WriteString(Uri.AbsoluteUri); } writer.WriteEndElement(); // ReferenceProperties if (_headers != null && _headers.HasReferenceProperties) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceProperties, XD.Addressing200408Dictionary.Namespace); _headers.WriteReferencePropertyContentsTo(writer); writer.WriteEndElement(); } // ReferenceParameters if (_headers != null && _headers.HasNonReferenceProperties) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing200408Dictionary.Namespace); _headers.WriteNonReferencePropertyContentsTo(writer); writer.WriteEndElement(); } // PSP (PortType, ServiceName, Policy) XmlDictionaryReader reader = null; if (_pspSection >= 0) { reader = GetReaderAtSection(Buffer, _pspSection); Copy(writer, reader); } // Metadata reader = null; if (_metadataSection >= 0) { reader = GetReaderAtSection(Buffer, _metadataSection); Copy(writer, reader); } // EndpointIdentity if (Identity != null) { Identity.WriteTo(writer); } // Extensions if (_extensionSection >= 0) { reader = GetReaderAtSection(Buffer, _extensionSection); while (reader.IsStartElement()) { if (reader.NamespaceURI == AddressingVersion.WSAddressingAugust2004.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, SR.Format(SR.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } writer.WriteNode(reader, true); } } }
/// <summary> /// 计算玩家积分 /// </summary> /// <param name="self"></param> /// <param name="gamer"></param> /// <param name="winnerIdentity"></param> /// <returns></returns> public static long GetGamerScore(this GameControllerComponent self, Gamer gamer, Identity winnerIdentity) { HandCardsComponent handCards = gamer.GetComponent <HandCardsComponent>(); //积分计算公式:全场底分 * 全场倍率 * 身份倍率 long integration = self.BasePointPerMatch * self.Multiples * (int)handCards.AccessIdentity; //当玩家不是胜者,结算积分为负 if (handCards.AccessIdentity != winnerIdentity) { integration = -integration; } return(integration); }
public static Test.ThrowerPrx allTests(global::Test.TestHelper helper) { Communicator communicator = helper.communicator(); var output = helper.getWriter(); { output.Write("testing object adapter registration exceptions... "); ObjectAdapter first; try { first = communicator.createObjectAdapter("TestAdapter0"); } catch (InitializationException) { // Expected } communicator.SetProperty("TestAdapter0.Endpoints", "tcp -h *"); first = communicator.createObjectAdapter("TestAdapter0"); try { communicator.createObjectAdapter("TestAdapter0"); test(false); } catch (ArgumentException) { // Expected. } try { ObjectAdapter second = communicator.createObjectAdapterWithEndpoints("TestAdapter0", "ssl -h foo -p 12011"); test(false); // // Quell mono error that variable second isn't used. // second.Deactivate(); } catch (ArgumentException) { // Expected } first.Deactivate(); output.WriteLine("ok"); } { output.Write("testing servant registration exceptions... "); communicator.SetProperty("TestAdapter1.Endpoints", "tcp -h *"); ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter1"); var obj = new EmptyI(); adapter.Add(obj, "x"); try { adapter.Add(obj, "x"); test(false); } catch (ArgumentException) { } try { adapter.Add(obj, ""); test(false); } catch (FormatException) { } adapter.Remove("x"); try { adapter.Remove("x"); test(false); } catch (NotRegisteredException) { } adapter.Deactivate(); output.WriteLine("ok"); } { output.Write("testing servant locator registration exceptions... "); communicator.SetProperty("TestAdapter2.Endpoints", "tcp -h *"); ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter2"); ServantLocator loc = new ServantLocatorI(); adapter.AddServantLocator(loc, "x"); try { adapter.AddServantLocator(loc, "x"); test(false); } catch (ArgumentException) { } adapter.Deactivate(); output.WriteLine("ok"); } output.Write("testing stringToProxy... "); output.Flush(); string @ref = "thrower:" + helper.getTestEndpoint(0); var @base = IObjectPrx.Parse(@ref, communicator); test(@base != null); output.WriteLine("ok"); output.Write("testing checked cast... "); output.Flush(); var thrower = Test.ThrowerPrx.CheckedCast(@base); test(thrower != null); test(thrower.Equals(@base)); output.WriteLine("ok"); output.Write("catching exact types... "); output.Flush(); try { thrower.throwAasA(1); test(false); } catch (Test.A ex) { test(ex.aMem == 1); } catch (Exception ex) { Console.WriteLine(ex); test(false); } try { thrower.throwAorDasAorD(1); test(false); } catch (Test.A ex) { test(ex.aMem == 1); } catch (Exception) { test(false); } try { thrower.throwAorDasAorD(-1); test(false); } catch (Test.D ex) { test(ex.dMem == -1); } catch (Exception) { test(false); } try { thrower.throwBasB(1, 2); test(false); } catch (Test.B ex) { test(ex.aMem == 1); test(ex.bMem == 2); } catch (Exception) { test(false); } try { thrower.throwCasC(1, 2, 3); test(false); } catch (Test.C ex) { test(ex.aMem == 1); test(ex.bMem == 2); test(ex.cMem == 3); } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("catching base types... "); output.Flush(); try { thrower.throwBasB(1, 2); test(false); } catch (Test.A ex) { test(ex.aMem == 1); } catch (Exception) { test(false); } try { thrower.throwCasC(1, 2, 3); test(false); } catch (Test.B ex) { test(ex.aMem == 1); test(ex.bMem == 2); } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("catching derived types... "); output.Flush(); try { thrower.throwBasA(1, 2); test(false); } catch (Test.B ex) { test(ex.aMem == 1); test(ex.bMem == 2); } catch (Exception) { test(false); } try { thrower.throwCasA(1, 2, 3); test(false); } catch (Test.C ex) { test(ex.aMem == 1); test(ex.bMem == 2); test(ex.cMem == 3); } catch (Exception) { test(false); } try { thrower.throwCasB(1, 2, 3); test(false); } catch (Test.C ex) { test(ex.aMem == 1); test(ex.bMem == 2); test(ex.cMem == 3); } catch (Exception) { test(false); } output.WriteLine("ok"); if (thrower.supportsUndeclaredExceptions()) { output.Write("catching unknown user exception... "); output.Flush(); try { thrower.throwUndeclaredA(1); test(false); } catch (UnknownUserException) { } catch (Exception) { test(false); } try { thrower.throwUndeclaredB(1, 2); test(false); } catch (UnknownUserException) { } catch (Exception) { test(false); } try { thrower.throwUndeclaredC(1, 2, 3); test(false); } catch (UnknownUserException) { } catch (Exception) { test(false); } output.WriteLine("ok"); } if (thrower.GetConnection() != null) { output.Write("testing memory limit marshal exception..."); output.Flush(); try { thrower.throwMemoryLimitException(null); test(false); } catch (MemoryLimitException) { } catch (Exception) { test(false); } try { thrower.throwMemoryLimitException(new byte[20 * 1024]); // 20KB test(false); } catch (ConnectionLostException) { } catch (UnknownLocalException) { // Expected with JS bidir server } catch (Exception) { test(false); } try { var thrower2 = ThrowerPrx.Parse("thrower:" + helper.getTestEndpoint(1), communicator); try { thrower2.throwMemoryLimitException(new byte[2 * 1024 * 1024]); // 2MB(no limits) } catch (MemoryLimitException) { } var thrower3 = Test.ThrowerPrx.Parse("thrower:" + helper.getTestEndpoint(2), communicator); try { thrower3.throwMemoryLimitException(new byte[1024]); // 1KB limit test(false); } catch (ConnectionLostException) { } } catch (ConnectionRefusedException) { // Expected with JS bidir server } output.WriteLine("ok"); } output.Write("catching object not exist exception... "); output.Flush(); { Identity id = Identity.Parse("does not exist"); try { var thrower2 = ThrowerPrx.UncheckedCast(thrower.Clone(id)); thrower2.IcePing(); test(false); } catch (ObjectNotExistException ex) { test(ex.id.Equals(id)); } catch (Exception) { test(false); } } output.WriteLine("ok"); output.Write("catching facet not exist exception... "); output.Flush(); try { var thrower2 = ThrowerPrx.UncheckedCast(thrower.Clone(facet: "no such facet")); try { thrower2.IcePing(); test(false); } catch (FacetNotExistException ex) { test(ex.facet.Equals("no such facet")); } } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("catching operation not exist exception... "); output.Flush(); try { var thrower2 = Test.WrongOperationPrx.UncheckedCast(thrower); thrower2.noSuchOperation(); test(false); } catch (OperationNotExistException ex) { test(ex.operation.Equals("noSuchOperation")); } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("catching unknown local exception... "); output.Flush(); try { thrower.throwLocalException(); test(false); } catch (UnknownLocalException) { } catch (Exception) { test(false); } try { thrower.throwLocalExceptionIdempotent(); test(false); } catch (UnknownLocalException) { } catch (OperationNotExistException) { } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("catching unknown non-Ice exception... "); output.Flush(); try { thrower.throwNonIceException(); test(false); } catch (UnknownException) { } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("testing asynchronous exceptions... "); output.Flush(); try { thrower.throwAfterResponse(); } catch (Exception) { test(false); } try { thrower.throwAfterException(); test(false); } catch (Test.A) { } catch (Exception) { test(false); } output.WriteLine("ok"); output.Write("catching exact types with AMI mapping... "); output.Flush(); { try { thrower.throwAasAAsync(1).Wait(); } catch (AggregateException exc) { test(exc.InnerException is Test.A); var ex = exc.InnerException as Test.A; test(ex.aMem == 1); } } { try { thrower.throwAorDasAorDAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.A ex) { test(ex.aMem == 1); } catch (Test.D ex) { test(ex.dMem == -1); } catch (Exception) { test(false); } } } { try { thrower.throwAorDasAorDAsync(-1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.A ex) { test(ex.aMem == 1); } catch (Test.D ex) { test(ex.dMem == -1); } catch (Exception) { test(false); } } } { try { thrower.throwBasBAsync(1, 2).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.B ex) { test(ex.aMem == 1); test(ex.bMem == 2); } catch (Exception) { test(false); } } } { try { thrower.throwCasCAsync(1, 2, 3).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.C ex) { test(ex.aMem == 1); test(ex.bMem == 2); test(ex.cMem == 3); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching derived types with new AMI mapping... "); output.Flush(); { try { thrower.throwBasAAsync(1, 2).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.B ex) { test(ex.aMem == 1); test(ex.bMem == 2); } catch (Exception) { test(false); } } } { try { thrower.throwCasAAsync(1, 2, 3).Wait(); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.C ex) { test(ex.aMem == 1); test(ex.bMem == 2); test(ex.cMem == 3); } catch (Exception) { test(false); } } } { try { thrower.throwCasBAsync(1, 2, 3).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (Test.C ex) { test(ex.aMem == 1); test(ex.bMem == 2); test(ex.cMem == 3); } catch (Exception) { test(false); } } } output.WriteLine("ok"); if (thrower.supportsUndeclaredExceptions()) { output.Write("catching unknown user exception with new AMI mapping... "); output.Flush(); { try { thrower.throwUndeclaredAAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownUserException) { } catch (Exception) { test(false); } } } { try { thrower.throwUndeclaredBAsync(1, 2).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownUserException) { } catch (Exception) { test(false); } } } { try { thrower.throwUndeclaredCAsync(1, 2, 3).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownUserException) { } catch (Exception) { test(false); } } } output.WriteLine("ok"); } output.Write("catching object not exist exception with new AMI mapping... "); output.Flush(); { Identity id = Identity.Parse("does not exist"); var thrower2 = Test.ThrowerPrx.UncheckedCast(thrower.Clone(id)); try { thrower2.throwAasAAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (ObjectNotExistException ex) { test(ex.id.Equals(id)); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching facet not exist exception with new AMI mapping... "); output.Flush(); { var thrower2 = ThrowerPrx.UncheckedCast(thrower.Clone(facet: "no such facet")); try { thrower2.throwAasAAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (FacetNotExistException ex) { test(ex.facet.Equals("no such facet")); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching operation not exist exception with new AMI mapping... "); output.Flush(); { try { var thrower4 = Test.WrongOperationPrx.UncheckedCast(thrower); thrower4.noSuchOperationAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (OperationNotExistException ex) { test(ex.operation.Equals("noSuchOperation")); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching unknown local exception with new AMI mapping... "); output.Flush(); { try { thrower.throwLocalExceptionAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownLocalException) { } catch (OperationNotExistException) { } catch (Exception) { test(false); } } } { try { thrower.throwLocalExceptionIdempotentAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownLocalException) { } catch (OperationNotExistException) { } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching unknown non-Ice exception with new AMI mapping... "); output.Flush(); { try { thrower.throwNonIceExceptionAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownException) { } catch (Exception) { test(false); } } } output.WriteLine("ok"); if (thrower.supportsUndeclaredExceptions()) { output.Write("catching unknown user exception with new AMI mapping... "); output.Flush(); { try { thrower.throwUndeclaredAAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownUserException) { } catch (Exception) { test(false); } } } { try { thrower.throwUndeclaredBAsync(1, 2).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownUserException) { } catch (Exception) { test(false); } } } { try { thrower.throwUndeclaredCAsync(1, 2, 3).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownUserException) { } catch (Exception) { test(false); } } } output.WriteLine("ok"); } output.Write("catching object not exist exception with new AMI mapping... "); output.Flush(); { Identity id = Identity.Parse("does not exist"); var thrower2 = Test.ThrowerPrx.UncheckedCast(thrower.Clone(id)); try { thrower2.throwAasAAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (ObjectNotExistException ex) { test(ex.id.Equals(id)); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching facet not exist exception with new AMI mapping... "); output.Flush(); { var thrower2 = Test.ThrowerPrx.UncheckedCast(thrower.Clone(facet: "no such facet")); try { thrower2.throwAasAAsync(1).Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (FacetNotExistException ex) { test(ex.facet.Equals("no such facet")); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching operation not exist exception with new AMI mapping... "); output.Flush(); { var thrower4 = Test.WrongOperationPrx.UncheckedCast(thrower); try { thrower4.noSuchOperationAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (OperationNotExistException ex) { test(ex.operation.Equals("noSuchOperation")); } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching unknown local exception with new AMI mapping... "); output.Flush(); { try { thrower.throwLocalExceptionAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownLocalException) { } catch (OperationNotExistException) { } catch (Exception) { test(false); } } } { try { thrower.throwLocalExceptionIdempotentAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownLocalException) { } catch (OperationNotExistException) { } catch (Exception) { test(false); } } } output.WriteLine("ok"); output.Write("catching unknown non-Ice exception with new AMI mapping... "); output.Flush(); { try { thrower.throwNonIceExceptionAsync().Wait(); test(false); } catch (AggregateException exc) { try { throw exc.InnerException; } catch (UnknownException) { } catch (Exception) { test(false); } } } output.WriteLine("ok"); return(thrower); }
public Agent(int _id) { int MAX_FOLLOWERS = 100; id = _id; identity = new Identity(); //probabilities //gender M-F float[] probaGender = new float[] { 0.491f, 0.509f }; //race caucasian, negroid, asian, middleeastern, none float[] probaRace = new float[] { 0.673f, 0.122f, 0.047f, 0.163f, 0.031f }; //nationnality decorrelated from race (need more nationnalities to correlate) //AMERICAN, BRITISH, SPANISH, CHINESE, IRISH, INDIAN, MALAYSIAN, FRENCH, KAZAKHSTANI float[] probaNationality = new float[] { 0.90f, 0.056f, 0.0063f, 0.0061f, 0.0051f, 0.0043f, 0.0042f, 0.000969f, 0.000936f, 0.000513f, 0.00546f, 0.000309f, 0.000309f }; //age from race (found only for while, black & asian) //by 5 year step + random adjustement between 0-5 years float[][] probaAge = new float[][] { new float[] { 0.057f, 0.059f, 0.061f, 0.065f, 0.065f, 0.064f, 0.061f, 0.063f, 0.067f, 0.076f, 0.077f, 0.070f, 0.061f, 0.046f, 0.035f, 0.028f, 0.022f, 0.022f }, new float[] { 0.075f, 0.074f, 0.078f, 0.089f, 0.080f, 0.072f, 0.068f, 0.067f, 0.069f, 0.073f, 0.069f, 0.057f, 0.043f, 0.030f, 0.022f, 0.016f, 0.011f, 0.010f }, new float[] { 0.061f, 0.063f, 0.060f, 0.065f, 0.075f, 0.084f, 0.085f, 0.088f, 0.079f, 0.073f, 0.067f, 0.058f, 0.047f, 0.032f, 0.024f, 0.017f, 0.012f, 0.009f }, new float[] { 0.118f, 0.105f, 0.097f, 0.096f, 0.090f, 0.088f, 0.081f, 0.072f, 0.063f, 0.054f, 0.043f, 0.031f, 0.022f, 0.014f, 0.010f, 0.007f, 0.004f, 0.003f } }; //religion from race float[][] probaReligion = new float[][] { new float[] { 0.700f, 0.006f, 0.003f, 0.030f, 0.020f, 0.001f, 0.240f }, new float[] { 0.790f, 0.020f, 0.003f, 0.003f, 0.010f, 0.004f, 0.170f }, new float[] { 0.340f, 0.070f, 0.160f, 0.010f, 0.040f, 0.070f, 0.310f }, new float[] { 0.770f, 0.003f, 0.003f, 0.010f, 0.004f, 0.010f, 0.200f }, new float[] { 0.785f, 0.006f, 0.004f, 0.017f, 0.012f, 0.007f, 0.161f } }; //social class float[] probaClass = new float[] { 0.48f, 0.46f, 0.06f }; identity.g = (eGender)randomProba(probaGender); identity.ra = (eRace)randomProba(probaRace); identity.n = (eNationality)randomProba(probaNationality); switch (identity.ra) { case eRace.WHITE: identity.age = 5 * randomProba(probaAge[0]) + UnityEngine.Random.Range(0, 5); identity.r = (eReligion)randomProba(probaReligion[0]); break; case eRace.BLACK: identity.age = 5 * randomProba(probaAge[1]) + UnityEngine.Random.Range(0, 5); identity.r = (eReligion)randomProba(probaReligion[1]); break; case eRace.ASIAN: identity.age = 5 * randomProba(probaAge[2]) + UnityEngine.Random.Range(0, 5); identity.r = (eReligion)randomProba(probaReligion[2]); break; case eRace.HISPANIC: identity.age = 5 * randomProba(probaAge[3]) + UnityEngine.Random.Range(0, 5); identity.r = (eReligion)randomProba(probaReligion[3]); break; default: identity.age = UnityEngine.Random.Range(0, 90); identity.r = (eReligion)randomProba(probaReligion[4]); break; } // if (age < 15)//make twitter users above 13 years olds (doesn't follow statistics but reflects that tweeter users are most ofter between 15 and 30) // age += 15; identity.c = (eClass)randomProba(probaClass); //big 5 mean for white young man (needed) float[] meanB5 = new float[] { 0, 0, 0, 0, 0 }; //big 5 correlation: Ext Agr Con Neu Ope CROSS Age female White Black Asian Hispanic Other float[][] correlationsB5 = new float[][] { new float[] { -0.04f, 0.12f, 0.32f, -0.1f, 0.01f }, new float[] { 0.18f, 0.17f, -0.12f, 0.14f, -0.2f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { -0.06f, -0.01f, -0.24f, -0.08f, -0.03f }, new float[] { -0.12f, 0.05f, -0.1f, 0.02f, -0.05f }, new float[] { 0f, -0.06f, -0.23f, 0, -0.06f } }; personality = new float[5]; //formula : personality[i] = mean[i]+SUM_j(correlation)+random value between -0.5 and 0.5) for (int i = 0; i < 5; i++) { personality[i] = meanB5[i] + UnityEngine.Random.value - 0.5f; personality[i] += correlationsB5[0][i] * (float)(identity.age - 50) / 100f; if (identity.g == eGender.FEMALE) { personality[i] += correlationsB5[1][i]; } switch (identity.ra) { case eRace.WHITE: personality[i] += correlationsB5[2][i]; break; case eRace.BLACK: personality[i] += correlationsB5[3][i]; break; case eRace.ASIAN: personality[i] += correlationsB5[4][i]; break; case eRace.HISPANIC: personality[i] += correlationsB5[5][i]; break; default: personality[i] += correlationsB5[2][i]; break; } personality[i] = clamp(personality[i]); } //preferences float[] correlation_religiosity = new float[] { 0.1f, 0.2f, 0.17f, 0.0f, -0.06f }; float[] correlation_religious_fundamentalism = new float[] { 0.09f, 0.13f, 0.09f, -0.12f, -0.14f }; float[] correlation_politics = new float[] { -0.081f, 0.025f, -0.42f, -0.29f, 0.84f }; //formula : pref_[own] = random value between -0.5 and 0.5 + SUM big5*correlation // pref_[other] = -pref_[own] float religiosity = UnityEngine.Random.value - 0.5f; //- to 1 float religious_fundamentalism = 0f; //- to 1 float politics = UnityEngine.Random.value - 0.5f; //-1 = very cons, 1 = very lib float ethnicity = 2 * UnityEngine.Random.value - 1f; float gender = 2f * UnityEngine.Random.value - 1f; float classPref = 2f * UnityEngine.Random.value - 1f; float nationalityPref = 2f * UnityEngine.Random.value - 1f; for (int i = 0; i < 5; ++i) { religiosity += personality[i] * 3f * correlation_religiosity[i]; religious_fundamentalism += personality[i] * 10f * correlation_religious_fundamentalism[i]; politics += personality[i] * correlation_politics[i]; } religiosity = clamp(religiosity); religious_fundamentalism = clamp(religious_fundamentalism); politics = clamp(politics); identity.pref_religion = new float[probaReligion[0].Length]; for (int i = 0; i < identity.pref_religion.Length; i++) { float atheist = 1.0f; if (identity.r == eReligion.ATHEIST) { atheist = -1.0f; } if ((eReligion)i == identity.r) { identity.pref_religion[i] = atheist * religiosity; } else { identity.pref_religion[i] = -atheist *religious_fundamentalism *Math.Abs(atheist *religiosity); } } identity.pref_ethnicity = new float[probaRace.Length]; for (int i = 0; i < identity.pref_ethnicity.Length; i++) { if ((eRace)i == identity.ra) { identity.pref_ethnicity[i] = ethnicity; } else { identity.pref_ethnicity[i] = -ethnicity; } } identity.pref_gender = new float[2]; for (int i = 0; i < 2; i++) { if ((eGender)i == identity.g) { identity.pref_gender[i] = gender; } else { identity.pref_gender[i] = -gender; } } identity.pref_class = new float[3]; for (int i = 0; i < 3; i++) { if ((eClass)i == identity.c) { identity.pref_class[i] = classPref; } else { identity.pref_class[i] = -classPref; } } identity.pref_nationality = new float[13]; for (int i = 0; i < identity.pref_nationality.Length; i++) { if ((eNationality)i == identity.n) { identity.pref_nationality[i] = nationalityPref; } else { identity.pref_nationality[i] = -nationalityPref; } } identity.pref_political = new float[4]; if (politics < 0)//conservative/facist { identity.p = (ePolitics)(2 * randomProba(new float[] { 0.75f, 0.25f })); } else //liberal/communist { identity.p = (ePolitics)(2 * randomProba(new float[] { 0.75f, 0.25f })) + 1; } for (int i = 0; i < identity.pref_political.Length; i++) { if ((ePolitics)i == identity.p) { identity.pref_political[i] = Math.Abs(politics); } else { identity.pref_political[i] = -Math.Abs(politics); } } followingList = new List <int>(); int numFollowers = UnityEngine.Random.Range(1, MAX_FOLLOWERS); for (int i = 0; i < numFollowers; ++i) { int f = UnityEngine.Random.Range(0, Generator.NUMBER_OF_AGENTS); while (f == id || followingList.Contains(f)) { f = UnityEngine.Random.Range(0, Generator.NUMBER_OF_AGENTS); } followingList.Add(f); } tweetMade = new List <int>(); readTweets = new List <int>(); /* Debug.Log(identity.age); * Debug.Log(identity.g); * Debug.Log(identity.ra); * Debug.Log(identity.r); * Debug.Log(identity.p); * Debug.Log("Ext: " + personality[0]); * Debug.Log("Agr: " + personality[1]); * Debug.Log("Con: " + personality[2]); * Debug.Log("Neu: " + personality[3]); * Debug.Log("Ope: " + personality[4]); * Debug.Log("relig :" + religiosity); * Debug.Log("funda :" + religious_fundamentalism); * Debug.Log("poli :" +politics); * Debug.Log("initial followers :" + numFollowers); * Debug.Log(" ");*/ }
public void DeleteWorkingTimeRange(Identity <WorkingTimeRange> identity) { _WorkingTimeRangeRepository.Remove(identity); }
public Task DeleteContext(Identity identity) { _data.Remove(GetKey(identity), out _); return(Task.CompletedTask); }
public void Run(String[] args) { if (!ParseCommandLine(args)) { return; } SessionOptions.ServerAddress[] servers = new SessionOptions.ServerAddress[d_hosts.Count]; for (int i = 0; i < d_hosts.Count; ++i) { servers[i] = new SessionOptions.ServerAddress(d_hosts[i], d_port); } SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerAddresses = servers; sessionOptions.AuthenticationOptions = d_authOptions; sessionOptions.AutoRestartOnDisconnection = true; sessionOptions.NumStartAttempts = servers.Length; System.Console.Write("Connecting to"); foreach (SessionOptions.ServerAddress server in sessionOptions.ServerAddresses) { System.Console.Write(" " + server); } System.Console.WriteLine(); ProviderSession session = new ProviderSession(sessionOptions, ProcessEvent); if (!session.Start()) { System.Console.Error.WriteLine("Failed to start session"); return; } Identity identity = null; if (d_authOptions != null) { if (!Authorize(out identity, session)) { return; } } if (d_groupId != null) { // NOTE: will perform explicit service registration here, instead of letting // createTopics do it, as the latter approach doesn't allow for custom // ServiceRegistrationOptions ServiceRegistrationOptions serviceRegistrationOptions = new ServiceRegistrationOptions(); serviceRegistrationOptions.GroupId = d_groupId; serviceRegistrationOptions.ServicePriority = d_priority; if (!session.RegisterService(d_service, identity, serviceRegistrationOptions)) { System.Console.Write("Failed to register " + d_service); return; } } TopicList topicList = new TopicList(); for (int i = 0; i < d_topics.Count; i++) { topicList.Add( d_service + "/" + d_topics[i], new CorrelationID(new MyStream(d_topics[i]))); } session.CreateTopics( topicList, ResolveMode.AUTO_REGISTER_SERVICES, identity); // createTopics() is synchronous, topicList will be updated // with the results of topic creation (resolution will happen // under the covers) List <MyStream> myStreams = new List <MyStream>(); for (int i = 0; i < topicList.Size; ++i) { MyStream stream = (MyStream)topicList.CorrelationIdAt(i).Object; if (topicList.StatusAt(i) == TopicList.TopicStatus.CREATED) { Message msg = topicList.MessageAt(i); stream.setTopic(session.GetTopic(msg)); myStreams.Add(stream); System.Console.WriteLine("Topic created: " + topicList.TopicStringAt(i)); } else { System.Console.WriteLine("Stream '" + stream.getId() + "': topic not resolved, status = " + topicList.StatusAt(i)); } } Service service = session.GetService(d_service); // Now we will start publishing Name eventName = Name.GetName("MarketDataEvents"); Name high = Name.GetName("HIGH"); Name low = Name.GetName("LOW"); long tickCount = 1; for (int eventCount = 0; eventCount < d_maxEvents; ++eventCount) { Event eventObj = service.CreatePublishEvent(); EventFormatter eventFormatter = new EventFormatter(eventObj); for (int index = 0; index < myStreams.Count; index++) { Topic topic = myStreams[index].getTopic(); if (!topic.IsActive()) { continue; } eventFormatter.AppendMessage(eventName, topic); if (1 == tickCount) { eventFormatter.SetElement("OPEN", 1.0); } else if (2 == tickCount) { eventFormatter.SetElement("BEST_BID", 3.0); } eventFormatter.SetElement(high, tickCount * 1.0); eventFormatter.SetElement(low, tickCount * 0.5); ++tickCount; } foreach (Message msg in eventObj) { System.Console.WriteLine(msg); } session.Publish(eventObj); Thread.Sleep(2 * 1000); } session.Stop(); }
/// <summary> /// 游戏结束 /// </summary> /// <param name="self"></param> public static async void GameOver(this GameControllerComponent self, Dictionary <long, long> gamersScore, Identity winnerIdentity) { Room room = self.GetParent <Room>(); Gamer[] gamers = room.GetAll(); //清理所有卡牌 self.BackToDeck(); room.GetComponent <DeskCardsCacheComponent>().Clear(); //同步匹配服务器结束游戏 room.State = RoomState.Ready; MapHelper.SendMessage(new MP2MH_SyncRoomState() { RoomID = room.Id, State = room.State }); Dictionary <long, long> gamersMoney = new Dictionary <long, long>(); foreach (Gamer gamer in gamers) { //结算玩家余额 long gamerMoney = await self.StatisticalIntegral(gamer, gamersScore[gamer.UserID]); gamersMoney[gamer.UserID] = gamerMoney; } //广播游戏结束消息 room.Broadcast(new M2C_Gameover() { Winner = (int)winnerIdentity, BasePointPerMatch = self.BasePointPerMatch, Multiples = self.Multiples, GamersScore = gamersScore }); //清理玩家 foreach (var _gamer in gamers) { //踢出离线玩家 if (_gamer.isOffline) { ActorProxy actorProxy = Game.Scene.GetComponent <ActorProxyComponent>().Get(_gamer.Id); await actorProxy.Call(new G2M_PlayerExitRoom()); } //踢出余额不足玩家 else if (gamersMoney[_gamer.UserID] < self.MinThreshold) { ActorProxy actorProxy = _gamer.GetComponent <UnitGateComponent>().GetActorProxy(); actorProxy.Send(new M2C_GamerMoneyLess() { UserID = _gamer.UserID }); } } }
public ValueTask <IObjectPrx?> FindObjectByIdAsync(Identity id, Current current) => _lookup.FindObjectAsync(id);
public int CountEscrows(Transaction tx, Identity identity) { var amount = identity == Identity.Bob ? Denomination : Denomination + Fee; return(tx.Outputs.Where(o => o.Value == amount).Count()); }
/// <summary> /// </summary> /// <param name="ownerInstance"> /// </param> public PlayerInventoryPage(Identity ownerInstance) : base((int)IdentityType.Inventory, 30, 0x40, ownerInstance) { }
/// <summary> /// Gets the System.Type of the current instance. /// </summary> /// <returns>The exact runtime type of the current instance.</returns> public override int GetHashCode() { return(Identity.GetHashCode()); }
public JwtIdentity(Identity identity) : base(identity.Client.Name) { this.Identity = identity; }
private void CreateStatisticsForPeriod(Period period, TrackRecord[] allRecords, Identity user) { Trace.WriteLine(string.Format("Creating stats for period from {0} to {1} for user {2}", period.StartDate, period.EndDate, user.Login)); //I tu ważna sprawa, jak nasze daty od do! var fromDate = period.StartDate < _startDateTime ? _startDateTime : period.StartDate; var toDate = period.EndDate > _endDateTime ? _endDateTime : period.EndDate; Trace.WriteLine(string.Format("Real range is {0}-{1}", fromDate.ToShortDateString(), toDate.ToShortDateString())); var totalTime = StatsCalculator.CalculateStats(allRecords, fromDate, toDate); var statsToUpdate = _wasteStatisticService.GetStats(user.Id, period.Id); if (statsToUpdate == null) { Trace.WriteLine(string.Format("Creating new stats")); _wasteStatisticService.CreateStatistics((int)totalTime, allRecords.Count( record => record.StartDate >= period.StartDate && record.StartDate < period.EndDate), user.Id, period.Id); } else { Trace.WriteLine(string.Format("Updating stats")); statsToUpdate.TimeSumInSecond = (int)totalTime; statsToUpdate.EntryCount = allRecords.Count( record => record.StartDate >= period.StartDate && record.StartDate < period.EndDate); _wasteStatisticService.UpdateStats(statsToUpdate); } }
Run(global::Test.TestHelper helper) { var output = helper.getWriter(); Communicator communicator = helper.communicator(); ObjectAdapter oa = communicator.CreateObjectAdapterWithEndpoints("MyOA", "tcp -h localhost"); oa.Activate(); output.Write("testing single category... "); output.Flush(); var servant = new MyObject(); oa.AddDefaultForCategory("foo", servant); try { oa.AddDefaultForCategory("foo", new MyObject()); test(false); // duplicate registration not allowed } catch (System.ArgumentException) { // Expected } IObject?r = oa.Find("foo"); test(r == null); r = oa.Find("foo/someId"); test(r == servant); r = oa.Find("bar/someId"); test(r == null); Identity identity = new Identity("", "foo"); string[] names = new string[] { "foo", "bar", "x", "y", "abcdefg" }; IMyObjectPrx?prx = null; for (int idx = 0; idx < 5; ++idx) { identity = new Identity(names[idx], identity.Category); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); prx.IcePing(); test(prx.GetName() == names[idx]); } identity = new Identity("ObjectNotExist", identity.Category); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); try { prx.IcePing(); test(false); } catch (ObjectNotExistException) { // Expected } try { prx.GetName(); test(false); } catch (ObjectNotExistException) { // Expected } identity = new Identity(identity.Name, "bar"); for (int idx = 0; idx < 5; idx++) { identity = new Identity(names[idx], identity.Category); prx = oa.CreateProxy(identity, Test.IMyObjectPrx.Factory); try { prx.IcePing(); test(false); } catch (Ice.ObjectNotExistException) { // Expected } try { prx.GetName(); test(false); } catch (Ice.ObjectNotExistException) { // Expected } } IObject?removed = oa.RemoveDefaultForCategory("foo"); test(removed == servant); removed = oa.RemoveDefaultForCategory("foo"); test(removed == null); identity = new Identity(identity.Name, "foo"); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); try { prx.IcePing(); } catch (ObjectNotExistException) { // Expected } output.WriteLine("ok"); output.Write("testing default servant... "); output.Flush(); var defaultServant = new MyObject(); oa.AddDefault(defaultServant); try { oa.AddDefault(servant); test(false); } catch (System.ArgumentException) { // Expected } oa.AddDefaultForCategory("", servant); // associated with empty category r = oa.Find("bar"); test(r == servant); r = oa.Find("x/y"); test(r == defaultServant); for (int idx = 0; idx < 5; ++idx) { identity = new Identity(names[idx], ""); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); prx.IcePing(); test(prx.GetName() == names[idx]); } removed = oa.RemoveDefault(); test(removed == defaultServant); removed = oa.RemoveDefault(); test(removed == null); output.WriteLine("ok"); }
// public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder) // { // FunctionsHostBuilderContext context = builder.GetContext(); // Envs.Load(); // // KeyVault // var secretClient = new SecretClient(new Uri(Env.GetString("AZURE_KEYVAULT_ENDPOINT")), Identity.GetCredentialChain()); // var storageConnectionString = secretClient.GetSecret(Env.GetString("AZURE_STORAGE_CONNECTION_STRING_SECRET_NAME")); // var signalRConnectionString = secretClient.GetSecret(Env.GetString("AZURE_SIGNALR_CONNECTION_STRING_SECRET_NAME")); // //Environment.SetEnvironmentVariable("Values:AzureWebJobsStorage", storageConnectionString.Value.Value); // builder.ConfigurationBuilder // .AddInMemoryCollection(new Dictionary<string, string> { // { "ClientSyncQueueConnectionString", storageConnectionString.Value.Value }, // { "AzureSignalRConnectionString", signalRConnectionString.Value.Value } // }) // .AddEnvironmentVariables(); // } public override void Configure(IFunctionsHostBuilder builder) { //FunctionsHostBuilderContext context = builder.GetContext(); Envs.Load(); // KeyVault var secretClient = new SecretClient(new Uri(Env.GetString("AZURE_KEYVAULT_ENDPOINT")), Identity.GetCredentialChain()); var storageConnectionString = secretClient.GetSecret(Env.GetString("AZURE_STORAGE_CONNECTION_STRING_SECRET_NAME")); var signalRConnectionString = secretClient.GetSecret(Env.GetString("AZURE_SIGNALR_CONNECTION_STRING_SECRET_NAME")); //Environment.SetEnvironmentVariable("Values:AzureWebJobsStorage", storageConnectionString.Value.Value); var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary <string, string> { { "ClientSyncQueueConnectionString", storageConnectionString.Value.Value }, { "AzureSignalRConnectionString", signalRConnectionString.Value.Value } }) .AddEnvironmentVariables().Build(); builder.Services.AddSingleton <IConfiguration>(config); }
private bool Authorize(out Identity identity, ProviderSession session) { identity = null; EventQueue tokenEventQueue = new EventQueue(); session.GenerateToken(new CorrelationID(tokenEventQueue), tokenEventQueue); String token = null; const int timeoutMilliSeonds = 10000; Event eventObj = tokenEventQueue.NextEvent(timeoutMilliSeonds); if (eventObj.Type == Event.EventType.TOKEN_STATUS) { foreach (Message msg in eventObj) { System.Console.WriteLine(msg.ToString()); if (msg.MessageType == TOKEN_SUCCESS) { token = msg.GetElementAsString("token"); } } } if (token == null) { System.Console.WriteLine("Failed to get token"); return(false); } if (session.OpenService("//blp/apiauth")) { Service authService = session.GetService("//blp/apiauth"); Request authRequest = authService.CreateAuthorizationRequest(); authRequest.Set("token", token); EventQueue authEventQueue = new EventQueue(); identity = session.CreateIdentity(); session.SendAuthorizationRequest(authRequest, identity, authEventQueue, new CorrelationID(identity)); while (true) { eventObj = authEventQueue.NextEvent(); if (eventObj.Type == Event.EventType.RESPONSE || eventObj.Type == Event.EventType.PARTIAL_RESPONSE || eventObj.Type == Event.EventType.REQUEST_STATUS) { foreach (Message msg in eventObj) { System.Console.WriteLine(msg.ToString()); if (msg.MessageType == AUTHORIZATION_SUCCESS) { return(true); } else { System.Console.WriteLine("Not authorized: " + msg); return(false); } } } } } return(false); }
public IEnumerable <Subscription> Execute(Identity topicId) { return(subscriptionsCollection.Find(CreateQueryDocument(topicId))); }
public Principal(string name) { Identity = new Identity(name); }
private void RolloutCrudTests( string serviceTopologyId, string artifactSourceId, string serviceUnitId, string failureServiceUnitId, string stepId, string location, AzureDeploymentManagerClient deploymentManagerClient, DeploymentManagerClientHelper clientHelper) { var rolloutName = clientHelper.ResourceGroupName + "Rollout"; var failureRolloutName = clientHelper.ResourceGroupName + "FailureRollout"; var userAssignedIdentity = this.SetManagedIdentity(clientHelper); var identity = new Identity() { Type = "userAssigned", IdentityIds = new List <string>() { userAssignedIdentity } }; var stepGroup = new StepGroup( name: "First_Region", deploymentTargetId: serviceUnitId) { PreDeploymentSteps = new List <PrePostStep> () { new PrePostStep(stepId) } }; var stepGroupForFailureRollout = new StepGroup( name: "FirstRegion", deploymentTargetId: failureServiceUnitId); var rolloutRequest = new RolloutRequest( location: location, buildVersion: "1.0.0.0", identity: identity, targetServiceTopologyId: serviceTopologyId, artifactSourceId: artifactSourceId, stepGroups: new List <StepGroup>() { stepGroup }); var createRolloutResponse = deploymentManagerClient.Rollouts.CreateOrUpdate( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: rolloutName, rolloutRequest: rolloutRequest); this.ValidateRollout(rolloutRequest, createRolloutResponse); // Kick off a rollout that would fail to test restart operation. var failureRolloutRequest = new RolloutRequest( location: location, buildVersion: "1.0.0.0", identity: identity, targetServiceTopologyId: serviceTopologyId, artifactSourceId: artifactSourceId, stepGroups: new List <StepGroup>() { stepGroupForFailureRollout }); var failureRolloutResponse = deploymentManagerClient.Rollouts.CreateOrUpdate( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: failureRolloutName, rolloutRequest: failureRolloutRequest); this.ValidateRollout(failureRolloutRequest, failureRolloutResponse); // Test Get rollout. var rollout = deploymentManagerClient.Rollouts.Get( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: rolloutName); Assert.NotNull(rollout); Assert.Equal("Running", rollout.Status); Assert.NotNull(rollout.OperationInfo); Assert.Equal(0, rollout.OperationInfo.RetryAttempt); // Test cancel rollout. rollout = deploymentManagerClient.Rollouts.Cancel( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: rolloutName); Assert.NotNull(rollout); Assert.Equal("Canceling", rollout.Status); this.WaitForRolloutTermination( rolloutName, deploymentManagerClient, clientHelper); var rollouts = deploymentManagerClient.Rollouts.List( resourceGroupName: clientHelper.ResourceGroupName); Assert.Equal(2, rollouts.Count); Assert.NotEmpty(rollouts.Where(r => r.Name.Equals(failureRolloutName, StringComparison.InvariantCultureIgnoreCase))); // Test delete rollout. deploymentManagerClient.Rollouts.Delete( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: rolloutName); var cloudException = Assert.Throws <CloudException>(() => deploymentManagerClient.Rollouts.Get( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: rolloutName)); Assert.Equal(HttpStatusCode.NotFound, cloudException.Response.StatusCode); // Check status of rollout expected to fail and attempt restart operation. var failureRollout = this.WaitForRolloutTermination( failureRolloutName, deploymentManagerClient, clientHelper); Assert.NotNull(failureRollout); Assert.Equal("Failed", failureRollout.Status); // Test Restart rollout. failureRollout = deploymentManagerClient.Rollouts.Restart( resourceGroupName: clientHelper.ResourceGroupName, rolloutName: failureRolloutName); Assert.NotNull(failureRollout); Assert.Equal("Running", failureRollout.Status); Assert.Equal(1, failureRollout.TotalRetryAttempts); Assert.Equal(false.ToString(), failureRollout.OperationInfo.SkipSucceededOnRetry.ToString()); }
/// <summary> /// 更新身份 /// </summary> /// <param name="self"></param> /// <param name="id"></param> /// <param name="identity"></param> public static void UpdateInIdentity(this GameControllerComponent self, Gamer gamer, Identity identity) { gamer.GetComponent <HandCardsComponent>().AccessIdentity = identity; }
public async Task <Identity> Create(Identity identity) { await _context.Identity.InsertOneAsync(identity); return(identity); }
allTests(global::Test.TestHelper helper) { var output = helper.getWriter(); Communicator communicator = helper.communicator(); ObjectAdapter oa = communicator.CreateObjectAdapterWithEndpoints("MyOA", "tcp -h localhost"); oa.Activate(); var servantI = new MyObject(); Disp servantD = (servantI as IObject).Dispatch; // // Register default servant with category "foo" // oa.AddDefaultServant(servantD, "foo"); // // Start test // output.Write("testing single category... "); output.Flush(); Disp r = oa.FindDefaultServant("foo"); test(r == servantD); r = oa.FindDefaultServant("bar"); test(r == null); Identity identity = new Identity("", "foo"); string[] names = new string[] { "foo", "bar", "x", "y", "abcdefg" }; IMyObjectPrx prx = null; for (int idx = 0; idx < 5; ++idx) { identity = new Identity(names[idx], identity.Category); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); prx.IcePing(); test(prx.getName() == names[idx]); } identity = new Identity("ObjectNotExist", identity.Category); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); try { prx.IcePing(); test(false); } catch (ObjectNotExistException) { // Expected } try { prx.getName(); test(false); } catch (ObjectNotExistException) { // Expected } identity = new Identity("FacetNotExist", identity.Category); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); try { prx.IcePing(); test(false); } catch (FacetNotExistException) { // Expected } try { prx.getName(); test(false); } catch (FacetNotExistException) { // Expected } identity = new Identity(identity.Name, "bar"); for (int idx = 0; idx < 5; idx++) { identity = new Identity(names[idx], identity.Category); prx = oa.CreateProxy(identity, Test.IMyObjectPrx.Factory); try { prx.IcePing(); test(false); } catch (Ice.ObjectNotExistException) { // Expected } try { prx.getName(); test(false); } catch (Ice.ObjectNotExistException) { // Expected } } oa.RemoveDefaultServant("foo"); identity = new Identity(identity.Name, "foo"); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); try { prx.IcePing(); } catch (ObjectNotExistException) { // Expected } output.WriteLine("ok"); output.Write("testing default category... "); output.Flush(); oa.AddDefaultServant(servantD, ""); r = oa.FindDefaultServant("bar"); test(r == null); r = oa.FindDefaultServant(""); test(r == servantD); for (int idx = 0; idx < 5; ++idx) { identity = new Identity(names[idx], identity.Category); prx = oa.CreateProxy(identity, IMyObjectPrx.Factory); prx.IcePing(); test(prx.getName() == names[idx]); } output.WriteLine("ok"); }
public static T AddEntity <T>(Identity identity, string locationId) where T : Entity, new() { return(AddEntity <T>(identity, Location.Get(locationId))); }
public static T AddEntity <T>(Identity identity) where T : Entity, new() { return(AddEntity <T>(identity: identity, location: null)); }
} // Invoke // This is called for all remoted calls on a TP except Ctors // The method called may be [....], Async or OneWay(special case of Async) // In the Async case we come here for both BeginInvoke & EndInvoke internal virtual IMessage InternalInvoke( IMethodCallMessage reqMcmMsg, bool useDispatchMessage, int callType) { Message reqMsg = reqMcmMsg as Message; if ((reqMsg == null) && (callType != Message.Sync)) { // Only the synchronous call type is supported for messages that // aren't of type Message. throw new RemotingException( Environment.GetResourceString("Remoting_Proxy_InvalidCallType")); } IMessage retMsg = null; Thread currentThread = Thread.CurrentThread; // pick up call context from the thread LogicalCallContext cctx = currentThread.GetMutableExecutionContext().LogicalCallContext; Identity idObj = IdentityObject; ServerIdentity serverID = idObj as ServerIdentity; if ((null != serverID) && idObj.IsFullyDisconnected()) { throw new ArgumentException( Environment.GetResourceString("Remoting_ServerObjectNotFound", reqMcmMsg.Uri)); } // Short-circuit calls to Object::GetType and Object::GetHashCode MethodBase mb = reqMcmMsg.MethodBase; if (_getTypeMethod == mb) { // Time to load the true type of the remote object.... Type t = GetProxiedType(); return(new ReturnMessage(t, null, 0, cctx, reqMcmMsg)); } if (_getHashCodeMethod == mb) { int hashCode = idObj.GetHashCode(); return(new ReturnMessage(hashCode, null, 0, cctx, reqMcmMsg)); } // check for channel sink if (idObj.ChannelSink == null) { IMessageSink chnlSink = null; IMessageSink envoySink = null; // If channelSink is null try to Create them again // the objref should be correctly fixed up at this point if (!idObj.ObjectRef.IsObjRefLite()) { RemotingServices.CreateEnvoyAndChannelSinks(null, idObj.ObjectRef, out chnlSink, out envoySink); } else { RemotingServices.CreateEnvoyAndChannelSinks(idObj.ObjURI, null, out chnlSink, out envoySink); } // Set the envoy and channel sinks in a thread safe manner RemotingServices.SetEnvoyAndChannelSinks(idObj, chnlSink, envoySink); // If the channel sink is still null then throw if (idObj.ChannelSink == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Proxy_NoChannelSink")); } } // Set the identity in the message object IInternalMessage iim = (IInternalMessage)reqMcmMsg; iim.IdentityObject = idObj; if (null != serverID) { Message.DebugOut("Setting serveridentity on message \n"); iim.ServerIdentityObject = serverID; } else { // We need to set the URI only for identities that // are not the server identities. The uri is used to // dispatch methods for objects outside the appdomain. // Inside the appdomain (xcontext case) we dispatch // by getting the server object from the server identity. iim.SetURI(idObj.URI); } Message.DebugOut("InternalInvoke. Dispatching based on class type\n"); AsyncResult ar = null; switch (callType) { case Message.Sync: Message.DebugOut("RemotingProxy.Invoke Call: SyncProcessMsg\n"); BCLDebug.Assert(!useDispatchMessage, "!useDispatchMessage"); bool bSkipContextChain = false; Context currentContext = currentThread.GetCurrentContextInternal(); IMessageSink nextSink = idObj.EnvoyChain; // if we are in the default context, there can be no // client context chain, so we can skip the intermediate // calls if there are no envoy sinks if (currentContext.IsDefaultContext) { if (nextSink is EnvoyTerminatorSink) { bSkipContextChain = true; // jump directly to the channel sink nextSink = idObj.ChannelSink; } } retMsg = CallProcessMessage(nextSink, reqMcmMsg, idObj.ProxySideDynamicSinks, currentThread, currentContext, bSkipContextChain); break; case Message.BeginAsync: case Message.BeginAsync | Message.OneWay: // For async calls we clone the call context from the thread // This is a limited clone (we dont deep copy the user data) cctx = (LogicalCallContext)cctx.Clone(); iim.SetCallContext(cctx); ar = new AsyncResult(reqMsg); InternalInvokeAsync(ar, reqMsg, useDispatchMessage, callType); Message.DebugOut("Propagate out params for BeginAsync\n"); retMsg = new ReturnMessage(ar, null, 0, null /*cctx*/, reqMsg); break; case Message.OneWay: // For async calls we clone the call context from the thread // This is a limited clone (we dont deep copy the user data) cctx = (LogicalCallContext)cctx.Clone(); iim.SetCallContext(cctx); InternalInvokeAsync(null, reqMsg, useDispatchMessage, callType); retMsg = new ReturnMessage(null, null, 0, null /*cctx*/, reqMcmMsg); break; case (Message.EndAsync | Message.OneWay): retMsg = new ReturnMessage(null, null, 0, null /*cctx*/, reqMcmMsg); break; case Message.EndAsync: // For endAsync, we merge back the returned callContext // into the thread's callContext retMsg = RealProxy.EndInvokeHelper(reqMsg, true); break; } return(retMsg); }
public SelectedScanEventArgs(MsDataFileUri dataFile, double retentionTime, Identity transitionId) { DataFile = dataFile; RetentionTime = retentionTime; TransitionId = transitionId; }
//揪團成員循著網址找到此方法 //GET: Account/Get_MyOrder public ActionResult Get_MyOrder(string ID) { if (String.IsNullOrEmpty(ID)) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //確認截止訂單(將過期的訂單結止) Models.HomeModels.HaveEndOrder(); //先將空白字服替換成+符 ID = ID.Replace(" ", "+"); //以Guid取出資料 var Check = db.SendMessageViews.Find(ID); if (Check == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //取出使用者ID及orderID var User = db.Users.Find(Check.UserID); var Order = db.CreateBuyOrder_LeaderOrders.Find(Check.OrderID); if (User == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //判斷訂單是否已經結束 if (Order == null || Order.CanOrNotOrder == 1 || Order.CanOrNotOrder == 2) { //將訂單設為已讀 Check.ReadOrNot = true; db.SaveChanges(); TempData["message"] = "這筆訂單已經結束訂購囉!"; return RedirectToAction("MessageView_Read", "Home"); } //將使用者的EMail,Name,Identity,權限存進Sessiion中 //存權限的順序依照資料庫 Identity query2 = db.Identities.Find(User.ID); UserCanDo query3 = db.UserCanDoes.Find(User.ID); string userdata = User.Email + "," + User.Identity + "," + query2.Identity2 + "," + query3.BuyDrink + "," + query3.OrderSet + "," + query3.Message + "," + query3.Callnotice + "," + query3.ChangePsd + "," + query3.MyUserSet + "," + query3.MyMenuSet; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, User.Name, DateTime.Now, DateTime.Now.AddMinutes(30), true, userdata, FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); cookie.HttpOnly = true; Response.Cookies.Add(cookie); //將資料設為已讀 ////有效期限為兩小時 //var time = DateTime.Now; //DateTime start = Convert.ToDateTime(Check.SendTime); //DateTime end = Convert.ToDateTime(time); ////判斷是否同一天 //string sDay = start.ToString("yyyyMMdd"); //string eDay = end.ToString("yyyyMMdd"); //if (sDay != eDay) //{ // Check.ReadOrNot = true; // db.SaveChanges(); // TempData["message"] = "這筆邀請已經過期囉!"; // return RedirectToAction("MessageView_Read", "Home"); //} ////先判斷上下午 //string W = start.ToString("tt"); //string N = end.ToString("tt"); //string ss = start.ToString("HH"); //string ee = end.ToString("HH"); //if (W == "下午" && ss == "00") //{ // ss = "22"; //} //if (W == "上午" && ss == "00") //{ // ss = "12"; //} //int stime = Int32.Parse(ss); //int etime = Int32.Parse(ee); //var dateH = etime - stime; ////TimeSpan ts = end.Subtract(start); ////var dateH = ts.Hours; //if (dateH >= 0 && (dateH < 2 || dateH == 0)) //{ // Check.ReadOrNot = true; // db.SaveChanges(); //} //else //{ // Check.ReadOrNot = true; // TempData["message"] = "這筆邀請已經超過2小時囉!"; // return RedirectToAction("MessageView_Read", "Home"); //} Check.ReadOrNot = true; db.SaveChanges(); //導入加點飲料介面 return RedirectToAction("DMDetail", "AnyDMorBuy", new { id = Order.MenuID, BuyCheck = Check.OrderID }); }
private static string GetKey(Identity identity) => $"identity_{identity.Type}_{identity.Id}";