/// <summary> /// Получение и обработка данных от клиента /// </summary> private void HandleClient() { int cmd = 0; log.WriteLine("Нашел клиента"); while (true) { try { cs.Receive(CNB.Ms_Buf); CNB.Ms.Position = 0; // Получаем команду и вызываем метод, выбирающий нужный обработчик cmd = CNB.Br.ReadInt32(); HandleReceive((Command)cmd); } catch (Exception E) { WriteLine(E.Message); cs.Close(); Command c = (Command)cmd; // Если что-то пошло не так во время загрузки файла на сервер, то // устанавливаем сервер в режим ожидания переподключения клиента if (CNB.Ms_Buf.Length != 0 && c == Command.Save) { Renew.ClientLosenTime = DateTime.Now; Renew.ExecCommandParam = CNB.Br.ReadString(); Renew.BuffPosition = Renew.GetPosition(CNB.Ms_Buf); Renew.Need = true; } // Далее в любом случае начинаем заново ждать подключения FindClient(); } } }
private async Task PullPointAsync(EndpointAddress endPointAddress, CancellationToken cancellationToken) { var pullPointSubscriptionClient = onvifClientFactory.CreateClient <PullPointSubscription>(endPointAddress, ConnectionParameters, MessageVersion.Soap12WSAddressing10); var subscriptionManagerClient = onvifClientFactory.CreateClient <SubscriptionManager>(endPointAddress, ConnectionParameters, MessageVersion.Soap12WSAddressing10); var pullRequest = new PullMessagesRequest("PT5S", 1024, null); int renewIntervalMs = (int)(subscriptionTerminationTime.TotalMilliseconds / 2); int lastTimeRenewMade = Environment.TickCount; while (!cancellationToken.IsCancellationRequested) { PullMessagesResponse response = await pullPointSubscriptionClient.PullMessagesAsync(pullRequest).ConfigureAwait(false); foreach (var messageHolder in response.NotificationMessage) { EventReceived(this, new DeviceEvent(messageHolder)); } if (IsTimeOver(lastTimeRenewMade, renewIntervalMs)) { lastTimeRenewMade = Environment.TickCount; var renew = new Renew { TerminationTime = GetTerminationTime() }; await subscriptionManagerClient.RenewAsync(new RenewRequest(renew)).ConfigureAwait(false); } } await subscriptionManagerClient.UnsubscribeAsync(new UnsubscribeRequest(new Unsubscribe())).ConfigureAwait(false); }
public void FindClient() { log.WriteLine("Ищу клиента"); cs = socket.Accept(); // Приняли подключение log.WriteLine("Проверяю возможность и необходимость докачки"); // Производим докачку если она нужна и таймаут ещё не закончился if (Server.Renew.Need) { if ((DateTime.Now - Renew.ClientLosenTime).TotalSeconds < 35) // в этом месте в последствии "35" нужно будет заменить на // специальный параметр "RenewTimeOut" { Renew.Start(CNB, cs, log); cs.Receive(CNB.Ms_Buf); CNB.Ms.Position = 0; HandleSave(); } else { log.WriteLine("Время для докачки вышло"); Renew.Need = false; CNB.Bw.Write(Renew.Need); cs.Send(CNB.Ms_Buf); } } else { log.WriteLine("Докачка не нужна"); CNB.Bw.Write(Renew.Need); cs.Send(CNB.Ms_Buf); } // Далее в любом случае начинаем ждать данных от клиента для обработки HandleClient(); }
public void UnsubscribeTest() { int actualTerminationTime = 10; SubscriptionHandler Handler = new SubscriptionHandler(this, true); Handler.SetPolicy(new EventsVerifyPolicy(true)); bool Unsubscribed = false; RunTest( () => { Handler.SetAddress(GetEventServiceAddress()); Handler.Subscribe(null, actualTerminationTime); SubscriptionHandler.Unsubscribe(Handler); Unsubscribed = true; TestErrorStep( () => { Renew renew = new Renew(); renew.TerminationTime = "PT10S"; Handler.GetProxy().Renew(renew); }, ValidateResourseUnknownFault ); }, () => { if (!Unsubscribed) { SubscriptionHandler.Unsubscribe(Handler); } }); }
public void UnsubscribeTest() { EndpointReferenceType subscriptionReference = null; bool unsubscribed = true; RunTest <object>( new Backup <object>( () => { return(null); }), () => { EnsureNotificationProducerClientCreated(); SubscribeResponse subscribeResponse = CreateStandardSubscription(); unsubscribed = false; if (subscribeResponse == null) { return; } subscriptionReference = subscribeResponse.SubscriptionReference; Unsubscribe request = new Unsubscribe(); UnsubscribeResponse unsubscribeResponse = Unsubscribe(request); unsubscribed = true; Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RunStep( () => { _subscriptionManagerClient.Renew(renew); unsubscribed = false; }, "Renew - negative test", new ValidateTypeFault(ValidateResourseUnknownFault)); }, (o) => { if (!unsubscribed) { if (subscriptionReference != null) { CreateSubscriptionManagerClient(subscriptionReference); } // // Use default timeout of 10 seconds. // Really timeout passed in Subscribe request may be different. // ReleaseSubscriptionManager(); } }); }
private void SpaceForm_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && generating > 0) // 왼쪽 버튼일 때, 모드 0을 거쳤을 때. { double r = diameter / 2.0; space.AddPlanet(new Planet(downX, downY, mass, diameter, planetColor, speed)); // space 객체에 행성 추가. generating = 0; // 모드 0으로 초기화. OnPaint(null); Renew.Start(); // 타이머 재시작. } }
public void TimeoutTest() { EndpointReferenceType endpointReference = null; RunTest <object>( () => { return(null); }, () => { EnsureEventPortTypeClientCreated(); int actualTerminationTime = 20; endpointReference = CreateStandardSubscription(ref actualTerminationTime); if (endpointReference == null) { return; } BeginStep("Wait until subscription expires"); Sleep(actualTerminationTime * 1000 + _operationDelay); StepPassed(); Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RunStep( () => { _subscriptionManagerClient.Renew(renew); }, "Renew - negative test", new ValidateTypeFault(ValidateUnsubscribeFault)); }, (o) => { if (endpointReference != null) { if (endpointReference.Address != null && _subscriptionManagerClient == null) { CreateSubscriptionManagerClient(endpointReference); } // // Use timeout of 10 seconds. // TT has already spent time waiting for timeout passed in Subscribe. // 10 seconds is the same as value passed in Renew. // ReleaseSubscriptionManager(10000); } }); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="stepName"></param> /// <returns></returns> /// <remarks>As this method uses SubscriptionManager client, care should be taken that client is created. /// It's not posisble to create it here since Subscribe method should be called first to get endpoint address.</remarks> protected RenewResponse Renew(Renew request, string stepName) { RenewResponse response = null; RunStep(() => { response = _subscriptionManagerClient.Renew(request); }, stepName); return(response); }
public void RenewTest() { EndpointReferenceType endpointReference = null; int actualTerminationTime = 10; RunTest <object>( () => { return(null); }, () => { EnsureEventPortTypeClientCreated(); endpointReference = CreateStandardSubscription(ref actualTerminationTime); if (endpointReference == null) { return; } Renew renew = new Renew(); renew.TerminationTime = "PT10S"; // there was no requirement to retry Renew for this test RenewResponse renewResponse = Renew(renew); Assert(renewResponse != null, "The DUT did not return Renew response", "Check that the DUT returned Renew response"); Assert(renewResponse.CurrentTimeSpecified, "Current time is not specified", "Check that CurrentTime is specified"); Assert(renewResponse.TerminationTime.HasValue, "Termination time is not specified", "Check that TerminationTime is specified"); Assert(renewResponse.CurrentTime.AddSeconds(10) <= renewResponse.TerminationTime.Value, "TerminationTime < CurrentTime + InitialTerminationTime", "Validate times"); }, (o) => { if (endpointReference != null) { if (endpointReference.Address != null && _subscriptionManagerClient == null) { CreateSubscriptionManagerClient(endpointReference); } ReleaseSubscriptionManager(actualTerminationTime * 1000); } }); }
private void btnRenew_Click(object sender, EventArgs e) { SafeInvoke(() => { Renew renew = new Renew(); renew.TerminationTime = tbRenewTime.Text; RenewResponse response = _subscriptionManager.Renew(renew); if (response.TerminationTime.HasValue) { _terminationTime = response.TerminationTime.Value; tbTerminationTime.Text = _terminationTime.ToString("hh:mm:ss.fff"); } }); }
public void Execute(Dictionary <string, string> arguments) { bool ptt = arguments.ContainsKey("/ptt"); string dc = arguments.ContainsKey("/dc") ? arguments["/dc"] : string.Empty; if (arguments.ContainsKey("/ticket")) { string kirbi64 = arguments["/ticket"]; if (Helpers.IsBase64String(kirbi64)) { KRB_CRED kirbi = new KRB_CRED(Convert.FromBase64String(kirbi64)); if (arguments.ContainsKey("/autorenew")) { // if we want to auto-renew the TGT up until the renewal limit Renew.TGTAutoRenew(kirbi, dc); } else { // otherwise a single renew operation byte[] blah = Renew.TGT(kirbi, ptt, dc); } } else if (File.Exists(kirbi64)) { KRB_CRED kirbi = new KRB_CRED(File.ReadAllBytes(kirbi64)); if (arguments.ContainsKey("/autorenew")) { // if we want to auto-renew the TGT up until the renewal limit Renew.TGTAutoRenew(kirbi, dc); } else { // otherwise a single renew operation byte[] blah = Renew.TGT(kirbi, ptt, dc); } } else { Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n"); } } else { Console.WriteLine("\r\n[X] A /ticket:X needs to be supplied!\r\n"); } }
public override RenewResponse Renew([System.Xml.Serialization.XmlElementAttribute("Renew", Namespace = "http://docs.oasis-open.org/wsn/b-2")] Renew Renew1) { SoapHeaderProcessing(unknownHeaders); TestSuitInit(); RenewResponse res; int timeOut; SoapException ex; StepType stepType = m_EventServiceTest.SMSRenewTest(out res, out ex, out timeOut, Renew1); StepTypeProcessing(stepType, ex, timeOut); actionHeader.actionValue = "http://docs.oasis-open.org/wsn/bw-2/SubscriptionManager/RenewResponse"; return(res); }
public void UnsubscribeTest() { bool unsubscribed = true; RunTest <object>( () => { return(null); }, () => { EnsureEventPortTypeClientCreated(); EndpointReferenceType endpoint = CreateStandardSubscription(); if (endpoint == null) { return; } Unsubscribe request = new Unsubscribe(); UnsubscribeResponse unsubscribeResponse = Unsubscribe(request); unsubscribed = true; Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RunStep( () => { _subscriptionManagerClient.Renew(renew); unsubscribed = false; }, "Renew - negative test", new ValidateTypeFault(ValidateResourseUnknownFault)); }, (o) => { if (!unsubscribed) { BeginStep("Wait until subscription expires"); Sleep(10000); StepPassed(); } }); }
public override RenewResponse Renew([System.Xml.Serialization.XmlElementAttribute("Renew", Namespace = "http://docs.oasis-open.org/wsn/b-2")] Renew Renew1) { SoapHeaderProcessing(unknownHeaders); ParametersValidation validation = new ParametersValidation(); validation.Add(ParameterType.Log, "TerminationTime", Renew1.TerminationTime); ExecuteVoidCommand(validation, PullPointSubscriptionServiceTest.RenewTest); RenewResponse result = new RenewResponse(); result.CurrentTimeSpecified = true; result.CurrentTime = PullPointSubscriptionServiceTest.TakeCurrentTime(); result.TerminationTime = PullPointSubscriptionServiceTest.TakeTerminationTime(result.CurrentTime); actionHeader.actionValue = "http://docs.oasis-open.org/wsn/bw-2/SubscriptionManager/RenewResponse"; return(result); }
public override RenewResponse Renew([System.Xml.Serialization.XmlElementAttribute("Renew", Namespace = "http://docs.oasis-open.org/wsn/b-2")] Renew Renew1) { int subscriptionKey = SoapReferanceHeaderProcessing(unknownHeaders); ConfStorageLoad(); EventServerLoad(); DateTime terminationTime; try { TimeSpan timeSpan = System.Xml.XmlConvert.ToTimeSpan(Renew1.TerminationTime); terminationTime = DateTime.UtcNow.Add(timeSpan.Add(new TimeSpan(0, 0, 1))); } catch (Exception) { try { terminationTime = System.Xml.XmlConvert.ToDateTime(Renew1.TerminationTime, XmlDateTimeSerializationMode.Utc); } catch (Exception) { throw FaultLib.GetSoapException(FaultType.General, "Wrong Initial Termination Time."); } } EventServer.RenewSubscribtion(subscriptionKey, terminationTime); RenewResponse res = new RenewResponse(); res.CurrentTimeSpecified = true; res.CurrentTime = DateTime.UtcNow; res.TerminationTime = terminationTime; EventServerSave(); ConfStorageSave(); actionHeader.actionValue = "http://docs.oasis-open.org/wsn/bw-2/SubscriptionManager/RenewResponse"; return(res); }
public RenewResponse Renew([System.Xml.Serialization.XmlElementAttribute("Renew", Namespace = "http://docs.oasis-open.org/wsn/b-2")] Renew Renew1) { if (Application["consumer"] == null) { SoapFaultSubCode subCode = new SoapFaultSubCode(new XmlQualifiedName("ResourseUnknown1", "http://www.onvif.org/ver10/error")); SoapException exception = new SoapException("Invalid Argument", new XmlQualifiedName("Sender", "http://www.w3.org/2003/05/soap-envelope"), subCode); throw exception; } RenewResponse response = new RenewResponse(); response.CurrentTime = System.DateTime.Now; response.CurrentTimeSpecified = true; response.TerminationTime = response.CurrentTime.AddSeconds(15); return(response); }
private void SpaceForm_MouseDown(object sender, MouseEventArgs e) // 마우스 Down 이벤트. { if (e.Button == MouseButtons.Left) // 마우스 버튼 클릭이 왼쪽일 때 수행. { Renew.Stop(); // 타이머 일시정지. // 사용자가 입력한 정보를 종합하여 변수에 저장. mass = (double)massNumeric.Value; planetColor = Color.FromArgb((int)rNumeric.Value, (int)gNumeric.Value, (int)bNumeric.Value); speed = new System.Windows.Vector(); diameter = (double)volumeNumeric.Value; downX = e.Location.X; // 마우스 Down 좌표 저장. downY = e.Location.Y; generating = 1; // 모드 1로 변경. OnPaint(null); // 화면 갱신. } else if (e.Button == MouseButtons.Right) // 오른쪽 버튼일 경우 작업 취소. { generating = 0; OnPaint(null); Renew.Start(); } }
public void RenewTest() { EndpointReferenceType subscriptionReference = null; bool subscribed = false; int terminationTime = 10; RunTest <object>( new Backup <object>( () => { return(null); }), () => { SubscribeResponse subscribeResponse = CreateStandardSubscription(); if (subscribeResponse == null) { return; } subscribed = true; subscriptionReference = subscribeResponse.SubscriptionReference; Renew renew = new Renew(); renew.TerminationTime = "PT10S"; RenewResponse renewResponse = null; bool retry = false; try { renewResponse = Renew(renew); } catch (FaultException exc) { FaultException <UnacceptableTerminationTimeFaultType> invalidTerminationTimeFault = exc as FaultException <UnacceptableTerminationTimeFaultType>; if (invalidTerminationTimeFault != null) { LogStepEvent(string.Format("Exception of type FaultException<UnacceptableTerminationTimeFaultType> received. Try to renew subscription with new parameters")); StepPassed(); string duration = string.Empty; terminationTime = GetRecommendedDuration <UnacceptableTerminationTimeFaultType>(invalidTerminationTimeFault, out duration); retry = true; renew.TerminationTime = duration; } else { throw; } } if (retry) { renewResponse = Renew(renew); } ValidateRenewResponse(renewResponse, terminationTime); DateTime requestTerminationTime = DateTime.UtcNow.AddSeconds(terminationTime); requestTerminationTime = new DateTime(requestTerminationTime.Year, requestTerminationTime.Month, requestTerminationTime.Day, requestTerminationTime.Hour, requestTerminationTime.Minute, requestTerminationTime.Second, requestTerminationTime.Kind); // TEST --> // requestTerminationTime = DateTime.Parse("2011-06-09T13:27:46Z").ToUniversalTime(); // TEST <-- string xsDateTime = requestTerminationTime.ToString("yyyy-MM-ddTHH:mm:ssZ"); // TEST --> //xsDateTime = "2011-06-09T13:27:46Z"; //requestTerminationTime = DateTime.Parse(xsDateTime); // <-- renew.TerminationTime = xsDateTime; try { renewResponse = Renew(renew, "Renew subscription - use xs:DateTime format for TerminationTime"); } catch (FaultException exc) { FaultException <UnacceptableTerminationTimeFaultType> invalidTerminationTimeFault = exc as FaultException <UnacceptableTerminationTimeFaultType>; if (invalidTerminationTimeFault != null) { LogStepEvent(string.Format("Exception of type FaultException<UnacceptableTerminationTimeFaultType> received. Try to renew subscription with new parameters")); StepPassed(); string duration = string.Empty; terminationTime = GetRecommendedDuration <UnacceptableTerminationTimeFaultType>(invalidTerminationTimeFault, out duration); requestTerminationTime = DateTime.UtcNow.AddSeconds(terminationTime); requestTerminationTime = new DateTime(requestTerminationTime.Year, requestTerminationTime.Month, requestTerminationTime.Day, requestTerminationTime.Hour, requestTerminationTime.Minute, requestTerminationTime.Second, requestTerminationTime.Kind); xsDateTime = requestTerminationTime.ToString("yyyy-MM-ddTHH:mm:ssZ"); //LogStepEvent(string.Format("Send TerminationTime '{0}'", xsDateTime)); retry = true; renew.TerminationTime = xsDateTime; } else { throw; } } if (retry) { renewResponse = Renew(renew); } ValidateRenewResponse(renewResponse, requestTerminationTime); }, (o) => { if (subscribed) { if (subscriptionReference != null) { CreateSubscriptionManagerClient(subscriptionReference); } ReleaseSubscriptionManager(terminationTime * 1000); } }); }
public void Renew() { int count = uow.Renews.GetAll().AsQueryable<Renew>().Count<Renew>(); #region Add Renew newEntity = new Renew() { LicenseNo = "LicenseNo", RequestID = (long)LookUps.LookUpsValues["RequestID"] }; uow.Renews.Add<Renew, long>(newEntity); uow.Renews.Commit(); var result = uow.Renews.GetAll().AsQueryable<Renew>(); Assert.AreEqual(count + 1, result.Count<Renew>(), "Adding Error"); #endregion #region Update Renew entity = uow.Renews.GetById(newEntity.ID); entity.LicenseNo = "LicenseNo2"; uow.Renews.Update(entity); uow.Renews.Commit(); Renew entity2 = uow.Renews.GetById(newEntity.ID); Assert.AreEqual("LicenseNo2", entity2.LicenseNo, "Updating Error"); #endregion #region Delete Renew entityDeleted = uow.Renews.GetById(newEntity.ID); uow.Renews.Delete(entity2); uow.Renews.Commit(); Assert.AreEqual(count, uow.Renews.GetAll().AsQueryable<Renew>().Count<Renew>(), "Deleting Error"); #endregion }
private void EnumerateInternalWithADWS(string distinguishedName, string filter, string[] properties, string scope, ReceiveItems callback) { bool nTSecurityDescriptor = false; List <string> listproperties = new List <string>(); Enumerate enumerate = new Enumerate(); enumerate.Filter = new FilterType(); enumerate.Filter.LdapQuery = new LdapQuery(); enumerate.Filter.LdapQuery.BaseObject = distinguishedName; Trace.WriteLine("LdapQuery.BaseObject=" + enumerate.Filter.LdapQuery.BaseObject); enumerate.Filter.LdapQuery.Scope = scope; enumerate.Filter.LdapQuery.Filter = filter; Trace.WriteLine("LdapQuery.Filter=" + enumerate.Filter.LdapQuery.Filter); if (properties != null) { listproperties.AddRange(properties); enumerate.Selection = new Selection(); enumerate.Selection.SelectionProperty = BuildProperties(listproperties); } EnumerateResponse enumerateResponse = null; Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] Running enumeration"); bool hasNewProperties = true; while (hasNewProperties) { try { enumerateResponse = Search.Enumerate(enumerate); hasNewProperties = false; } catch (FaultException <schemas.microsoft.com._2008._1.ActiveDirectory.EnumerateFault> ex) { // handle the case where the property is not available in the schema. // an exception is thrown // remove the litigious property and resume the query Trace.WriteLine("The server doesn't support the property: " + ex.Detail.InvalidProperty); int postns = ex.Detail.InvalidProperty.IndexOf(':'); string property = ex.Detail.InvalidProperty; if (postns > 0) { property = ex.Detail.InvalidProperty.Substring(postns + 1); } if (!listproperties.Remove(property)) { throw; } if (listproperties.Count == 0) { return; } enumerate.Selection.SelectionProperty = BuildProperties(listproperties); } } Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Enumeration successful"); Trace.WriteLine("Enumeration expires at " + enumerateResponse.Expires); Trace.WriteLine("Enumeration context is " + String.Join(",", enumerateResponse.EnumerationContext.Text)); // prepare the flag for the ntsecuritydescriptor foreach (string property in listproperties) { if (String.Compare("nTSecurityDescriptor", property, true) == 0) { nTSecurityDescriptor = true; } } // do not fail if the expiration cannot be parsed DateTime expiration = DateTime.Now.AddMinutes(30); DateTime.TryParse(enumerateResponse.Expires, out expiration); bool bcontinue = true; int pagenum = 0; while (bcontinue) { if (expiration.AddMinutes(-5) < DateTime.Now) { Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Renewing the enumeration (expiration)"); Renew renew = new Renew(); renew.EnumerationContext = enumerateResponse.EnumerationContext; renew.Expires = DateTime.Now.AddMinutes(20).ToString("O"); RenewResponse renewresponse = Search.Renew(renew); Trace.WriteLine("New expiration at " + renewresponse.Expires); DateTime.TryParse(renewresponse.Expires, out expiration); Trace.WriteLine("New enumeration context " + String.Join(",", renewresponse.EnumerationContext.Text)); enumerateResponse.EnumerationContext = renewresponse.EnumerationContext; } Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Getting Enumerate page " + pagenum); Pull pull = new Pull(); pull.EnumerationContext = enumerateResponse.EnumerationContext; pull.MaxElements = "500"; if (nTSecurityDescriptor || DomainScope) { List <controlsControl> controls = new List <controlsControl>(); if (nTSecurityDescriptor) { // this is the flag https://msdn.microsoft.com/en-us/library/cc223323.aspx // the last byte, 0x07, is OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION controlsControl control = new controlsControl(); controls.Add(control); control.controlValue = Convert.ToBase64String(new byte[] { 0x30, 0x84, 0x00, 0x00, 0x00, 0x03, 0x02, 0x01, 0x07 }); control.criticality = true; control.type = "1.2.840.113556.1.4.801"; } if (DomainScope) { // this is the flag https://msdn.microsoft.com/en-us/library/cc223323.aspx // the last byte, 0x07, is OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION controlsControl control = new controlsControl(); controls.Add(control); control.criticality = true; control.type = "1.2.840.113556.1.4.1339"; } pull.controls = controls.ToArray(); } PullResponse pullResponse = null; try { pullResponse = Search.Pull(pull); } catch (FaultException ex) { Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Pull unsuccessful"); Trace.WriteLine("Fault Exception: " + ex.Message); Trace.WriteLine("Reason: " + ex.Reason); var stringWriter = new StringWriter(); var xmlTextWriter = new XmlTextWriter(stringWriter); var messageFault = ex.CreateMessageFault(); messageFault.WriteTo(xmlTextWriter, EnvelopeVersion.Soap12); var stringValue = Convert.ToString(stringWriter); Trace.WriteLine("Detail:"); Trace.WriteLine(stringValue); throw new PingCastleException("An ADWS exception occured (fault:" + ex.Message + ";reason:" + ex.Reason + ").\r\nADWS is a faster protocol than LDAP but bound to a default 30 minutes limitation. If this error persists, we recommand to force the LDAP protocol. Run PingCastle with the following switches: --protocol LDAPOnly --interactive"); } Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Pull successful"); if (pullResponse.EndOfSequence != null) { bcontinue = false; } callback(pullResponse.Items); pagenum++; } Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Releasing the enumeration context"); Release relase = new Release(); relase.EnumerationContext = enumerateResponse.EnumerationContext; Search.Release(relase); }
/// <summary> /// Called on start, sets the tooltip texts. /// </summary> void Start() { //Renew RenewHot renewHot = new RenewHot(); Renew renew = new Renew(); renew.Awake(); tooltip[1] = "Applies a buff that heals the target for " + (renewHot.HEALPERTICK * (renewHot.DURATION / renewHot.INTERVALLTICKS)) + " health over " + renewHot.DURATION + " seconds. "; tooltip[1] += GenerateSpellString(renew); //greaterHeal GreaterHeal greaterHeal = new GreaterHeal(); greaterHeal.Awake(); tooltip[2] = "A manaefficient spell that heals the target for " + greaterHeal.healAmount + " health. "; tooltip[2] += GenerateSpellString(greaterHeal); //placeholder CircleOfHealing circleOfHealing = new CircleOfHealing(); circleOfHealing.Awake(); tooltip[3] = "A spell that heals the " + circleOfHealing.numberTargets + " partymembers, which currently have the lowest health, for " + circleOfHealing.healAmount + " health each. "; tooltip[3] += GenerateSpellString(circleOfHealing); //prayer of mending PrayerBuff prayerBuff = new PrayerBuff(); Prayer prayer = new Prayer(); tooltip[4] = "Places a ward on a target that heals them for " + prayerBuff.HEALAMOUNT + " health the next time it takes damage, and then jumps to another target. Jumps up to " + prayerBuff.jumpsLeft + " times and lasts " + prayerBuff.DURATION + " seconds. "; tooltip[4] += GenerateSpellString(prayer); //NYI tooltip[5] = "NYI"; //NYI tooltip[6] = "NYI"; //hymn of hope Hymn hymn = new Hymn(); tooltip[7] = "Channels a hymn of hope that heals every partymember for " + (hymn.HEALAMOUNT * hymn.TICKS) + " health over " + hymn.CASTTIME + " seconds. "; tooltip[7] += GenerateSpellString(hymn); //dispell Dispell dispell = new Dispell(); tooltip[8] = "Removes all dispellable debuffs from your target. "; tooltip[8] += GenerateSpellString(dispell); //greaterHeal FlashHeal flashHeal = new FlashHeal(); greaterHeal.Awake(); tooltip[9] = "A fast spell that heals the target for " + flashHeal.HEALAMOUNT + " health. "; tooltip[9] += GenerateSpellString(flashHeal); //shield Shield shield = new Shield(); ShieldBuff shieldBuff = new ShieldBuff(); tooltip[10] = "Places a shield on a target that lasts " + shieldBuff.DURATION + " seconds and absorbs the next " + shieldBuff.absorbAmount + " damage it takes. "; tooltip[10] += GenerateSpellString(shield); //binding heal BindingHeal bindingHeal = new BindingHeal(); tooltip[11] = "A spell that heals the target and the partymember that currently has the lowest health for " + bindingHeal.HEALAMOUNT + " health each. "; tooltip[11] += GenerateSpellString(bindingHeal); //guardian spirit GuardianSpirit guardianSpirit = new GuardianSpirit(); GuardianSpiritBuff guardianSpiritBuff = new GuardianSpiritBuff(); tooltip[12] = "Calls upon a guardian spirit to watch over your target for " + guardianSpiritBuff.DURATION + " seconds and preventing the target from dying by sacificing itself, healing the target to full health. "; tooltip[12] += GenerateSpellString(guardianSpirit); }
void ExternalAuthorizationTimeoutTest( Func <AccessPointInfo, bool> accessPointCapabilitiesTest, TopicInfo accessRequestTopic, Action <XmlElement, TopicInfo> validateAccessRequestTopic, ValidateMessageFunction validateRequestMessageFunction, TopicInfo resultTopic, Action <XmlElement, TopicInfo> validateResultTopic, ValidateMessageFunction validateResultMessageFunction) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { //3. Get complete list of access points from the DUT (see Annex A.1). List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList(); //4. Check that there is at least one Access Point with required Capabilities List <AccessPointInfo> accessPointsList = null; if (accessPointCapabilitiesTest != null) { accessPointsList = fullAccessPointsList.Where(A => accessPointCapabilitiesTest(A)).ToList(); if (accessPointsList.Count == 0) { LogTestEvent("No AccessPoints with required Capabilities found, exit the test." + Environment.NewLine); return; } } else { accessPointsList = fullAccessPointsList; } // Get topic description from the DUT and check topics support ValidateTopicsSupport(accessRequestTopic, validateAccessRequestTopic, resultTopic, validateResultTopic); // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(new TopicInfo[] { accessRequestTopic, resultTopic }); // create notification listener and subscription Utils.NotifyServer server = new NotifyServer(_nic); SetupNotifyServer(server); string notificationsUri = server.GetNotificationUri(); subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out subscribeStarted); // get access request message string credentialsToken = string.Empty; string credentialsHolderName = string.Empty; string accessPointToken = GetAccessRequestMessage(server, timeout, accessRequestTopic, validateRequestMessageFunction, fullAccessPointsList, accessPointsList, ref credentialsToken, ref credentialsHolderName); RemoveHandlers(server); // receive events { EnsureNotificationProducerClientCreated(); LogTestEvent(string.Format("Wait for {0} event{1}", resultTopic.GetDescription(), Environment.NewLine)); Utils.NotifyAsyncServer asyncServer = new NotifyAsyncServer(_nic); SetupNotifyServer2(asyncServer); asyncServer.StartCollecting(_semaphore.StopEvent); AutoResetEvent received = new AutoResetEvent(false); asyncServer.NotificationReceived += new Action <byte[]>((data) => { received.Set(); }); Renew request = new Renew(); request.TerminationTime = "PT60S"; // use 50 second instead of 60 int subscriptionGuaranteedTimeLeft = (int)(subscribeStarted.AddSeconds(50) - System.DateTime.Now).TotalMilliseconds; if (subscriptionGuaranteedTimeLeft < 0) { subscriptionGuaranteedTimeLeft = 0; } System.DateTime exitTime = System.DateTime.Now.AddMilliseconds(_messageTimeout); try { while (true) { // check if we are still waiting the message int waitTimeLeft = (int)(exitTime - System.DateTime.Now).TotalMilliseconds; if (waitTimeLeft <= 0) { break; } // compute time for next wait int waitTime = Math.Min(subscriptionGuaranteedTimeLeft, waitTimeLeft); int res = WaitHandle.WaitAny(new WaitHandle[] { received, _semaphore.StopEvent }, waitTime); if (res == WaitHandle.WaitTimeout) { // no notification received if (System.DateTime.Now < exitTime) { Renew(request); subscriptionGuaranteedTimeLeft = 50000; subscribeStarted = System.DateTime.Now; } else { break; } } else if (res == 1) { asyncServer.StopCollecting(); // Stop event received throw new StopEventException(); } else { // Notification received break; } } } catch (Exception exc) { throw; } finally { asyncServer.StopCollecting(); RemoveHandlers2(asyncServer); } Dictionary <Notify, byte[]> messages = asyncServer.Get(); Assert(messages.Count > 0, "No notifications received", "Check if the DUT sent notifications"); Notify notify = messages.Keys.First(); byte[] rawData = messages[notify]; ValidateNotificationsPacket(rawData); ValidateNotifyNotEmpty(notify); NotificationMessageHolderType theMessage = notify.NotificationMessage[0]; ValidateResultMessage(notify, theMessage, rawData, resultTopic, validateResultMessageFunction, accessPointToken, credentialsToken, credentialsHolderName); } }, () => { _operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
/// <summary> /// Wrapper for Renew method. /// </summary> /// <param name="request"></param> /// <returns></returns> /// <remarks>As this method uses SubscriptionManager client, care should be taken that client is created. /// It's not posisble to create it here since Subscribe method should be called first to get endpoint address.</remarks> protected RenewResponse Renew(Renew request) { return(Renew(request, "Renew subscription")); }
internal StepType SMSRenewTest(out RenewResponse target, out SoapException ex, out int timeOut, Renew Renew1) { StepType res = StepType.None; target = new RenewResponse(); timeOut = 0; ex = null; bool passed = true; string logMessage = ""; //Get step list for command XmlNodeList m_testList = m_TestCommon.GetStepsForCommand("SMSRenew"); if (m_testList != null) { //Get current step XmlNode test = m_testList[m_commandCount[SMSRenew]]; #region Analyze request //TerminationTime if (test.SelectNodes("RequestParameters/TerminationTime[@type=\"now+diff\"]").Count == 0) { CommonCompare.StringCompare("RequestParameters/TerminationTime", "TerminationTime", Renew1.TerminationTime, ref logMessage, ref passed, test); } else { CommonCompare.CompareRealTime("RequestParameters/TerminationTime", "TerminationTime", Renew1.TerminationTime, ref logMessage, ref passed, test); } #endregion //Analyze request //Generate response object targetObj; res = m_TestCommon.GenerateResponseStepTypeNotVoid(test, out targetObj, out ex, out timeOut, typeof(RenewResponse)); target = (RenewResponse)targetObj; #region Serialization Temp //Events.EndpointReferenceType dsr = new Events.EndpointReferenceType(); //dsr.Address = new Events.AttributedURIType(); //dsr.Address.Value = "http://192.168.10.203/onvif/event"; //dsr.Metadata = new Events.MetadataType(); //dsr.ReferenceParameters = new Events.ReferenceParametersType(); //XmlSerializer serializer1 = new XmlSerializer(typeof(Events.EndpointReferenceType)); //TextWriter textWriter = new StreamWriter("c:\\2.txt"); //serializer1.Serialize(textWriter, dsr); #endregion //Serialization Temp if (res == StepType.Normal) { //CurrentTime string CurrentTimeType = test.SelectSingleNode("ResponseParametersAdditional/CurrentTime/@type").InnerText; switch (CurrentTimeType) { case "now": { target.CurrentTime = System.DateTime.UtcNow; break; } case "value": { target.CurrentTime = Convert.ToDateTime(test.SelectSingleNode("ResponseParametersAdditional/CurrentTime").InnerText); break; } case "nowDiff": { int timeDiff = Convert.ToInt32(test.SelectSingleNode("ResponseParametersAdditional/CurrentTime").InnerText); target.CurrentTime = System.DateTime.UtcNow.AddSeconds(timeDiff); break; } case "none": { target.CurrentTimeSpecified = false; break; } } //TerminationTime if (test.SelectNodes("ResponseParametersAdditional/TerminationTime[@type=\"fromrequest\"]").Count != 0) { target.TerminationTime = Convert.ToDateTime(Renew1.TerminationTime); } else { if (test.SelectNodes("ResponseParametersAdditional/TerminationTime[@differance=\"true\"]").Count != 0) { int timeDiff = Convert.ToInt32(test.SelectSingleNode("ResponseParametersAdditional/TerminationTime").InnerText); target.TerminationTime = target.CurrentTime.AddSeconds(timeDiff); } else { target.TerminationTime = Convert.ToDateTime(test.SelectSingleNode("ResponseParametersAdditional/TerminationTime").InnerText); } } } m_TestCommon.writeToLog(test, logMessage, passed); Increment(m_testList.Count, SMSRenew); } else { timeOut = 0; target = null; ex = null; res = StepType.None; } return(res); }
public void Execute(Dictionary <string, string> arguments) { string outfile = ""; bool ptt = false; string dc = ""; if (arguments.ContainsKey("/outfile")) { outfile = arguments["/outfile"]; } if (arguments.ContainsKey("/ptt")) { ptt = true; } if (arguments.ContainsKey("/dc")) { dc = arguments["/dc"]; } if (arguments.ContainsKey("/ticket")) { string kirbi64 = arguments["/ticket"]; byte[] kirbiBytes = null; if (Helpers.IsBase64String(kirbi64)) { kirbiBytes = Convert.FromBase64String(kirbi64); } else if (File.Exists(kirbi64)) { kirbiBytes = File.ReadAllBytes(kirbi64); } if (kirbiBytes == null) { Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n"); } else { KRB_CRED kirbi = new KRB_CRED(kirbiBytes); if (arguments.ContainsKey("/autorenew")) { Console.WriteLine("[*] Action: Auto-Renew Ticket\r\n"); // if we want to auto-renew the TGT up until the renewal limit Renew.TGTAutoRenew(kirbi, dc); } else { Console.WriteLine("[*] Action: Renew Ticket\r\n"); // otherwise a single renew operation byte[] blah = Renew.TGT(kirbi, outfile, ptt, dc); } } return; } else { Console.WriteLine("\r\n[X] A /ticket:X needs to be supplied!\r\n"); return; } }
public async Task PullPointAsync(System.Threading.CancellationToken cancellationToken) { if (m_PullPointSubscriptionClient == null) { } // var pullPointSubscriptionClient = _onvifClientFactory.CreateClient<PullPointSubscription>(endPointAddress, _connectionParameters, // MessageVersion.Soap12WSAddressing10); // var subscriptionManagerClient = _onvifClientFactory.CreateClient<SubscriptionManager>(endPointAddress, _connectionParameters, // MessageVersion.Soap12WSAddressing10); try { var pullRequest = new PullMessagesRequest("PT1S", 1024, null); pullRequest.MessageLimit = 1024; pullRequest.Timeout = "PT1S"; // int renewIntervalMs = (int)(m_subscriptionTerminationTime.TotalMilliseconds / 2); // int lastTimeRenewMade = Environment.TickCount; TimeUtil timeutil = new TimeUtil(m_subscriptionTerminationTime.TotalMilliseconds / 2); while (!cancellationToken.IsCancellationRequested) { PullMessagesResponse response = await m_PullPointSubscriptionClient.PullMessagesAsync(pullRequest); foreach (var messageHolder in response.NotificationMessage) { if (messageHolder.Message == null) { continue; } string var = messageHolder.Message.Value; var @event = new DeviceEvent(messageHolder.Message.Value); OnEventReceived(@event); } if (timeutil.IsTimeover()) { timeutil.Time = System.DateTime.Now; // lastTimeRenewMade = Environment.TickCount; var renew = new Renew { TerminationTime = GetTerminationTime() }; // var renewrequ = new RenewRequest(); // renewrequ.Renew = renew; await m_SubscriptionManagerClient.RenewAsync(renew); } } //new UnsubscribeRequest(new Unsubscribe()) OnVifServices.OnvifEvent10.Unsubscribe unsub = new Unsubscribe(); await m_SubscriptionManagerClient.UnsubscribeAsync(unsub); } catch (Exception ex) { m_ErrorMessage = ex.Message; } }
public static void ShowWindow() { Renew window = GetWindow <Renew>("Sprite Importer"); }