public void ServiceAttributeIsAvailable() { ServiceAttribute attr = new ServiceAttribute(); Assert.IsNotNull(attr); Assert.IsNull(attr.RegisterAs); }
internal static void RecordWithOneItem_AssertIsAttributeAt0(ServiceAttribute attr) { Assert.AreEqual(UniversalAttributeId.ServiceRecordHandle, attr.Id); Assert.AreEqual(ElementTypeDescriptor.UnsignedInteger, attr.Value.ElementTypeDescriptor); Assert.AreEqual(ElementType.UInt32, attr.Value.ElementType); Assert.AreEqual(55, attr.Value.Value); }
/// <summary> /// 生成服务方法代码 /// </summary> /// <param name="method">方法</param> /// <param name="service">特性</param> /// <returns></returns> private string GetSelfMethodCode(MethodInfo method, ServiceAttribute service) { var returnTypeName = this.GetTypeName(method.ReturnType); var parameters = method.GetParameters().Skip(1); var parameterStateString = string.Join(", ", parameters.Select(item => string.Format("{0} {1}", this.GetTypeName(item.ParameterType), item.Name))); var parameterItemsString = string.Join(", ", parameters.Select(item => item.Name)); if (string.IsNullOrEmpty(parameterItemsString) == false) { parameterItemsString = ", " + parameterItemsString; } var attribute = this.FormatString(4, "[Service(Implements.Remote, {0})]", service.Command); var statement = this.FormatString(4, "public {0} {1}({2})", returnTypeName, method.Name, parameterStateString); if (method.ReturnType != typeof(void)) { statement = this.FormatString(4, "public Task<{0}> {1}({2})", returnTypeName, method.Name, parameterStateString); } var inline = this.FormatString(8, "this.InvokeRemote({0}{1});", service.Command, parameterItemsString); if (method.ReturnType != typeof(void)) { inline = this.FormatString(8, "return this.InvokeRemote<{0}>({1}{2});", returnTypeName, service.Command, parameterItemsString); } StringBuilder sb = new StringBuilder(); sb.AppendLine(attribute); sb.AppendLine(statement); sb.AppendLine(string.Empty.PadRight(4, ' ') + "{"); sb.AppendLine(inline); sb.AppendLine(string.Empty.PadRight(4, ' ') + "}"); return(sb.ToString().TrimEnd()); }
// GetService(ServiceName name) -> handle<move, session> public ResultCode GetService(ServiceCtx context) { if (!_isInitialized) { return(ResultCode.NotInitialized); } string name = ReadName(context); if (name == string.Empty) { return(ResultCode.InvalidName); } KSession session = new KSession(context.Device.System.KernelContext); if (_registeredServices.TryGetValue(name, out KPort port)) { KernelResult result = port.EnqueueIncomingSession(session.ServerSession); if (result != KernelResult.Success) { throw new InvalidOperationException($"Session enqueue on port returned error \"{result}\"."); } } else { if (_services.TryGetValue(name, out Type type)) { ServiceAttribute serviceAttribute = (ServiceAttribute)type.GetCustomAttributes(typeof(ServiceAttribute)).First(service => ((ServiceAttribute)service).Name == name); session.ClientSession.Service = serviceAttribute.Parameter != null ? (IpcService)Activator.CreateInstance(type, context, serviceAttribute.Parameter) : (IpcService)Activator.CreateInstance(type, context); } else { if (ServiceConfiguration.IgnoreMissingServices) { Logger.PrintWarning(LogClass.Service, $"Missing service {name} ignored"); session.ClientSession.Service = new DummyService(name); } else { throw new NotImplementedException(name); } } } if (context.Process.HandleTable.GenerateHandle(session.ClientSession, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); return(ResultCode.Success); }
private static void InitRPCServers() { var services = ServiceAttribute.GetServics(); foreach (var service in services) { RPCServer.Open(service, MQServiceHandler.Instance); } }
public void OneMoveNextMoveNextFalseAndGetCurrent() { ServiceRecord record = RecordAccess_Data.CreateRecordWithOneItems(); IEnumerator_ServiceAttribute etor = record.GetEnumerator(); Assert.IsTrue(etor.MoveNext()); Assert.IsFalse(etor.MoveNext()); ServiceAttribute attr = (ServiceAttribute)etor.Current; }
public MetadataDescriptor(TypeInfo service, TypeInfo implementation) { Service = service ?? throw new ArgumentNullException(nameof(service)); Implementation = implementation; Methods = service.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(item => item.ReturnType != typeof(void) && item.ReturnType != typeof(Task)); ServiceAttribute attribute = service.GetCustomAttribute <ServiceAttribute>(); Group = string.IsNullOrWhiteSpace(attribute.Group) ? service.Assembly.GetName().Name : attribute.Group; }
private Type GetFakeType(ServiceAttribute serviceAttribute) { Mock <Type> type = new Mock <Type>(); type.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())) .Returns(new object[] { serviceAttribute }); return(type.Object); }
private static void CleanupRPCServers() { var services = ServiceAttribute.GetServics(); foreach (var service in services) { RPCServer.Close(service); } }
public void MultipleAndDisposedCurrent() { ServiceRecord record = RecordAccess_Data.CreateRecordWithMultipleItems(); IEnumerator_ServiceAttribute etor = record.GetEnumerator(); Assert.IsTrue(etor.MoveNext()); RecordAccess_Data.RecordWithMultipleItems_AssertIsAttributeAt0(etor.Current); etor.Dispose(); ServiceAttribute attr = etor.Current; }
public void MultipleCurrent() { ServiceRecord record = RecordAccess_Data.CreateRecordWithMultipleItems(); IEnumerator_ServiceAttribute etor = record.GetEnumerator(); try { ServiceAttribute obj = (ServiceAttribute)etor.Current; Assert.Fail("should have thrown!"); } catch (InvalidOperationException) { } }
/// <summary> /// Получить контекст сервиса по типу сервиса. /// </summary> /// <param name="serviceAttribute">Атрибут сервиса.</param> /// <param name="serviceType">Тип сервиса.</param> /// <returns>Контекст сервиса.</returns> public static ServiceContext GetServiceContext(this ServiceAttribute serviceAttribute, Type serviceType) { return(new ServiceContext(serviceType) { CheckAuth = serviceAttribute.CheckAuth, MaxRetryCount = serviceAttribute.MaxRetryCount, IncludeFilters = serviceAttribute.IncludeFilters, ExcludeFilters = serviceAttribute.ExcludeFilters }); }
static void chaosaSrb2() { ushort u = 0x37; // the mobile can get the number of '10' using this ServiceElement se = new ServiceElement(ElementType.Int32, 10); ServiceAttribute sa = new ServiceAttribute(u, se); ServiceRecordBuilder srb = new ServiceRecordBuilder(); srb.AddCustomAttribute(sa); ServiceRecord rcd = srb.ServiceRecord; }
static bool WriteWellKnownAttribute(ServiceAttribute attr) //, ServiceRecord record) { switch (attr.Id) { case UniversalAttributeId.ServiceClassIdList: throw new InvalidOperationException("INTERNAL ERROR: ServiceClassIdList should have been handled earlier."); default: return(false); } }
public void BadStringEncodingNotAscii() { byte[] buffer = RecordBytesEnIsEncodings; ServiceRecord record = new ServiceRecordParser().Parse(buffer); // ServiceAttribute attr = record.GetAttributeById((ServiceAttributeId)0x0100); const ushort langEn = 0x656e; const ushort ietfAscii = 3; LanguageBaseItem langBase = new LanguageBaseItem(langEn, ietfAscii, (ServiceAttributeId)0x0999); String x = attr.Value.GetValueAsString(langBase); }
static Server() { serverThread = new Thread(KeepThreadAlive); ContextRunner.onRequestFinishedProcessing += (msg) => onRequestReceived?.Invoke(msg); ExceptionHandler.onError += (err) => { var serverEvent = new ServerEventData(null, null, err, null); onServerError?.Invoke(serverEvent); }; ServiceAttribute.RegisterServices(); }
static void CollectServices() { foreach (var type in typeof(BaiduServiceProvider).GetTypeInfo().Assembly.ExportedTypes) { ServiceAttribute serviceAttribute = type.GetTypeInfo().GetCustomAttribute <ServiceAttribute>(); if (serviceAttribute != null) { _dic.Add(serviceAttribute.ServiceType, serviceAttribute.ServiceImpType); } } }
public async Task <TResult> DispatchAsync <TResult>(MethodInfo method, object[] args) { ServiceAttribute attribute = method.DeclaringType.GetCustomAttribute <ServiceAttribute>(); OwinRequest request = new OwinRequest() { Path = RoutePath.Parse(method), Parameters = args, Group = string.IsNullOrWhiteSpace(attribute.Group) ? method.DeclaringType.Assembly.GetName().Name : attribute.Group }; return(await this.SendAsync <TResult>(request)); }
public void GetServicesFrom_ServiceAttributeDoesNotHaveExportType_DecoratedTypeUsedAsFromType() { ServiceAttribute service = new ServiceAttribute(); Type fakeType = GetFakeType(service); ServiceRegistrationBehavior behavior = GetTarget(); IEnumerable <ServiceInfo> services = behavior.GetServicesFrom(fakeType); ServiceInfo[] expected = { new ServiceInfo(fakeType, fakeType, Lifetime.Instance) }; AssertEx.AreEquivalent(services, ServiceInfoEquals, expected); }
private static void DoAreEqual(ExpectedServiceAttribute[] expectedAttributes, ServiceRecord record, int depth) { Assert.AreEqual(expectedAttributes.Length, record.Count, "Number of attributes."); for (int i = 0; i < expectedAttributes.Length; ++i) { ExpectedServiceAttribute expected = expectedAttributes[i]; ServiceAttribute row = record[i]; ServiceAttributeId expectedId = (ServiceAttributeId)expected.Id; Assert.AreEqual(expectedId, row.Id, "Attr Id."); DoAreEqual(expected, row.Value, depth + 1); }//for }
public ServiceInfo(Type targetType) { ServiceAttribute serviceAttribute = targetType.GetCustomAttribute <ServiceAttribute>(); if (serviceAttribute == null) { throw new NotSupportedException($"The target type '{targetType.FullName}' is not marked with 'ServiceAttribute'."); } ServiceType = serviceAttribute.ServiceType ?? targetType; InstanceType = targetType; OnDemand = typeof(IServiceInitializer).IsAssignableFrom(targetType); }
internal static ProxyRegistration FromService(object service) { ServiceAttribute attribute = service.GetType().GetCustomAttribute <ServiceAttribute>(); if (attribute == null) { return(null); } ProxyRegistration registration = new ProxyRegistration(attribute.ProxyKey, attribute.ServiceProxyType); return(registration); }
public IEnumerable <ServiceInfo> GetServicesFrom(Type type) { ServiceAttribute atr = AttributesUtil.GetAttribute <ServiceAttribute>(type); if (atr.ContractName == this.annotation) { return new[] { new ServiceInfo(typeof(IService), type, Lifetime.Instance) } } ; return(new ServiceInfo[] {}); } }
internal static void RecordWithMultipleItems_AssertIsAttributeAt2(ServiceAttribute attr) { Assert.AreEqual(UniversalAttributeId.LanguageBaseAttributeIdList, attr.Id); Assert.AreEqual(ElementTypeDescriptor.ElementSequence, attr.Value.ElementTypeDescriptor); Assert.AreEqual(ElementType.ElementSequence, attr.Value.ElementType); // ServiceElement[] seq = attr.Value.GetValueAsElementArray(); Assert.AreEqual(6, seq.Length); ServiceElement element = seq[0]; Assert.AreEqual(ElementTypeDescriptor.UnsignedInteger, element.ElementTypeDescriptor); Assert.AreEqual(ElementType.UInt16, element.ElementType); Assert.AreEqual(Data_LanguageBaseList.LangEn, element.Value); }
public void AccessAttrById() { ServiceRecord record = RecordAccess_Data.CreateRecordWithMultipleItems(); // Assert.AreEqual(RecordAccess_Data.MultipleItemsCount, record.Count); // ServiceAttribute attr = record.GetAttributeById(UniversalAttributeId.ServiceRecordHandle); Assert.AreEqual(UniversalAttributeId.ServiceRecordHandle, attr.Id); Assert.AreEqual(ElementTypeDescriptor.UnsignedInteger, attr.Value.ElementTypeDescriptor); Assert.AreEqual(ElementType.UInt32, attr.Value.ElementType); Assert.AreEqual(66, attr.Value.Value); }
public void CustomOne() { // Rfcomm/StdSvcClass/SvcName ServiceRecordBuilder bldr = new ServiceRecordBuilder(); bldr.AddServiceClass(BluetoothService.SerialPort); bldr.ServiceName = "Hello World!"; ServiceAttribute attr = new ServiceAttribute( UniversalAttributeId.ServiceAvailability, ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, 255)); bldr.AddCustomAttribute(attr); DoTest(ServiceRecordBuilderTests_Data.OnePlusNamePlusCustomOne, bldr); }
public void AccessAttrByIndex0() { ServiceRecord record = RecordAccess_Data.CreateRecordWithMultipleItems(); // Assert.AreEqual(RecordAccess_Data.MultipleItemsCount, record.Count); IList_ServiceAttributeId ids = record.AttributeIds; Assert.AreEqual(RecordAccess_Data.MultipleItemsCount, ids.Count); Assert.AreEqual(UniversalAttributeId.ServiceRecordHandle, ids[0]); // ServiceAttribute attr = record.GetAttributeByIndex(0); RecordAccess_Data.RecordWithMultipleItems_AssertIsAttributeAt0(attr); }
private async Task <ServiceAttribute> CreateUndefined(int serviceId, int specId, int typeId) { var attr = new ServiceAttribute { EventServiceModelId = serviceId, ServiceAttributeSpecificationId = specId, ServiceTypeId = typeId, Value = "undefined" }; _dataContext.ServiceAttributes.Add(attr); await _dataContext.SaveChangesAsync(); return(attr); }
/// <summary> /// ペアリングとサービスのインストールを実施。 /// </summary> /// <param name="deviceInfo">対象のデバイス</param> /// <returns></returns> private bool Pairing(BluetoothDeviceInfo deviceInfo) { // ペアリングリクエスト。完了するまで待ち合わせる。 bool paired = BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, null); // ペアリング失敗したらそこで終了 if (!paired) { return(false); } deviceInfo = new BluetoothDeviceInfo(deviceInfo.DeviceAddress); // ペアリングしたデバイスが対応しているサービス一覧を取得し、リストに記憶する。 List <Guid> serviceGuidList = new List <Guid>(); // L2CapProtocolにてGetServiceRecordsを実行するとデバイスが利用可能なサービス一覧を取得できる。 ServiceRecord[] serviceinfo = deviceInfo.GetServiceRecords(BluetoothService.L2CapProtocol); foreach (var record in serviceinfo) { // サービスレコードをテキストでダンプ //ServiceRecordUtilities.Dump(Console.Error, record); // 取得したサービスレコードのうち、ServiceDescription のレコードを取得する。 ServiceAttribute sdpRecord = record.GetAttributeById(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceDescription); if (sdpRecord != null) { // サービスのGuidを取得 serviceGuidList.Add(sdpRecord.Value.GetValueAsElementArray()[0].GetValueAsUuid()); } } // サービスのインストール foreach (Guid service in serviceGuidList) { try { // 個々のServiceに対し、有効を設定する。 deviceInfo.SetServiceState(service, true, true); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); Console.Error.WriteLine(ex.StackTrace); } } return(true); }
protected override Task ExecuteAsync(CancellationToken stoppingToken) { mXRPCServer = new XRPCServer(); mXRPCServer.RPCOptions.LogToConsole = _xRpcSettingHandler.LogToConsole; mXRPCServer.ServerOptions.LogLevel = _xRpcSettingHandler.LogTypeInfo; mXRPCServer.EventCenter.ServiceInstance += (o, e) => { // e.Service = _serviceProvider.GetService(typeof(XRPCServer)); var item = _serviceProvider.GetService(e.Type); e.Service = item; }; ServiceDescriptor[] items = new ServiceDescriptor[_xRpcSettingHandler.Services.Count]; _xRpcSettingHandler.Services.CopyTo(items, 0); foreach (var item in items) { _serviceCollection.Insert(0, item); } foreach (Assembly item in _xRpcSettingHandler.Assemblies) { Type[] types = item.GetTypes(); foreach (Type type in types) { ServiceAttribute ca = type.GetCustomAttribute <ServiceAttribute>(false); if (ca != null) { if (ca.SingleInstance) { _serviceCollection.AddSingleton(type); } else { _serviceCollection.AddScoped(type); } } } } _serviceCollection.AddSingleton(mXRPCServer); _serviceProvider = _serviceCollection.BuildServiceProvider(); if (_xRpcSettingHandler.Assemblies != null) { mXRPCServer.Register(_xRpcSettingHandler.Assemblies); } mXRPCServer.Open(); return(Task.CompletedTask); }