private void GetServiceStatus() { if (service != null) service.Refresh(); var ss = ServiceControl.GetServiceStatus(service); if (ss != serviceStatus) { serviceStatus = ss; DDnsSharpTray.SetStatus(serviceStatus); string serviceStr; switch (serviceStatus) { case ServiceStatus.Running: serviceStr = "服务正在运行."; break; case ServiceStatus.Stopped: serviceStr = "服务已停止."; break; case ServiceStatus.NotExist: serviceStr = "服务尚未安装."; break; default: serviceStr = "服务状态未知."; break; } DDnsSharpTray.Current.Text = "DDnsSharp: " + serviceStr + "\r\n双击打开或隐藏界面."; } }
public static void SetStatus(ServiceStatus ss) { if (instance != null) { instance.Icon = iconDict[ss]; } }
internal ServiceStatusEventArgs(IServiceAddress serviceAddress, ServiceType serviceType, ServiceStatus oldStatus, ServiceStatus newStatus) { this.serviceAddress = serviceAddress; this.serviceType = serviceType; this.oldStatus = oldStatus; this.newStatus = newStatus; }
// constructors /// <summary> /// Initializes a new instance of the <see cref="Service"/> class. /// </summary> protected Service() { this.status = (this is ServiceControllable) ? ServiceStatus.Stopped : ServiceStatus.Passive; this.statusDate = DateTimeOffset.UtcNow; this.log = new Logger(this.Name); }
public void Start() { Stop(); _timer = new Timer(5000); _timer.Elapsed += TimerOnElapsed; _timer.Start(); ServiceStatus = ServiceStatus.Started; }
public void Stop() { if (_timer != null) { _timer.Stop(); _timer.Dispose(); _timer = null; } ServiceStatus = ServiceStatus.Stopped; }
public void Resume() { Monitor.Enter(this.lockObject); if (this.serviceStatus == ServiceStatus.Paused) { this.serviceStatus = ServiceStatus.Running; } Monitor.Exit(this.lockObject); }
public void StopService() { try { SaveSettings(); } finally { Status = ServiceStatus.Stopped; } }
private void DoStart(string[] args) { if (m_verbose_messages) m_eventLog.WriteEntry("Starting..."); lock(m_lock) if (m_runner == null) { if (m_verbose_messages) m_eventLog.WriteEntry("Set start time to 30 seconds..."); var sv = new ServiceStatus() { dwCurrentState = ServiceState.SERVICE_START_PENDING, dwWaitHint = (int)TimeSpan.FromSeconds(30).TotalMilliseconds }; SetServiceStatus(this.ServiceHandle, ref sv); if (m_verbose_messages) m_eventLog.WriteEntry("Starting runner..."); m_runner = new Runner( m_cmdargs, () => { if (m_verbose_messages) m_eventLog.WriteEntry("Started!"); var sv2 = new ServiceStatus() { dwCurrentState = ServiceState.SERVICE_RUNNING }; SetServiceStatus(this.ServiceHandle, ref sv2); }, () => { if (m_verbose_messages) m_eventLog.WriteEntry("Stopped!"); var sv2 = new ServiceStatus() { dwCurrentState = ServiceState.SERVICE_STOPPED }; SetServiceStatus(this.ServiceHandle, ref sv2); base.Stop(); }, (msg, important) => { if (important || m_verbose_messages) m_eventLog.WriteEntry(msg); } ); } }
public void StartService() { try { LoadSettings(); Status = ServiceStatus.Started; } catch { Status = ServiceStatus.Error; throw; } }
private ConsoleColor Color(ServiceStatus status) { switch (status) { case ServiceStatus.Pending : return ConsoleColor.DarkYellow; case ServiceStatus.Ok: return ConsoleColor.Green; case ServiceStatus.Fail: return ConsoleColor.Red; default: throw new ArgumentOutOfRangeException(nameof(status), status, null); } }
public static void SetServiceStatus(string name, ServiceStatus status) { switch (status) { case ServiceStatus.Started: Start(name, StatusChangeTimeout); return; case ServiceStatus.Stopped: Stop(name, StatusChangeTimeout); return; } Debug.Assert(false, status.ToString()); }
protected override void OnStop() { // Update the service state to Start Pending. ServiceStatus serviceStatus = new ServiceStatus(); serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING; serviceStatus.dwWaitHint = 100000; SetServiceStatus(this.ServiceHandle, ref serviceStatus); eventLog1.WriteEntry("In onStop."); // Update the service state to Running. serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING; SetServiceStatus(this.ServiceHandle, ref serviceStatus); }
protected override void OnStop() { var serviceStatus = new ServiceStatus(); serviceStatus.dwCurrentState = ServiceState.SERVICE_STOP_PENDING; serviceStatus.dwWaitHint = 10000; SetServiceStatus(this.ServiceHandle, ref serviceStatus); if (server != null) server.Stop(); if (dataServer != null) dataServer.Stop(); // Update the service state to Stopped. serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED; SetServiceStatus(this.ServiceHandle, ref serviceStatus); }
protected override void OnStart(string[] args) { var serviceStatus = new ServiceStatus(); serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING; serviceStatus.dwWaitHint = 10000; SetServiceStatus(this.ServiceHandle, ref serviceStatus); if (server != null) server.Start(); if (dataServer != null) dataServer.Start(); // Update the service state to Running. serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING; SetServiceStatus(this.ServiceHandle, ref serviceStatus); }
public void Start() { Monitor.Enter(this.lockObject); if (this.serviceStatus == ServiceStatus.Stopped) { this.serviceStatus = ServiceStatus.Running; } Monitor.Exit(this.lockObject); while (true) { Thread.Sleep(SendIntervalInMilliseconds); Monitor.Enter(this.lockObject); if (this.serviceStatus == ServiceStatus.Stopped) { Monitor.Exit(this.lockObject); break; } if (this.serviceStatus == ServiceStatus.Paused) { Monitor.Exit(this.lockObject); continue; } Monitor.Exit(this.lockObject); // retrieve data var systemInfo = this.systemInformationProvider.GetSystemInfo(); if (systemInfo == null) { // skip this run continue; } // add message to queue this.workQueue.Enqueue(new SystemInformationQueueItem(systemInfo)); } Monitor.Enter(this.lockObject); this.serviceStatus = ServiceStatus.Stopped; Monitor.Exit(this.lockObject); }
protected override void OnStart(string[] args) { eventLog1.WriteEntry("In OnStart"); System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 60000; // 60 seconds timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer); timer.Start(); // Update the service state to Start Pending. ServiceStatus serviceStatus = new ServiceStatus(); serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING; serviceStatus.dwWaitHint = 100000; SetServiceStatus(this.ServiceHandle, ref serviceStatus); // Update the service state to Running. serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING; SetServiceStatus(this.ServiceHandle, ref serviceStatus); }
private static void HandleEntityPreReleasing(IService sender, ServiceStatus old, ServiceStatus value) { if (sender is IEntity entity) { foreach (IComponent component in entity.Components) { component.TryRelease(); } entity.Components = EntityComponentServiceLoader.EmptyComponentArray; } }
private async Task StartServer(string accessToken, string url, int port) { if (!HttpListener.IsSupported) { _logger.Fatal("Server is not supported, aborting!"); return; } var listenAddress = $"{url}:{port}/"; _logger.Info("Starting server..."); _logger.Info( "Remember to execute `netsh http add urlacl url=\"{listenUrl}\" user=EVERYONE`! (or `user=Все` in russian locale)", listenAddress); var server = new HttpListener(); server.Prefixes.Add($"{listenAddress}mediaApi/"); server.Start(); _logger.Info("Server started on {listenAddress}", listenAddress); var serviceStatus = new ServiceStatus { dwCurrentState = ServiceState.SERVICE_RUNNING, dwWaitHint = 3000 }; SetServiceStatus(ServiceHandle, ref serviceStatus); while (true) { var context = await server.GetContextAsync(); var request = context.Request; var response = context.Response; JObject result; try { result = await ProcessRequest(request, accessToken); } catch (Exception e) when(e is MalformedJsonException || e is SecurityException || e is UnknownMethodException || e is InvalidOperationException) { result = new JObject { ["success"] = false, ["error"] = e.GetType().Name, ["errorDescription"] = e.Message }; } catch (Exception e) { _logger.Error(e, "SHIT! Unexpected exception occured!\nTrace: {trace}", e.ToString()); result = new JObject { ["success"] = false, ["error"] = e.GetType().ToString(), ["errorDescription"] = e.ToString() }; } byte[] responseBuffer = Encoding.UTF8.GetBytes(result.ToString()); response.ContentLength64 = responseBuffer.LongLength; var outStream = response.OutputStream; await outStream.WriteAsync(responseBuffer, 0, responseBuffer.Length); outStream.Close(); outStream.Dispose(); } }
public ServiceStatus GetServiceStatus(DocumentURI uri, string serviceIdentifier) { if (uri != null) { var doc = this.docRepository.GetDocByRegUriIncludeElectronicServiceStages(uri.RegisterIndex, int.Parse(uri.SequenceNumber), uri.ReceiptOrSigningDate.Value); if (doc != null) { ServiceStatus serviceStatus = new ServiceStatus(); serviceStatus.InitiatingDocumentURI = new InitiatingDocumentURI(); serviceStatus.InitiatingDocumentURI.RegisterIndex = uri.RegisterIndex; serviceStatus.InitiatingDocumentURI.SequenceNumber = uri.SequenceNumber; serviceStatus.InitiatingDocumentURI.ReceiptOrSigningDate = uri.ReceiptOrSigningDate; //if (!String.IsNullOrWhiteSpace(doc.DocType.ElectronicServiceFileTypeUri)) //{ // serviceStatus.ServiceURI = new AdministrativeNomenclatureServiceURI(); // serviceStatus.ServiceURI.SUNAUServiceURI = doc.DocType.ElectronicServiceFileTypeUri; //} serviceStatus.ServiceURI = new AdministrativeNomenclatureServiceURI(); serviceStatus.ServiceURI.SUNAUServiceURI = !String.IsNullOrWhiteSpace(doc.DocType.ApplicationName) ? doc.DocType.ApplicationName : doc.DocType.Name; var allStages = this.unitOfWork.DbContext.Set<ElectronicServiceStage>() .Where(e => e.DocTypeId == doc.DocTypeId.Value) .OrderBy(e => e.ElectronicServiceStageId) .ToList(); if (doc.DocElectronicServiceStages.Where(s => s.EndingDate.HasValue).Any()) { serviceStatus.ExecutedTasks = new ExecutedTasks(); serviceStatus.ExecutedTasks.TaskCollection = new TaskCollection(); foreach (var executedStage in doc.DocElectronicServiceStages.Where(s => s.EndingDate.HasValue)) { var stage = allStages.Where(s => s.ElectronicServiceStageId == executedStage.ElectronicServiceStageId).FirstOrDefault(); if (stage != null) { var task = new Task(); task.TaskData = new AISTask(); task.TaskData.NameAndShortDescription = stage.Name; task.TaskData.ExpandedDescription = stage.Description; ; task.TaskData.ScheduledStartDate = executedStage.StartingDate; task.TaskData.ScheduledCompletionDate = executedStage.ExpectedEndingDate; task.TaskData.ActualStartDate = executedStage.StartingDate; task.TaskData.ActualCompletionDate = executedStage.EndingDate; task.TaskData.ExecutedBy = new AISTaskExecutor(); task.TaskData.ExecutedBy.Names = new AISUserNames(); task.TaskData.ExecutedBy.Names.PersonNames = new PersonNames(); task.TaskData.ExecutedBy.Names.PersonNames.First = doc.DocSourceType.Alias == "Internet" && stage.Alias == "AcceptApplication" ? "Системен потребител" : "Служител МОСВ"; serviceStatus.ExecutedTasks.TaskCollection.Add(task); } } } var unexecutedStages = allStages.Where(s => !doc.DocElectronicServiceStages.Where(ds => ds.EndingDate.HasValue).Select(ds => ds.ElectronicServiceStageId).ToList() .Contains(s.ElectronicServiceStageId)); if (unexecutedStages.Any()) { serviceStatus.UnexecutedTasks = new UnexecutedTasks(); serviceStatus.UnexecutedTasks.TaskOrServiceStageCollection = new TaskOrServiceStageCollection(); foreach (var unexecutedStage in unexecutedStages) { if (unexecutedStage.Alias != "DecreeRefusal") { var task = new TaskOrServiceStage(); task.Task = new TaskOrServiceStageTask(); task.Task.TaskData = new AISTask(); task.Task.TaskData.NameAndShortDescription = unexecutedStage.Name; task.Task.TaskData.ExpandedDescription = unexecutedStage.Description; task.Task.TaskData.ScheduledStartDate = null; task.Task.TaskData.ScheduledCompletionDate = null; task.Task.TaskData.ExecutedBy = new AISTaskExecutor(); task.Task.TaskData.ExecutedBy.Names = new AISUserNames(); task.Task.TaskData.ExecutedBy.Names.PersonNames = new PersonNames(); task.Task.TaskData.ExecutedBy.Names.PersonNames.First = "Служител МОСВ"; serviceStatus.UnexecutedTasks.TaskOrServiceStageCollection.Add(task); } } } return serviceStatus; } else { throw new Exception("Document not found."); } } else { throw new ArgumentException(); } }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var termDocs = TermDocuments.GetInstance(); var serviceStatus = ServiceStatus.GetInstance(); var dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <string> norPropertyTypes = new List <string>() { "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, norPropertyTypes, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property and a normal property with string type, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } EntityTypeElement entityType = null; foreach (var ele in entityTypeElements) { if (ele.EntityTypeShortName.IsMediaType()) { continue; } var funcs = new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions, AnnotationsHelper.GetDeleteRestrictions }; var methods = new List <Func <string, string, List <string>, bool?> >() { SupportiveFeatureHelper.IsSupportBatchOperation }; var restrictions = ele.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, funcs, null, NavigationRoughType.None, methods); if (!string.IsNullOrEmpty(restrictions.Item1) || null != restrictions.Item2 || restrictions.Item2.Any() || null != restrictions.Item3 || restrictions.Item3.Any()) { entityType = ele; break; } } if (null == entityType || string.IsNullOrEmpty(entityType.EntitySetName)) { detail.ErrorMessage = "The service does not support batch operation."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { detail.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, false, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); detail.URI = url; detail.ResponsePayload = resp.ResponsePayload; detail.ResponseHeaders = resp.ResponseHeaders; detail.HTTPMethod = "POST"; if (null != resp && HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; bool hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.GetEntity(entityId); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { JObject entity = JObject.Parse(resp.ResponsePayload); List <string> norPropertyNames = entityType.NormalProperties.Where(norProp => norPropertyTypes.Contains(norProp.PropertyType)).Select(norProp => norProp.PropertyName).ToList(); reqDataStr = dFactory.ConstructUpdatedEntityData(entity, norPropertyNames).ToString(); string boundary = "batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f"; string batchReqData = string.Format( @" --batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f Content-Type: multipart/mixed; boundary=changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621 --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621 Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 1 PATCH {0} HTTP/1.1 Content-Type: application/json " + (hasEtag ? "If-Match: *" : string.Empty) + @" {1} --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621 Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 2 PATCH {0} HTTP/1.1 Content-Type: application/json " + (hasEtag ? "If-Match: *" : string.Empty) + @" {1} --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621-- --batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f Content-Type: application/http Content-Transfer-Encoding: binary GET {0} HTTP/1.1 --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621-- --batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f-- ", entityId, reqDataStr); string strurl = serviceStatus.RootURL.TrimEnd('/'); resp = WebHelper.BatchOperation(strurl, batchReqData, boundary); detail = new ExtensionRuleResultDetail(this.Name, strurl + "/$batch", HttpMethod.Post, string.Empty, resp, string.Empty, batchReqData); if (HttpStatusCode.OK == resp.StatusCode) { string expectedRespData = @"Content-ID: 1 HTTP/1.1 204 No Content Content-ID: 2 HTTP/1.1 204 No Content HTTP/1.1 200 OK "; if (expectedRespData == resp.ResponsePayload.Filtration(new List <string>() { "\nContent-ID:", "\nHTTP/1.1 " })) { passed = true; } else { passed = false; detail.ErrorMessage = "The requests in batch are not processed by order received."; } } else { passed = false; detail.ErrorMessage = "The OData service does not return a 200 OK HTTP status code."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } } else { passed = false; detail.ErrorMessage = string.Format("Created entity failed for above URI with entity data {0}. Server Response: {1}", reqDataStr, resp.StatusCode); } var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(this.ErrorMessage, new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
public static void CategoriesUpdated() { if (CurrentStatus == null) CurrentStatus = new ServiceStatus(); CurrentStatus.CategoriesLastUpdated = DateTime.Now; }
/// <summary> /// Do any cleanup needed before terminating the service /// </summary> public virtual void StopService() { Status = ServiceStatus.Stopped; }
protected override void HandleEntityInitializing(IService sender, ServiceStatus old, ServiceStatus value) { this.Entity.Messages.Add(Guppy.Network.Constants.Messages.Channel.CreateNetworkEntity, Guppy.Network.Constants.MessageContexts.InternalReliableDefault); this.Entity.Messages.Add(Guppy.Network.Constants.Messages.Channel.UpdateNetworkEntity, Guppy.Network.Constants.MessageContexts.InternalReliableDefault); this.Entity.Messages.Add(Guppy.Network.Constants.Messages.Channel.PingNetworkEntity, Guppy.Network.Constants.MessageContexts.InternalUnreliableDefault); this.Entity.Messages.Add(Guppy.Network.Constants.Messages.Channel.DeleteNetworkEntity, Guppy.Network.Constants.MessageContexts.InternalReliableDefault); }
protected static string GetServiceStatusDescription(ServiceStatus status) { return(MonitoringResource.ResourceManager.GetString("ServiceStatus" + status) ?? status.ToString()); }
internal void OnServiceChanged(string msg, ServiceStatus state) { SetSIPService(msg, state); }
public override ServiceState setServiceState(ServiceStatus setTo) { throw new NotImplementedException(); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); var detail3 = new ExtensionRuleResultDetail(this.Name); var detail4 = new ExtensionRuleResultDetail(this.Name); var detail5 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.CollectionValued).ToList(); if (entityTypeElements == null || entityTypeElements.Count == 0) { detail1.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } foreach (var et in entityTypeElements) { string navigPropName = null; string navigPropRelatedEntitySetUrl = null; string navigPropRelatedEntityTypeKeyName = null; NavigationRoughType navigPropRoughType = NavigationRoughType.None; var matchEntity = et.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetDeleteRestrictions, AnnotationsHelper.GetInsertRestrictions }); if (string.IsNullOrEmpty(matchEntity.Item1) || matchEntity.Item2 == null || !matchEntity.Item2.Any() || matchEntity.Item3 == null || !matchEntity.Item3.Any()) { continue; } foreach (var np in matchEntity.Item3) { navigPropName = np.NavigationPropertyName; string navigEntityTypeShortName = np.NavigationPropertyType.RemoveCollectionFlag().GetLastSegment(); List <NormalProperty> navigKeyProps = MetadataHelper.GetKeyProperties(serviceStatus.MetadataDocument, navigEntityTypeShortName).ToList(); if (navigKeyProps.Count == 1 && keyPropertyTypes.Contains(navigKeyProps[0].PropertyType)) { navigPropRelatedEntitySetUrl = navigEntityTypeShortName.MapEntityTypeShortNameToEntitySetURL(); navigPropRelatedEntityTypeKeyName = navigKeyProps[0].PropertyName; navigPropRoughType = np.NavigationRoughType; break; } } if (!string.IsNullOrEmpty(navigPropRelatedEntityTypeKeyName) && !string.IsNullOrEmpty(navigPropRelatedEntitySetUrl)) { string entitySetUrl = et.EntitySetName.MapEntitySetNameToEntitySetURL(); string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var resp = WebHelper.Get(new Uri(url), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.AcceptHeaderJson, serviceStatus.DefaultHeaders), resp); detail1.URI = url; detail1.ResponsePayload = resp.ResponsePayload; detail1.ResponseHeaders = resp.ResponseHeaders; detail1.HTTPMethod = "GET"; detail1.ResponseStatusCode = resp.StatusCode.ToString(); if (resp.StatusCode == HttpStatusCode.OK) { JObject feed; resp.ResponsePayload.TryToJObject(out feed); var entries = JsonParserHelper.GetEntries(feed); DataFactory factory = DataFactory.Instance(); var additionalInfos = new List <AdditionalInfo>(); var reqData = factory.ConstructInsertedEntityData(et.EntitySetName, et.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); resp = WebHelper.CreateEntity(url, reqDataStr); detail2 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; url = serviceStatus.RootURL.TrimEnd('/') + @"/" + navigPropRelatedEntitySetUrl; resp = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders); detail3 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.V4AcceptHeaderJsonFullMetadata, serviceStatus.DefaultHeaders), resp); detail3.URI = url; detail3.ResponsePayload = resp.ResponsePayload; detail3.ResponseHeaders = resp.ResponseHeaders; detail3.HTTPMethod = "GET"; detail3.ResponseStatusCode = resp.StatusCode.ToString(); if (resp.StatusCode == HttpStatusCode.OK) { resp.ResponsePayload.TryToJObject(out feed); var entities = JsonParserHelper.GetEntries(feed); if (null != entities && entities.Any()) { string odataID = entities.First[Constants.V4OdataId] != null ? entities.First[Constants.V4OdataId].Value <string>() : string.Empty; reqDataStr = @"{""" + Constants.V4OdataId + @""" : """ + odataID + @"""}"; url = string.Format("{0}/{1}/$ref", entityId.TrimEnd('/'), navigPropName.TrimEnd('/')); resp = WebHelper.CreateEntity(url, reqDataStr); detail4 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (resp.StatusCode == HttpStatusCode.NoContent) { string deleteUrl = url; if (navigPropRoughType == NavigationRoughType.CollectionValued) { deleteUrl = string.Format("{0}/{1}/$entity?$id={2}", entityId.TrimEnd('/'), navigPropName.TrimEnd('/'), entities[0][Constants.V4OdataId].ToString()); } resp = WebHelper.DeleteEntity(deleteUrl); detail5 = new ExtensionRuleResultDetail(this.Name, deleteUrl, HttpMethod.Delete, string.Empty, resp); if (null != resp && HttpStatusCode.NoContent == resp.StatusCode) { passed = true; } else { passed = false; detail5.ErrorMessage = "Delete the above reference failed."; } } else { passed = false; detail4.ErrorMessage = "Created navigation failed."; } } } else { passed = false; detail3.ErrorMessage = "Can not get the created entity from above URI."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { passed = false; detail2.ErrorMessage = "Created the new entity failed for above URI."; } break; } } } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4, detail5 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
/// <summary> /// Verifies the service implementation feature. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if the service implementation feature passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var svcStatus = ServiceStatus.GetInstance(); string entityTypeShortName; var propNames = MetadataHelper.GetPropertyNames("Edm.String", out entityTypeShortName); if (null == propNames || !propNames.Any()) { return(passed); } string propName = propNames[0]; var entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL(); string url = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl; var resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { JObject jObj = JObject.Parse(resp.ResponsePayload); JArray jArr = jObj.GetValue(Constants.Value) as JArray; var entity = jArr.First as JObject; var propVal = entity[propName].ToString(); string subStr = propVal.Substring(propVal.Length / 2); url = string.Format("{0}?$filter=endswith({1}, '{2}')", url, propName, subStr); resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty); detail.URI = url; detail.ResponsePayload = resp.ResponsePayload; detail.ResponseHeaders = resp.ResponseHeaders; detail.HTTPMethod = "GET"; detail.ResponseStatusCode = resp.StatusCode.ToString(); info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { jObj = JObject.Parse(resp.ResponsePayload); jArr = jObj.GetValue(Constants.Value) as JArray; foreach (JObject et in jArr) { passed = et[propName].ToString().EndsWith(subStr); if (passed == false) { detail.ErrorMessage = et[propName].ToString() + " does not end with " + subStr; break; } } } else { detail.ErrorMessage = "The server returned an error response: " + detail.ResponseStatusCode; passed = false; } } return(passed); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } EntityTypeElement eTypeElement = new EntityTypeElement(); Dictionary <string, string> entityAndpaths = MetadataHelper.StreamPropertyEntities(serviceStatus.MetadataDocument); string relativePath = string.Empty; foreach (var en in entityTypeElements) { if (entityAndpaths.Keys.Contains(en.EntityTypeShortName) && string.IsNullOrEmpty(en.EntitySetName)) { eTypeElement = en; relativePath = entityAndpaths[en.EntityTypeShortName]; break; } } if (eTypeElement.EntityTypeShortName == null) { detail.ErrorMessage = "Cannot find the appropriate entity-set to verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + eTypeElement.EntitySetName; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(eTypeElement.EntitySetName, eTypeElement.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode || HttpStatusCode.NoContent == resp.StatusCode) { url = additionalInfos.Last().EntityId.TrimEnd('/') + "/" + relativePath.TrimEnd('/'); if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { detail.ErrorMessage = string.Format("Fail to find the stream property read and edit URL.", resp.StatusCode); // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); return(passed); } resp = WebHelper.Get(new Uri(url), null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, null); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.V4AcceptHeaderJsonFullMetadata, serviceStatus.DefaultHeaders), resp); if ((resp.StatusCode.HasValue && HttpStatusCode.OK == resp.StatusCode) || HttpStatusCode.NoContent == resp.StatusCode) { resp = WebHelper.UpdateMediaTypeEntity(url, context.RequestHeaders, additionalInfos.Last().HasEtag); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Put, string.Empty, resp, string.Empty, "Successfully updated the stream of the image."); if (null != resp && (HttpStatusCode.NoContent == resp.StatusCode || resp.StatusCode == HttpStatusCode.OK)) { passed = true; } else { passed = false; detail.ErrorMessage = string.Format("HTTP PUT to update the stream property failed with the error {0}.", resp.StatusCode); } } else { detail.ErrorMessage = "Get stream property failed from above URI."; } // Restore the service. WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { detail.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(new Uri(url), serviceStatus.ServiceDocument, details); return(passed); }
public void StopService() { // TODO: Add DomainManager.UnloadService implementation Status = ServiceStatus.Stopped; }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty); string updateUrl = serviceStatus.RootURL; List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <string> norPropertyTypes = new List <string>() { "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.CollectionValued).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property and a string type normal property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } EntityTypeElement entityType = null; List <string> navigationPropNames = new List <string>(); foreach (var en in entityTypeElements) { if (MetadataHelper.HasEntityNavigationProp(serviceStatus.MetadataDocument, en.EntityTypeShortName, NavigationRoughType.CollectionValued, context, out navigationPropNames)) { entityType = en; break; } } if (navigationPropNames != null && !navigationPropNames.Any()) { detail.ErrorMessage = "To verify this rule it is expected that an entity type has collection-valued navigation type property, but there is no such entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string navigationPropName = navigationPropNames.First(); string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); updateUrl = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; if (string.IsNullOrEmpty(entitySetUrl)) { detail.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfosAll = new List <AdditionalInfo>(); var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); additionalInfosAll = additionalInfos; string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; string nPropUrl = entityId.TrimEnd('/') + "/" + navigationPropName; updateUrl = entityId.TrimEnd('/') + "/" + navigationPropName + "/$ref"; bool hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.GetEntity(updateUrl); detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Get, string.Empty, resp); if (HttpStatusCode.OK == resp.StatusCode) { string navigPropType = MetadataHelper.GetNavigPropertyTypeFromMetadata(navigationPropName, entityType.EntityTypeShortName, serviceStatus.MetadataDocument); string navigPropTypeShortName = navigPropType.Substring(navigPropType.IndexOf("(")).GetLastSegment().TrimEnd(')'); string nEntitySetName = navigationPropName.MapNavigationPropertyNameToEntitySetName(entityType.EntityTypeShortName); string nEntitySetUrl = nEntitySetName.MapEntitySetNameToEntitySetURL(); nEntitySetUrl = serviceStatus.RootURL.TrimEnd('/') + @"/" + nEntitySetUrl; reqData = dFactory.ConstructInsertedEntityData(nEntitySetName, navigPropTypeShortName, null, out additionalInfos); foreach (AdditionalInfo a in additionalInfos) { additionalInfosAll.Add(a); } reqDataStr = reqData.ToString(); isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); resp = WebHelper.CreateEntity(nEntitySetUrl, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, nEntitySetUrl, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { string refEntityId = additionalInfos.Last().EntityId; resp = WebHelper.GetEntity(refEntityId); detail = new ExtensionRuleResultDetail(this.Name, refEntityId, HttpMethod.Get, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.OK == resp.StatusCode) { string refEntitySetNameWithEnityID = refEntityId.Split('/').Last(); string refEntityValue = serviceStatus.RootURL.TrimEnd('/') + @"/" + refEntitySetNameWithEnityID; string refEntityID = refEntitySetNameWithEnityID.Contains("'") ? refEntitySetNameWithEnityID.Split('\'')[1] : refEntitySetNameWithEnityID.Split('(')[1].TrimEnd(')'); JObject navigationRefSet = new JObject(); navigationRefSet.Add(Constants.V4OdataId, refEntityValue); resp = WebHelper.CreateEntity(updateUrl, context.RequestHeaders, navigationRefSet, isMediaType, ref additionalInfosAll); detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Patch, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.NoContent == resp.StatusCode) { resp = WebHelper.GetEntity(updateUrl); detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Get, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.OK == resp.StatusCode) { JObject refEntitySet; resp.ResponsePayload.TryToJObject(out refEntitySet); bool created = false; var entries = JsonParserHelper.GetEntries(refEntitySet); if (entries != null) { foreach (JObject entry in entries) { foreach (JProperty prop in entry.Children()) { if (prop.Name.Equals(Constants.V4OdataId)) { created = prop.Value.ToString().Contains(refEntityID); if (created) { passed = true; break; } } } } if (!created) { passed = false; detail.ErrorMessage = string.Format("The HTTP Post to add a reference to a collection-valued navigation property failed."); } } } else { passed = false; detail.ErrorMessage = "HTTP Get to the navigation property reference failed."; } } else { passed = false; detail.ErrorMessage = "HTTP Post to add the navigation property reference failed."; } } else { detail.ErrorMessage = "Can not get the created navigation entity set entity."; } } else { detail.ErrorMessage = "Creating navigation entity failes from above URI."; } } else { detail.ErrorMessage = "Can not get the created entity's navigation property reference collection set from above URI."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfosAll); } else { detail.ErrorMessage = "Creating the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(new Uri(updateUrl), serviceStatus.ServiceDocument, details); return(passed); }
protected override void HandleEntityReleasing(IService sender, ServiceStatus old, ServiceStatus value) { this.Entity.Messages.Remove(Guppy.Network.Constants.Messages.Channel.CreateNetworkEntity); this.Entity.Messages.Remove(Guppy.Network.Constants.Messages.Channel.UpdateNetworkEntity); this.Entity.Messages.Remove(Guppy.Network.Constants.Messages.Channel.PingNetworkEntity); this.Entity.Messages.Remove(Guppy.Network.Constants.Messages.Channel.DeleteNetworkEntity); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty); string deleteUrl = serviceStatus.RootURL; List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } EntityTypeElement eTypeElement = null; foreach (var en in entityTypeElements) { if (MetadataHelper.IsMediaEntity(serviceStatus.MetadataDocument, en.EntityTypeShortName, context)) { eTypeElement = en; break; } } if (null == eTypeElement) { detail.ErrorMessage = "To verify this rule it expects an entity type with deleteable and insertable restrictions, but there is no entity type in metadata which is insertable and deleteable."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string entitySetUrl = eTypeElement.EntitySetName.MapEntitySetNameToEntitySetURL(); deleteUrl = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; if (string.IsNullOrEmpty(entitySetUrl)) { detail.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", eTypeElement.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(eTypeElement.EntitySetName, eTypeElement.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, true, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode || HttpStatusCode.NoContent == resp.StatusCode) { var entityId = additionalInfos.Last().EntityId; deleteUrl = entityId; var hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.DeleteEntity(entityId, context.RequestHeaders, hasEtag); detail = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Delete, string.Empty, resp); detail.URI = entityId; detail.ResponsePayload = resp.ResponsePayload; detail.ResponseHeaders = resp.ResponseHeaders; detail.HTTPMethod = "GET"; detail.ResponseStatusCode = resp.StatusCode.ToString(); if (HttpStatusCode.NoContent == resp.StatusCode) { resp = WebHelper.GetEntity(entityId); detail = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp); if (HttpStatusCode.NotFound == resp.StatusCode) { additionalInfos.Remove(additionalInfos.Last()); passed = true; } else { passed = false; detail.ErrorMessage = string.Format("Delete media entity failed because it still can get the entity {0}.", entityId); } } else { passed = false; detail.ErrorMessage = string.Format("Delete the created media entity failed."); } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { detail.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(new Uri(deleteUrl), serviceStatus.ServiceDocument, details); return(passed); }
/// <summary> /// 设置sip服务状态 /// </summary> /// <param name="state">sip状态</param> private void SetSIPService(string msg, ServiceStatus state) { logger.Debug("SIP Service Status: " + msg + "," + state); }
/// <summary> /// Initialize the Service /// </summary> public virtual void StartService() { Status = ServiceStatus.Started; }
internal StatusChangedEventArgs(ServiceStatus status) { this.Status = status; }
public void StartService() { try { // TestAgency requires on the RuntimeFrameworkService. _runtimeService = ServiceContext.GetService<IRuntimeFrameworkService>(); // Any object returned from ServiceContext is an IService if (_runtimeService != null && ((IService)_runtimeService).Status == ServiceStatus.Started) { try { Start(); Status = ServiceStatus.Started; } catch { Status = ServiceStatus.Error; throw; } } else { Status = ServiceStatus.Error; } } catch { Status = ServiceStatus.Error; throw; } }
/// <summary> /// Default constructor /// </summary> /// <param name="serviceStatus"></param> /// <param name="errorMessage"></param> public ServiceResponse(ServiceStatus serviceStatus, string errorMessage) { ServiceStatus = serviceStatus; ErrorMessage = errorMessage; }
private void HandleServiceHostFault(object sender, ServiceHostFaultEventArgs e) { var handlerList = this.ServiceManager.UnhandledExceptionHandlerList; foreach (var handler in handlerList) { try { if (!handler.Handle(e.Exception, e.ChannelDispatcher, this)) { lock (this.statusSyncRoot) { this.status = ServiceStatus.Faulted; } } } catch (Exception ex) { _logger.LogError( string.Format("Exception handler {0}, raise exception", handler.GetType().FullName), ex); } } }
public AddTransactionCommandResponse(ServiceStatus serviceStatus, string errorMessage) : base(serviceStatus, errorMessage) { ServiceStatus = serviceStatus; ErrorMessage = errorMessage; }
protected static string GetServiceStatusDescription(ServiceStatus status) { return MonitoringResource.ResourceManager.GetString("ServiceStatus" + status) ?? status.ToString(); }
internal BlockServerInfo(long guid, IServiceAddress address, ServiceStatus status) { this.guid = guid; this.address = address; this.status = status; }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var serviceStatus = ServiceStatus.GetInstance(); string feedUrl = string.Empty; string entityUrl = string.Empty; KeyValuePair <string, IEnumerable <string> > entityUrls; if (JsonParserHelper.GetBatchSupportedEntityUrls(out entityUrls)) { feedUrl = string.Format("{0}/{1}", context.ServiceBaseUri.OriginalString.TrimEnd('/'), entityUrls.Key); entityUrl = entityUrls.Value.First(); } else { var detail2 = new ExtensionRuleResultDetail(this.Name, context.ServiceBaseUri.OriginalString + "/$batch", HttpMethod.Post, string.Empty, string.Empty, string.Empty, string.Empty); passed = false; detail2.ErrorMessage = string.Format("This server does have any entities that support batch request"); info = new ExtensionRuleViolationInfo(detail2.ErrorMessage, context.ServiceBaseUri, detail2.ErrorMessage); return(passed); } string relativeUrl = string.Empty; try { relativeUrl = new Uri(entityUrl).LocalPath; } catch { passed = false; var detail33 = new ExtensionRuleResultDetail(this.Name, context.ServiceBaseUri.OriginalString.TrimEnd('/') + "/$batch", HttpMethod.Post, string.Empty, string.Empty, string.Empty, string.Empty); detail33.ErrorMessage = "The entity URL is not valid: " + entityUrl; info = new ExtensionRuleViolationInfo(detail33.ErrorMessage, context.ServiceBaseUri, detail33.ErrorMessage); return(passed); } string host = entityUrl.Remove(entityUrl.IndexOf(relativeUrl)); string batchRequest = string.Format(@" --batch_36522ad7-fc75-4b56-8c71-56071383e77b Content-Type: application/http Content-Transfer-Encoding:binary GET {0} HTTP/1.1 --batch_36522ad7-fc75-4b56-8c71-56071383e77b Content-Type: application/http Content-Transfer-Encoding:binary GET {0} HTTP/1.1 --batch_36522ad7-fc75-4b56-8c71-56071383e77b--", entityUrl); string boundary = @"batch_36522ad7-fc75-4b56-8c71-56071383e77b"; List <string> batchResponseSigns = new List <string>(); Response batchResponse = WebHelper.BatchOperation(context.ServiceBaseUri.OriginalString, batchRequest, boundary); var detail = new ExtensionRuleResultDetail(this.Name, context.ServiceBaseUri.OriginalString + "/$batch", HttpMethod.Post, string.Empty, batchResponse, string.Empty, batchRequest); detail.URI = context.ServiceBaseUri.OriginalString + "/$batch"; detail.ResponsePayload = batchResponse.ResponsePayload; detail.ResponseHeaders = batchResponse.ResponseHeaders; detail.HTTPMethod = "POST"; detail.ResponseStatusCode = batchResponse.StatusCode.ToString(); if (batchResponse != null && !string.IsNullOrEmpty(batchResponse.ResponsePayload)) { string[] responseSegments = batchResponse.ResponsePayload.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string seg in responseSegments) { if (seg.StartsWith(@"--batchresponse")) { batchResponseSigns.Add(seg); } } // The request has 3 batch separators if (batchResponseSigns.Count == 3) { passed = true; } else { passed = false; detail.ErrorMessage = string.Format("The batch response body does not match one-to-one with the batch request body, the batch request has 3 batch separators, but response has {0} batch separators. ", batchResponseSigns.Count); } } else { passed = false; detail.ErrorMessage = string.Format("Batch request failed: {0}.", batchRequest); } info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail); return(passed); }
public void StopService() { try { Stop(); } finally { Status = ServiceStatus.Stopped; } }
/// <summary> /// Verifies the service implementation feature. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if the service implementation feature passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var svcStatus = ServiceStatus.GetInstance(); string entityTypeShortName; var propNames = MetadataHelper.GetPropertyNames("Edm.String", out entityTypeShortName); if (null == propNames || !propNames.Any()) { return(passed); } string propName = propNames[0]; var entitySetUrl = entityTypeShortName.GetAccessEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { return(passed); } string url = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl; var resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { JObject jObj = JObject.Parse(resp.ResponsePayload); JArray jArr = jObj.GetValue("value") as JArray; var entity = jArr.First as JObject; var propVal = entity[propName].ToString(); url = string.Format("{0}?$search={1}", url, propVal); resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); var detail = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionSearch", url, HttpMethod.Get, string.Empty); info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { jObj = JObject.Parse(resp.ResponsePayload); jArr = jObj.GetValue("value") as JArray; if (null == jArr || !jArr.Any()) { return(false); } entity = jArr.First as JObject; passed = propVal == entity[propName].ToString(); } else { passed = false; } } else { return(passed); } return(passed); }
public void Stop() { if (this.ServiceHost == null || this.status == ServiceStatus.Closing) { return; } lock (this.statusSyncRoot) { if (this.status != ServiceStatus.Opened) { throw new InvalidOperationException("Stop can be called only when the current status is Opened"); } this.status = ServiceStatus.Closing; } ServiceStatus resultStatus = ServiceStatus.Closed; try { this.ServiceHost.Close(); this.ServiceHost = null; } catch (Exception ex) { resultStatus = ServiceStatus.Faulted; _logger.LogInfo(string.Format("{0} Service Stop error", this.ServiceName), ex); } finally { this.status = resultStatus; } }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var serviceStatus = ServiceStatus.GetInstance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); var detail3 = new ExtensionRuleResultDetail(this.Name); var detail4 = new ExtensionRuleResultDetail(this.Name); string feedUrl = string.Empty; string entityUrl = string.Empty; KeyValuePair <string, IEnumerable <string> > entityUrls; try { if (JsonParserHelper.GetBatchSupportedEntityUrls(out entityUrls)) { feedUrl = string.Format("{0}/{1}", serviceStatus.RootURL.TrimEnd('/'), entityUrls.Key); entityUrl = entityUrls.Value.First(); } } catch (Exception ex) { passed = false; detail4.ErrorMessage = ex.Message + " Your service document should identify the EntitySet like this: {\"name\":\"Property\",\"url\":\"Property\",\"kind\":\"EntitySet\"}"; List <ExtensionRuleResultDetail> details2 = new List <ExtensionRuleResultDetail>() { detail4 }; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details2); return(passed); } string relativeUrl = new Uri(entityUrl).LocalPath; string host = entityUrl.Remove(entityUrl.IndexOf(relativeUrl)); string format1Request = string.Format(@" --batch_36522ad7-fc75-4b56-8c71-56071383e77b Content-Type: application/http Content-Transfer-Encoding:binary GET {0} HTTP/1.1 --batch_36522ad7-fc75-4b56-8c71-56071383e77b--", entityUrl); string format2Request = string.Format(@" --batch_36522ad7-fc75-4b56-8c71-56071383e77b Content-Type: application/http Content-Transfer-Encoding:binary GET {0} HTTP/1.1 Host: {1} --batch_36522ad7-fc75-4b56-8c71-56071383e77b--", relativeUrl, host); string format3Reuqest = string.Format(@" --batch_36522ad7-fc75-4b56-8c71-56071383e77b Content-Type: application/http Content-Transfer-Encoding:binary GET {0} HTTP/1.1 --batch_36522ad7-fc75-4b56-8c71-56071383e77b--", relativeUrl); string boundary = @"batch_36522ad7-fc75-4b56-8c71-56071383e77b"; Response format1Response = WebHelper.BatchOperation(serviceStatus.RootURL.TrimEnd('/') + @"/", format1Request, boundary); detail1 = new ExtensionRuleResultDetail(this.Name, feedUrl.TrimEnd('/') + "/$batch", HttpMethod.Post, string.Empty, format1Response, string.Empty, format1Request); Response format2Response = WebHelper.BatchOperation(serviceStatus.RootURL.TrimEnd('/') + @"/", format2Request, boundary); detail2 = new ExtensionRuleResultDetail(this.Name, feedUrl.TrimEnd('/') + "/$batch", HttpMethod.Post, string.Empty, format2Response, string.Empty, format2Request); Response format3Response = WebHelper.BatchOperation(serviceStatus.RootURL.TrimEnd('/') + @"/", format3Reuqest, boundary); detail3 = new ExtensionRuleResultDetail(this.Name, feedUrl.TrimEnd('/') + "/$batch", HttpMethod.Post, string.Empty, format3Response, string.Empty, format3Reuqest); if (format1Response != null && !string.IsNullOrEmpty(format1Response.ResponsePayload)) { if (!format1Response.ResponsePayload.Contains(@"HTTP/1.1 200 OK")) { passed = false; detail1.ErrorMessage = string.Format("Batch request failed by above URI."); } } else { passed = false; detail1.ErrorMessage = "No response returned from above URI."; } if (format2Response != null && !string.IsNullOrEmpty(format2Response.ResponsePayload)) { if (!format2Response.ResponsePayload.Contains(@"HTTP/1.1 200 OK")) { passed = false; detail2.ErrorMessage = string.Format("Batch request failed by above URI and host : {0}. ", host); } } else { passed = false; detail2.ErrorMessage = string.Format("No response returned from above URI and host : {0}. ", host); } if (format3Response != null && !string.IsNullOrEmpty(format3Response.ResponsePayload)) { if (!format3Response.ResponsePayload.Contains(@"HTTP/1.1 200 OK")) { passed = false; detail3.ErrorMessage = string.Format("Batch request failed by above URI and Batch request host : {0}.", host); } } else { passed = false; detail3.ErrorMessage = string.Format("No response returned from above URI and Batch request host : {0}. ", host); } if (passed == null) { passed = true; } List <ExtensionRuleResultDetail> details = new List <ExtensionRuleResultDetail>() { detail1, detail2, detail3 }; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
private void Open(bool isRestart) { if (!isRestart) { lock (this.statusSyncRoot) { if (this.status == ServiceStatus.Opening) { return; } else if (this.status != ServiceStatus.Created) { throw new InvalidOperationException("Open can be called only when the current status is Created"); } this.status = ServiceStatus.Opening; } } ServiceStatus resultStatus = ServiceStatus.Opened; try { var oldServiceHost = this.ServiceHost; this.ServiceHost = this.createServiceHost(); this.ServiceName = this.ServiceHost.Description.Name; this.AttachServiceHostEventHandler(this.ServiceHost); if (this.ServiceHostCreated != null) { this.ServiceHostCreated(this); } if (oldServiceHost != null) { try { oldServiceHost.Close(); } catch { } } this.ServiceHost.Open(); this.StartedTime = DateTime.Now; } catch (Exception ex) { resultStatus = ServiceStatus.Faulted; _logger.LogError(string.Format("Cannot start WCF Service: {0}", this.ServiceName), ex); } finally { lock (this.statusSyncRoot) { this.status = resultStatus; } } }
/// <summary> /// Pauses this instance. This is different from Stopping, as queued jobs stay in memory, they just won't be executed. /// </summary> /// <returns></returns> public bool Pause() { serviceStatus = ServiceStatus.Paused; pollTimer.Stop(); return(true); }
private static ServiceStatus DependencyStatusToServiceStatus(ServiceStatus dependencyStatus, bool isUnion) { if (dependencyStatus == ServiceStatus.Error) return ServiceStatus.DependencyError; if (dependencyStatus == ServiceStatus.NotResolved && isUnion) return ServiceStatus.Ok; return dependencyStatus; }
private static extern bool SetServiceStatus(System.IntPtr handle, ref ServiceStatus serviceStatus);
internal RootServerInfo(IServiceAddress address, ServiceStatus status) { this.address = address; this.status = status; }
/// <summary> /// Verifies the service implementation feature. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if the service implementation feature passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var svcStatus = ServiceStatus.GetInstance(); string entityTypeShortName; var props = MetadataHelper.GetProperties("Edm.GeographyPoint", 1, out entityTypeShortName); if (null == props || !props.Any()) { return(passed); } string propName = props[0].PropertyName; string srid = props[0].SRID; var entitySetUrl = entityTypeShortName.GetAccessEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { return(passed); } string url = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl; var resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { JObject jObj = JObject.Parse(resp.ResponsePayload); JArray jArr = jObj.GetValue(Constants.Value) as JArray; var entity = jArr.First as JObject; var propVal = entity[propName]["coordinates"] as JArray; var pt1 = new Point(Convert.ToDouble(propVal[0]), Convert.ToDouble(propVal[1])); var pt2 = new Point(0.0, 0.0); var distance = Point.GetDistance(pt1, pt2); url = string.Format("{0}?$filter=geo.distance({1}, SRID={2};POINT(0.0 0.0)) eq {3}", url, propName, srid, distance); resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty); info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { jObj = JObject.Parse(resp.ResponsePayload); jArr = jObj.GetValue(Constants.Value) as JArray; foreach (JObject et in jArr) { propVal = et[propName]["coordinates"] as JArray; pt1 = new Point(Convert.ToDouble(propVal[0]), Convert.ToDouble(propVal[1])); pt2 = new Point(0.0, 0.0); var dis = Point.GetDistance(pt1, pt2); passed = dis == distance; } } else { passed = false; } } return(passed); }
public static void VideosUpdated() { if (CurrentStatus == null) CurrentStatus = new ServiceStatus(); CurrentStatus.VideosLastUpdated = DateTime.Now; }
public static extern bool ControlService(IntPtr hService, ServiceControl dwControl, ref ServiceStatus lpServiceStatus);
/// <summary> /// Verifies the service implementation feature. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if the service implementation feature passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; var entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.CollectionValued); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string entitySet = string.Empty; EntityTypeElement entityType = new EntityTypeElement(); foreach (var en in entityTypeElements) { entitySet = en.EntitySetName; var funcs = new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetDeleteRestrictions }; var restrictions = entitySet.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, funcs, null, NavigationRoughType.None); if (!string.IsNullOrEmpty(restrictions.Item1) && null != restrictions.Item2 && restrictions.Item2.Any() && null != restrictions.Item3 && restrictions.Item3.Any()) { entityType = en; break; } } if (string.IsNullOrEmpty(entitySet)) { detail.ErrorMessage = "Cannot find an entity-set URL which can be execute the deep insert operation on it."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string entitySetUrl = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySet; string rootUrl = serviceStatus.RootURL.TrimEnd('/') + @"/"; string url = entitySetUrl; Response resp = null; bool gotDeltaLink = false; string deltaLink = string.Empty; while (!gotDeltaLink) { resp = WebHelper.GetDeltaLink(url, context.RequestHeaders); JObject payload; if (resp.StatusCode == HttpStatusCode.OK) { bool hasNextOrDelta = false; resp.ResponsePayload.TryToJObject(out payload); foreach (JProperty child in payload.Children <JProperty>()) { if (child.Name.Equals(Constants.V4OdataDeltaLink)) { gotDeltaLink = true; hasNextOrDelta = true; deltaLink = child.Value.ToString(); if (Uri.IsWellFormedUriString(deltaLink, UriKind.Relative)) { deltaLink = rootUrl + deltaLink; } break; } if (child.Name.Equals(Constants.V4OdataNextLink)) { url = child.Value.ToString(); hasNextOrDelta = true; if (Uri.IsWellFormedUriString(url, UriKind.Relative)) { url = rootUrl + deltaLink; } break; } } if (!hasNextOrDelta) { break; } } } if (!gotDeltaLink) { detail.ErrorMessage = "The service does not support delta tracking."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); passed = false; return(passed); } bool isCreated = false; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); resp = WebHelper.CreateEntity(entitySetUrl, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, entitySetUrl, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { var entityId = additionalInfos.Last().EntityId; resp = WebHelper.GetEntity(entityId); detail = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.OK == resp.StatusCode) { isCreated = true; } } resp = WebHelper.GetEntity(deltaLink); if ((isCreated && resp.StatusCode == HttpStatusCode.OK) || resp.StatusCode == HttpStatusCode.NoContent) { passed = true; detail = new ExtensionRuleResultDetail(this.Name, deltaLink, HttpMethod.Get, string.Empty, resp, string.Empty, null); } else { passed = false; detail = new ExtensionRuleResultDetail(this.Name, deltaLink, HttpMethod.Get, string.Empty, resp, string.Empty, null); detail.ErrorMessage = "Cannot get delta changes from the delta link."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(new Uri(url), serviceStatus.ServiceDocument, details); return(passed); }
/// <summary> /// Verifies the service implementation feature. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if the service implementation feature passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var svcStatus = ServiceStatus.GetInstance(); string entityTypeShortName; var propTypes = new string[1] { "Edm.DateTimeOffset" }; var propNames = MetadataHelper.GetPropertyNames(propTypes, out entityTypeShortName); if (null == propNames || !propNames.Any()) { return(passed); } string propName = propNames[0]; var entitySetUrl = entityTypeShortName.GetAccessEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { return(passed); } string url = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl; var resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { var settings = new JsonSerializerSettings(); settings.DateParseHandling = DateParseHandling.None; JObject jObj = JsonConvert.DeserializeObject(resp.ResponsePayload, settings) as JObject; JArray jArr = jObj.GetValue(Constants.Value) as JArray; var entity = jArr.First as JObject; string propVal = string.Empty; //Need to find one that has a value. Previously only looked at the first attribute. for (int i = 0; i < propNames.Count - 1; i++) { try { propVal = entity[propNames[i].ToString()].ToString(); } catch { } if (!string.IsNullOrEmpty(propVal)) { propName = propNames[i].ToString(); break; } } int index = propVal.IndexOf('T'); if (index > 0) { propVal = propVal.Substring(index + 1, 2); url = string.Format("{0}?$filter=hour({1}) eq {2}", url, propName, propVal); resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty); info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { jObj = JsonConvert.DeserializeObject(resp.ResponsePayload, settings) as JObject; jArr = jObj.GetValue(Constants.Value) as JArray; if (null == jArr || !jArr.Any()) { return(false); } foreach (JObject et in jArr) { passed = et[propName].ToString().Substring(index + 1, 2) == propVal; } } else { passed = false; } } else { passed = false; } } return(passed); }
public BlockServerElement(IServiceAddress address, ServiceStatus status) { this.address = address; this.status = status; }
static void SetStatusToDisabled(Type serviceType) { knownServices[serviceType] = new ServiceStatus { Service = serviceType, Enabled = false }; }