public void ProxyForClass() { object proxy = generator.CreateClassProxy( typeof(ServiceClass), new ResultModifierInterceptor() ); Assert.IsNotNull(proxy); Assert.IsTrue(typeof(ServiceClass).IsAssignableFrom(proxy.GetType())); ServiceClass instance = (ServiceClass)proxy; // return value is changed by the interceptor Assert.AreEqual(44, instance.Sum(20, 25)); // return value is changed by the interceptor Assert.AreEqual(true, instance.Valid); Assert.AreEqual((byte)45, instance.Sum((byte)20, (byte)25)); // byte Assert.AreEqual(45L, instance.Sum(20L, 25L)); // long Assert.AreEqual((short)45, instance.Sum((short)20, (short)25)); // short Assert.AreEqual(45f, instance.Sum(20f, 25f)); // float Assert.AreEqual(45.0, instance.Sum(20.0, 25.0)); // double Assert.AreEqual((ushort)45, instance.Sum((ushort)20, (ushort)25)); // ushort Assert.AreEqual((uint)45, instance.Sum((uint)20, (uint)25)); // uint Assert.AreEqual((ulong)45, instance.Sum((ulong)20, (ulong)25)); // ulong }
public void MethodWithWarpedParametersButVoidResult() { ServiceClass clazz = JsonRpcServices.GetClassFromType(typeof(ServiceWithMethodsUsingWarpedParameters)); Method foo = clazz.FindMethodByName("FooNoResult"); Assert.AreEqual(typeof(void), foo.ResultType); }
/// <summary> /// Изменение кодов КСГ и других зависимых данных при смене имени услуги /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void comboBoxServiceName_SelectedIndexChanged(object sender, EventArgs e) { if (_stopComboBoxServiceNameItemsChanged) { return; } // Если убирается название услуги то надо попробовать заполнить данные по КСГ из данных по МКБ if (string.IsNullOrEmpty(comboBoxServiceName.Text)) { comboBoxMKB_TextChanged(sender, e); return; } LastServiceComboBoxItem item = (LastServiceComboBoxItem)comboBoxServiceName.SelectedItem; ServiceClass service = new ServiceClass(item.HiddenValue); textBoxServiceCode.Text = service.ServiceCode; textBoxKsgCode.Text = service.KsgCode; textBoxKsgDecoding.Text = service.KsgDecoding; _stopComboBoxServiceNameItemsChanged = true; SaveLastUsedServices((LastServiceComboBoxItem)comboBoxServiceName.SelectedItem); _stopComboBoxServiceNameItemsChanged = false; }
private void SetButton() { lbInform.Text = ""; ServiceClass sc = new ServiceClass(); if (!sc.UserAction(User.Identity.Name, Restrictions.LibraryEdit)) { bNew.Visible = false; bEdit.Visible = false; bDelete.Visible = false; bExcel.Visible = false; return; } if (gvAttachments.Rows.Count > 0) { bEdit.Visible = true; bDelete.Visible = true; bExcel.Visible = true; bDelete.Attributes.Add("OnClick", String.Format("return confirm('Удалить вложение {0}?');", gvAttachments.DataKeys[Convert.ToInt32(gvAttachments.SelectedIndex)].Values["prod_name_at"].ToString())); bEdit.Attributes.Add("OnClick", String.Format("return show_productatt('mode=2&id_pa={0}&id_prb={1}')", gvAttachments.DataKeys[Convert.ToInt32(gvAttachments.SelectedIndex)].Values["id_pa"].ToString(), gvAttachments.DataKeys[Convert.ToInt32(gvAttachments.SelectedIndex)].Values["id_prb_p"].ToString())); } else { bEdit.Visible = false; bDelete.Visible = false; bExcel.Visible = false; } }
public void Copy(string fileSource, string fileDestination) //Метод копирования БД { if (ServiceClass.ChekServices(Program.controllers)) { MessageBox.Show("Не все службы остановлены"); } else { FileStreamSource = new FileStream(fileSource, FileMode.Open); FileStreamDestination = new FileStream(fileDestination, FileMode.OpenOrCreate); double countEtalon = FileStreamSource.Length / 100; double persent = 1; double count = 0; while (FileStreamSource.Position < FileStreamSource.Length) { byte[] buffer = new byte[1000000]; int i = FileStreamSource.Read(buffer, 0, buffer.Length); FileStreamDestination.Write(buffer, 0, i); while (persent < 100) { count += countEtalon; persent = count * 100 / FileStreamSource.Length; Program.myForm.updProgressBar(persent); } } FileStreamSource.Close(); FileStreamDestination.Flush(); FileStreamDestination.Close(); chekMD5(fileSource, fileDestination); } }
private static T Create <T>(DeviceClass dc, ServiceClass sc) where T : MarshalByRefObject { var p = new SimpleBluetoothClassMock(typeof(T), dc, sc); return((T)p.GetTransparentProxy()); }
/// <exclude/> /// <summary> /// Add a SDP record. /// </summary> /// - /// <param name="sdpRecord">An array of <see cref="T:System.Byte"/> /// containing the complete SDP record. /// </param> /// <param name="cod">A <see cref="T:InTheHand.Net.Bluetooth.ServiceClass"/> /// containing any bits to set in the devices Class of Device value. /// </param> /// - /// <returns>A handle representing the record, pass to /// <see cref="RemoveService"/> to remote the record. /// </returns> public static IntPtr SetService(byte[] sdpRecord, ServiceClass cod) { BTHNS_SETBLOB blob = new BTHNS_SETBLOB(sdpRecord); //added for XP - adds class of device bits #if WinXP blob.CodService = (uint)cod; #endif WSAQUERYSET qs = new WSAQUERYSET(); qs.dwSize = WqsOffset.StructLength_60; qs.dwNameSpace = WqsOffset.NsBth_16; System.Diagnostics.Debug.Assert(Marshal.SizeOf(qs) == qs.dwSize, "WSAQUERYSET SizeOf == dwSize"); GCHandle hBlob = GCHandle.Alloc(blob.ToByteArray(), GCHandleType.Pinned); BLOB b = new BLOB(blob.Length, GCHandleHelper.AddrOfPinnedObject(hBlob)); GCHandle hb = GCHandle.Alloc(b, GCHandleType.Pinned); qs.lpBlob = hb.AddrOfPinnedObject(); try { int hresult = NativeMethods.WSASetService(ref qs, WSAESETSERVICEOP.RNRSERVICE_REGISTER, 0); SocketBluetoothClient.ThrowSocketExceptionForHR(hresult); } finally { hb.Free(); hBlob.Free(); } IntPtr handle = blob.Handle; blob.Dispose(); return(handle); }
public ActionResult LookCode(BaseConfigModel r) { ServiceClass default_Template = new ServiceClass(); BaseConfigModel baseConfigModel = r; var tableFiled = new DataBaseTableBLL().GetTableFiledList(baseConfigModel.DataBaseLinkId, baseConfigModel.DataBaseTableName); string entitybuilder = default_Template.EntityBuilder(baseConfigModel, DataHelper.ListToDataTable <DataBaseTableFieldEntity>(tableFiled.ToList())); string entitymapbuilder = default_Template.EntityMapBuilder(baseConfigModel); string servicebuilder = default_Template.ServiceBuilder(baseConfigModel); string iservicebuilder = default_Template.IServiceBuilder(baseConfigModel); string businesbuilder = default_Template.BusinesBuilder(baseConfigModel); var jsonData = new { entityCode = entitybuilder, entitymapCode = entitymapbuilder, serviceCode = servicebuilder, iserviceCode = iservicebuilder, businesCode = businesbuilder, }; return(ToJsonResult(jsonData)); }
private static List <BluetoothDevice> GetDevices(int type) { AndroidJavaObject array; if (type == 0) { array = ServiceClass.CallStatic <AndroidJavaObject>("u_getBondedDevices"); } else { array = ServiceClass.CallStatic <AndroidJavaObject>("u_getDiscoveredDevices"); } List <BluetoothDevice> bondedDevices = new List <BluetoothDevice>(); if (array.GetRawObject().ToInt32() != 0) { string[] devices = AndroidJNIHelper.ConvertFromJNIArray <string[]>(array.GetRawObject()); foreach (string device in devices) { string[] tokens = device.Split(','); BluetoothDevice dev; dev.address = tokens[0]; dev.name = tokens[1]; bondedDevices.Add(dev); } } return(bondedDevices); }
public MainWindow() { InitializeComponent(); HttpChannel channel = new HttpChannel(); ChannelServices.RegisterChannel(channel, false); // Registers the remote class. (This could be done with a // configuration file instead of a direct call.) RemotingConfiguration.RegisterWellKnownClientType( Type.GetType("Remote.ServiceClass, remote"), "http://localhost:8080/object1uri"); // Instead of creating a new object, this obtains a reference // to the server's single instance of the ServiceClass object. ServiceClass object1 = new ServiceClass(); try { MessageBox.Show("Suma " + object1.sum(1,3)); } catch (Exception ex) { MessageBox.Show("Exception of type: " + ex.ToString() + " occurred."); MessageBox.Show("Details: " + ex.Message); } }
private void SetButton() { ServiceClass sc = new ServiceClass(); if (!sc.UserAction(User.Identity.Name, Restrictions.LibraryEdit)) { bNew.Visible = false; bEdit.Visible = false; bDelete.Visible = false; bExcel.Visible = false; return; } if (gvManufacturers.Rows.Count > 0) { bEdit.Visible = true; bDelete.Visible = true; bExcel.Visible = true; bDelete.Attributes.Add("OnClick", String.Format("return confirm('Удалить производителя {0}?');", gvManufacturers.DataKeys[Convert.ToInt32(gvManufacturers.SelectedIndex)].Values["name"].ToString())); bEdit.Attributes.Add("OnClick", String.Format("return show_catalog('type=manufacturer&mode=2&id={0}')", gvManufacturers.DataKeys[Convert.ToInt32(gvManufacturers.SelectedIndex)].Values["id"].ToString())); } else { bEdit.Visible = false; bDelete.Visible = false; bExcel.Visible = false; } }
public void SubtractMethod_Numbers_Success() { var sc = new ServiceClass(); var result = sc.Subtract(4, 3); Assert.Equal(1, result); }
private JsonObject BuildCallTemplatesObject() { JsonObject info = new JsonObject(); StringBuilder sb = new StringBuilder(); foreach (Method method in ServiceClass.GetMethods()) { sb.Length = 0; sb.Append("{ "); Parameter[] parameters = method.GetParameters(); if (parameters.Length == 0) { sb.Append("/* void */"); } else { foreach (Parameter parameter in parameters) { if (parameter.Position > 0) { sb.Append(", "); } sb.Append('"').Append(parameter.Name).Append("\" : null"); } } sb.Append(" }"); info.Put(method.Name, sb.ToString()); } return(info); }
public void CheckHotelQuotes_SmallQuotaState() { using (var searchDc = new MtSearchDbDataContext()) { string hash; const ServiceClass serviceClass = ServiceClass.Hotel; const int code = 19730; const int subCode1 = 2; int? subCode2 = 32; const int partnerKey = 6732; var serviceDateFrom = new DateTime(2014, 04, 27); var serviceDateTo = new DateTime(2014, 05, 03); const int requestedPlaces = 2; var result = searchDc.CheckServiceQuota(serviceClass, code, subCode1, subCode2, partnerKey, serviceDateFrom, serviceDateTo, requestedPlaces, out hash); Assert.AreEqual(result, new QuotaStatePlaces { IsCheckInQuota = false, Places = 1, QuotaState = QuotesStates.Small }); } }
public void MultiplyMethod_Numbers_Success() { var sc = new ServiceClass(); var result = sc.Multiply(4, 3); Assert.Equal(12, result); }
protected void Page_Load(object sender, EventArgs e) { lock (Database.lockObjectDB) { ServiceClass sc = new ServiceClass(); if (!sc.UserAction(User.Identity.Name, Restrictions.LibraryOrgEdit)) { Response.Redirect("~\\Account\\Restricted.aspx", true); } org_id = Convert.ToInt32(Request.QueryString["idO"]); p_id = Convert.ToInt32(Request.QueryString["idP"]); mode = Convert.ToInt32(Request.QueryString["mode"]); Title = (mode == 1) ? "Добавление сотрудника организации" : "Редактирование сотрудника организации"; if (Page.IsPostBack) { return; } if (mode == 1) { DataSet ds = new DataSet(); Database.ExecuteQuery("select title,embosstitle from org where id=" + org_id.ToString(), ref ds, null); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { tbTitle.Text = Convert.ToString(ds.Tables[0].Rows[0]["Title"]).Trim(); tbEmboss.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmbossTitle"]).Trim(); } } if (mode == 2) { LoadOrg(); } } }
public void ProxyForClassWithInterfaces() { object proxy = generator.CreateClassProxy(typeof(ServiceClass), new[] { typeof(IDisposable) }, new ResultModifierInterceptor()); Assert.IsNotNull(proxy); Assert.IsTrue(typeof(ServiceClass).IsAssignableFrom(proxy.GetType())); Assert.IsTrue(typeof(IDisposable).IsAssignableFrom(proxy.GetType())); ServiceClass inter = (ServiceClass)proxy; Assert.AreEqual(44, inter.Sum(20, 25)); Assert.AreEqual(true, inter.Valid); try { IDisposable disp = (IDisposable)proxy; disp.Dispose(); Assert.Fail("Expected exception as Dispose has no implementation"); } catch (NotImplementedException ex) { Assert.AreEqual( "This is a DynamicProxy2 error: The interceptor attempted to 'Proceed' for method 'Void Dispose()' which has no target. " + "When calling method without target there is no implementation to 'proceed' to and it is the responsibility of the interceptor " + "to mimic the implementation (set return value, out arguments etc)", ex.Message); } }
/// <summary> /// Изменение кодов КСГ и других зависимых данных при смене имени услуги /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void comboBoxServiceName_SelectedIndexChanged(object sender, EventArgs e) { if (_stopComboBoxServiceNameItemsChanged) { return; } if (string.IsNullOrEmpty(comboBoxServiceName.Text)) { textBoxServiceCode.Text = textBoxKsgCode.Text = textBoxKsgDecoding.Text = string.Empty; return; } LastServiceComboBoxItem item = (LastServiceComboBoxItem)comboBoxServiceName.SelectedItem; ServiceClass service = new ServiceClass(item.HiddenValue); textBoxServiceCode.Text = service.ServiceCode; textBoxKsgCode.Text = service.KsgCode; textBoxKsgDecoding.Text = service.KsgDecoding; _stopComboBoxServiceNameItemsChanged = true; SaveLastUsedServices((LastServiceComboBoxItem)comboBoxServiceName.SelectedItem); _stopComboBoxServiceNameItemsChanged = false; }
public void InvocationForConcreteClassProxy() { KeepDataInterceptor interceptor = new KeepDataInterceptor(); object proxy = generator.CreateClassProxy(typeof(ServiceClass), interceptor); ServiceClass instance = (ServiceClass)proxy; instance.Sum(20, 25); Assert.IsNotNull(interceptor.Invocation); Assert.IsNotNull(interceptor.Invocation.Arguments); Assert.AreEqual(2, interceptor.Invocation.Arguments.Length); Assert.AreEqual(20, interceptor.Invocation.Arguments[0]); Assert.AreEqual(25, interceptor.Invocation.Arguments[1]); Assert.AreEqual(20, interceptor.Invocation.GetArgumentValue(0)); Assert.AreEqual(25, interceptor.Invocation.GetArgumentValue(1)); Assert.AreEqual(45, interceptor.Invocation.ReturnValue); Assert.IsNotNull(interceptor.Invocation.Proxy); Assert.IsInstanceOf(typeof(ServiceClass), interceptor.Invocation.Proxy); Assert.IsNotNull(interceptor.Invocation.InvocationTarget); Assert.IsInstanceOf(typeof(ServiceClass), interceptor.Invocation.InvocationTarget); Assert.IsNotNull(interceptor.Invocation.TargetType); Assert.AreSame(typeof(ServiceClass), interceptor.Invocation.TargetType); Assert.IsNotNull(interceptor.Invocation.Method); Assert.IsNotNull(interceptor.Invocation.MethodInvocationTarget); Assert.AreSame(interceptor.Invocation.Method, interceptor.Invocation.MethodInvocationTarget.GetBaseDefinition()); }
public void MethodIdempotency() { ServiceClass clazz = JsonRpcServices.GetClassFromType(typeof(IdempotencyTestService)); Assert.IsFalse(clazz.GetMethodByName("NonIdempotentMethod").Idempotent); Assert.IsTrue(clazz.GetMethodByName("IdempotentMethod").Idempotent); }
public async Task <List <ServiceClass> > GetServiceGroupsAsync(ContentURI uri) { Helpers.SqlIOAsync sqlIO = new Helpers.SqlIOAsync(uri); SqlDataReader serviceGroups = await sqlIO.RunProcAsync("0GetServiceGroups"); List <ServiceClass> colServiceGroups = new List <ServiceClass>(); if (serviceGroups != null) { using (serviceGroups) { //build a related service list to return to the client while (await serviceGroups.ReadAsync()) { ServiceClass newServiceGroup = new ServiceClass(); newServiceGroup.PKId = serviceGroups.GetInt32(0); newServiceGroup.ServiceClassNum = serviceGroups.GetString(1); newServiceGroup.ServiceClassName = serviceGroups.GetString(2); newServiceGroup.ServiceClassDesc = serviceGroups.GetString(3); newServiceGroup.Service = new List <Service>(); //nondb newServiceGroup.IsSelected = false; colServiceGroups.Add(newServiceGroup); } } } sqlIO.Dispose(); return(colServiceGroups); }
public void SleeperClassPropertySet(string value, ServiceClass expectedValue) { var classRecord = $"BSNC108651812191905171110100GPXX1S531220122180012 DMUV 125 B{value}S T P"; var record = ParseRecord(classRecord); Assert.Equal(expectedValue, record.SleeperClass); }
public void DivideMethod_Numbers_Success() { var sc = new ServiceClass(); var result = sc.Divide(4, 2); Assert.Equal(2, result); }
public void AddMethod_Numbers_Success() { var sc = new ServiceClass(); var result = sc.Add(1, 2); Assert.Equal(3, result); }
internal static ClassOfDevice ConvertCoDs(BluetoothClass codAndroid) { DeviceClass dc = (DeviceClass)(int)codAndroid.DeviceClass; ServiceClass sc = FindSetServiceBits(codAndroid); return(new ClassOfDevice(dc, sc)); }
/// <summary> /// Является ли значение типом мало /// </summary> /// <param name="dc">Контекст базы данных</param> /// <param name="serviceClass">Класс услуги</param> /// <param name="quotaExistCount">Число оставшихся квот</param> /// <param name="quotaAllCount">Число квот всего</param> /// <param name="hash">Хэш кэша</param> /// <returns></returns> public static bool IsSmallQuotaState(this MtSearchDbDataContext dc, ServiceClass serviceClass, uint quotaExistCount, uint quotaAllCount, out string hash) { hash = String.Format("{0}_{1}_{2}_{3}", MethodBase.GetCurrentMethod().Name, serviceClass, quotaExistCount, quotaAllCount); if (CacheHelper.IsCacheKeyExists(hash)) { var result = CacheHelper.GetCacheItem <bool>(hash); return(result); } QuotaSmallServiceParams pars = dc.GetQuotaSmallServiceParams()[(uint)serviceClass]; if (pars == null) { throw new ApplicationException("Ошибка метода: " + MethodBase.GetCurrentMethod().Name + "_" + serviceClass); } bool res; bool?placeCondition = null; bool?percentCondition = null; if (pars.PlaceParam.HasValue) { placeCondition = quotaExistCount <= pars.PlaceParam.Value; } if (pars.PercentParam.HasValue) { percentCondition = (quotaExistCount / (double)quotaAllCount) * 100 <= pars.PercentParam.Value; } if (pars.AndParam) { if (placeCondition.HasValue && placeCondition.Value == false || percentCondition.HasValue && percentCondition.Value == false) { res = false; } else { res = true; } } else { if (placeCondition.HasValue && placeCondition.Value || percentCondition.HasValue && percentCondition.Value) { res = true; } else { res = false; } } CacheHelper.AddCacheData(hash, res, new List <string>() { TableName }, Globals.Settings.Cache.LongCacheTimeout); return(res); }
static void Main(string[] args) { string processNameOrID; bool isKillProcessFail = false; while (true) { Console.Clear(); Process[] processes = Process.GetProcesses(); Console.Write("\tИмя процесса"); Console.SetCursorPosition(40, Console.CursorTop); Console.WriteLine("ID процесса"); foreach (var item in processes) { Console.Write(" " + item.ProcessName); Console.SetCursorPosition(40, Console.CursorTop); Console.WriteLine(item.Id); } Console.Write("Введите имя процесса или его номер для его завершения: "); processNameOrID = Console.ReadLine(); if (int.TryParse(processNameOrID, out int processID)) { try { Process.GetProcessById(processID).Kill(); while (ServiceClass.isProcessExist(processID)) { ; } } catch (Exception) { Console.WriteLine("Невозможно завершить указанный процесс"); Console.ReadKey(); } } else { foreach (var item in Process.GetProcessesByName(processNameOrID)) { try { item.Kill(); } catch (Exception) { isKillProcessFail = true; Console.WriteLine("Невозможно завершить указанный процесс"); Console.ReadKey(); } } while (ServiceClass.isProcessExist(processNameOrID) && !isKillProcessFail) { ; } } } }
protected override void ProcessRequest() { Destination destination = null; string destinationId; string s = base.Request.QueryString["source"]; if (!StringUtils.IsNullOrEmpty(s)) { destinationId = this.MessageBroker.GetDestinationId(s); destination = this.MessageBroker.GetDestination(destinationId); } else { destinationId = base.Request.QueryString["destination"]; if (!StringUtils.IsNullOrEmpty(destinationId)) { destination = this.MessageBroker.GetDestination(destinationId); s = destination.Source; } } FactoryInstance factoryInstance = destination.GetFactoryInstance(); factoryInstance.Source = s; Type instanceClass = factoryInstance.GetInstanceClass(); if (instanceClass != null) { ServiceClass service = JsonRpcServiceReflector.FromType(instanceClass); this.UpdateLastModifiedTime(instanceClass); if (!this.Modified()) { base.Response.StatusCode = 0x130; } else { if (this._lastModifiedTime != DateTime.MinValue) { base.Response.Cache.SetCacheability(HttpCacheability.Public); base.Response.Cache.SetLastModified(this._lastModifiedTime); } base.Response.ContentType = "text/javascript"; string str3 = service.Name + "Proxy.js"; base.Response.AppendHeader("Content-Disposition", "attachment; filename=" + str3); string key = "default"; if (!StringUtils.IsNullOrEmpty(base.Request.QueryString["generator"])) { key = base.Request.QueryString["generator"]; } if (this._generators.Contains(key)) { (this._generators[key] as IJsonRpcProxyGenerator).WriteProxy(service, new IndentedTextWriter(base.Response.Output), base.Request); } else if (log.get_IsErrorEnabled()) { log.Error(string.Format("JsonRpcGenerator {0} was not found", key)); } } } }
public static extern ServiceError DNSServiceQueryRecord(out ServiceRef sdRef, ServiceFlags flags, uint interfaceIndex, string fullname, ServiceType rrtype, ServiceClass rrclass, DNSServiceQueryRecordReply callBack, IntPtr context);
public FickleType(string name, Type baseType, bool byRef = false, bool isPrimitive = false) { this.name = name; this.ServiceClass = null; this.baseType = baseType; this.byRef = byRef; this.isPrimitive = isPrimitive; }
public FickleType(ServiceClass serviceClass, ServiceModel serviceModel, bool byRef = false, bool isPrimitive = false) { this.serviceModel = serviceModel; this.name = serviceClass.Name; this.ServiceClass = serviceClass; this.byRef = byRef; this.isPrimitive = isPrimitive; }
public void WriteRequestAndReadResponse() { //var properties = new Hashtable() { { "port", 8080 } }; //var channel = new TcpChannel(properties, null, new SoapServerFormatterSinkProvider()); //if using SOAP via TCP, messageRequestStream must be SOAP format var channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel, false); var service = new ServiceClass(); ObjRef obj = RemotingServices.Marshal(service, "Remote"); var uri = "tcp://localhost:8080/Remote"; using (var client = new TcpClient()) { client.Connect("localhost", 8080); using (var stream = client.GetStream()) { var messageRequest = new MethodCall(new Header[] { new Header("__Uri", uri), new Header("__MethodName", "Do"), new Header("__MethodSignature", new Type[] { typeof(string) }), new Header("__TypeName", typeof(ServiceClass).AssemblyQualifiedName), new Header("__Args", new object[] { "Hi" }) }); var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest); var writer = new ProtocolWriter(stream); writer.WritePreamble(); writer.WriteMajorVersion(); writer.WriteMinorVersion(); writer.WriteOperation(TcpOperations.Request); writer.WriteContentDelimiter(TcpContentDelimiter.ContentLength); writer.WriteContentLength(messageRequestStream.Length); writer.WriteTransportHeaders(uri); writer.WriteBytes(messageRequestStream); var reader = new ProtocolReader(stream); Console.WriteLine("Preamble: {0}", reader.ReadPreamble()); Console.WriteLine("MajorVersion: {0}", reader.ReadMajorVersion()); Console.WriteLine("MinorVersion: {0}", reader.ReadMinorVersion()); var op = reader.ReadOperation(); Assert.AreEqual(TcpOperations.Reply, op); Console.WriteLine("Operation: {0}", op); Console.WriteLine("ContentDelimiter: {0}", reader.ReadContentDelimiter()); var length = reader.ReadContentLength(); Console.WriteLine("ContentLength: {0}", length); reader.ReadTransportHeaders(); var messageResponse = BinaryFormatterHelper.DeserializeObject(reader.ReadBytes(length)) as MethodResponse; Assert.IsNotNull(messageResponse); DumpHelper.DumpMessage(messageResponse); if (messageResponse.Exception != null) throw messageResponse.Exception; Assert.AreEqual("Hi", messageResponse.ReturnValue); } } }
public MainWindow() { InitializeComponent(); HttpChannel channel = new HttpChannel(8080); ChannelServices.RegisterChannel(channel, false); ServiceClass object1 = new ServiceClass(); // Creates the single instance of ServiceClass. All clients // will use this instance. ObjRef ref1 = RemotingServices.Marshal(object1, "object1uri"); }
public void TestModelMapper() { var service1 = new ServiceClass() { Id = new Guid("51438b2f-4cd7-4e02-0000-000100000000"), Name = "John", Length = 1024, Nullable1 = 10, Nullable2 = null, Pi = 3.14, When = DateTime.SpecifyKind(new DateTime(2013, 06, 24, 8, 0, 0), DateTimeKind.Utc), AnotherWhen = new TimeSpan(6, 12, 8, 0), MaybeId = new Guid("51438b2f-4cd7-4e02-0000-033300000000"), Thing = new ServiceThing { Name = "X", Value = "123" }, Stuff = new List<string> { "A", "B", "C" }, Links = new List<Guid> { new Guid("51438b2f-4cd7-ff02-0000-000100000000"), new Guid("51438b2f-4cd7-ff02-0000-000200000000") }, Things = new List<ServiceThing> { new ServiceThing { Name = "Blue", Value="0000FF" } }, Mapping = new Dictionary<string, string> { { "A", "1" }, { "B", "2" }, { "C", "2" } }, Contents = "{ \"list\" : [\"1\", \"2\", \"3\"], \"anotherList\" : [\"A\", \"B\", \"C\"] }" }; var data = service1.CopyAsNew<DataClass>(); var service2 = data.CopyAsNew<ServiceClass>(); Assert.AreEqual(service1.Id, service2.Id); Assert.AreEqual(service1.Name, service2.Name); Assert.AreEqual(service1.Length, service2.Length); Assert.AreEqual(service1.Nullable1, service2.Nullable1); Assert.AreEqual(service1.Nullable2, service2.Nullable2); Assert.AreEqual(service1.Pi, service2.Pi); Assert.AreEqual(service1.When, service2.When); Assert.AreEqual(service1.AnotherWhen, service2.AnotherWhen); Assert.AreEqual(service1.MaybeId, service2.MaybeId); CollectionAssert.AreEqual(service1.Stuff, service2.Stuff); CollectionAssert.AreEqual(service1.Links, service2.Links); CollectionAssert.AreEqual(service1.Things, service2.Things); CollectionAssert.AreEqual(service1.Mapping, service2.Mapping); Assert.AreEqual(service1.Contents, service2.Contents); }
public void TrackingAndCustomProxy() { TrackingServices.RegisterTrackingHandler(new TrackingHandler()); var channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel, false); var service = new ServiceClass(); ObjRef obj = RemotingServices.Marshal(service, "TcpService"); var url="tcp://localhost:8080/TcpService"; service = RemotingServices.Connect(typeof(ServiceClass), url) as ServiceClass; Console.WriteLine("client received: {0}", service.Echo("hello")); service = new CustomProxy(typeof(ServiceClass), url).GetTransparentProxy() as ServiceClass; Console.WriteLine("client received: {0}", service.Echo("hello")); RemotingServices.Unmarshal(obj); RemotingServices.Disconnect(service); }
public void TestCustomTypeCopying() { PropertyCopier.ClearTypeConverters(); PropertyCopier.AddTypeConverter<MyId, ObjectId>(fromValue => new ObjectId(((MyId)fromValue).Id)); PropertyCopier.AddTypeConverter<ObjectId, MyId>(fromValue => new MyId((ObjectId)fromValue)); ServiceClass service1 = new ServiceClass() { Id = MyId.GenerateNewId(), Ids = new MyId[] { MyId.GenerateNewId(), MyId.GenerateNewId() }, MoreIds = new List<MyId> { MyId.GenerateNewId(), MyId.GenerateNewId() } }; var data = service1.CopyAsNew<DataClass>(); var service2 = data.CopyAsNew<ServiceClass>(); Assert.AreEqual(service1.Id, service2.Id); CollectionAssert.AreEqual(service1.Ids, service2.Ids); CollectionAssert.AreEqual(service1.MoreIds, service2.MoreIds); }
private static IntPtr SetService(byte[] sdpRecord, ServiceClass cod) { BTHNS_SETBLOB blob = new BTHNS_SETBLOB(sdpRecord); //added for XP - adds class of device bits #if WinXP blob.CodService = (uint)cod; #endif WSAQUERYSET qs = new WSAQUERYSET(); qs.dwSize = WqsOffset.StructLength_60; qs.dwNameSpace = WqsOffset.NsBth_16; System.Diagnostics.Debug.Assert(Marshal.SizeOf(qs) == qs.dwSize, "WSAQUERYSET SizeOf == dwSize"); GCHandle hBlob = GCHandle.Alloc(blob.ToByteArray(), GCHandleType.Pinned); BLOB b = new BLOB(blob.Length, GCHandleHelper.AddrOfPinnedObject(hBlob)); GCHandle hb = GCHandle.Alloc(b, GCHandleType.Pinned); qs.lpBlob = hb.AddrOfPinnedObject(); try { int hresult = NativeMethods.WSASetService(ref qs, WSAESETSERVICEOP.RNRSERVICE_REGISTER, 0); BluetoothClient.ThrowSocketExceptionForHR(hresult); } finally { hb.Free(); hBlob.Free(); } IntPtr handle = blob.Handle; blob.Dispose(); return handle; }
public void Run() { // Enable this and the e.WaitOne call at the bottom if you // are going to make more than one asynchronous call. e = new ManualResetEvent(false); // false : evt non signalé Console.WriteLine("Remote synchronous and asynchronous delegates."); Console.WriteLine(new String('-',80)); Console.WriteLine(); // This is the only thing you must do in a remoting scenario // for either synchronous or asynchronous programming // configuration. RemotingConfiguration.Configure("SyncAsync.exe.config", true); // The remaining steps are identical to single- // AppDomain programming. Sauf si on veut utiliser la ligne suivante, plus prudente qu'un new // ServiceClass obj = (ServiceClass)Activator.GetObject(typeof(ServiceClass), "tcp://localhost:8085/ServiceClass.rem"); ServiceClass obj = new ServiceClass(); // attention, on récupère un proxy ... // This delegate is a remote synchronous delegate. RemoteSyncDelegate Remotesyncdel = new RemoteSyncDelegate(obj.VoidCall); // When invoked, program execution waits until the method returns. // This delegate can be passed to another application domain // to be used as a callback to the obj.VoidCall method. Console.WriteLine(Remotesyncdel()); Console.WriteLine("Pause 1"); Console.Read(); // This delegate is an asynchronous delegate. Two delegates must // be created. The first is the system-defined AsyncCallback // delegate, which references the method that the remote type calls // back when the remote method is done. AsyncCallback RemoteCallback = new AsyncCallback(this.OurRemoteAsyncCallBack); // Create the delegate to the remote method you want to use // asynchronously. RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.TimeConsumingRemoteCall); // Start the method call. Note that execution on this // thread continues immediately without waiting for the return of // the method call. IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null); // BeginInvoke est générée : prend d'abord les paramètres s'il y en a (ici : non, TimeConsumingRemoteCall ne prend pas de param), puis le callback, puis un objet qcq, qui peut être utile par exemple à passer des informations d'état) Console.WriteLine("Pause 2"); Console.Read(); // If you want to stop execution on this thread to // wait for the return from this specific call, retrieve the // IAsyncResult returned from the BeginIvoke call, obtain its // WaitHandle, and pause the thread, such as the next line: // RemAr.AsyncWaitHandle.WaitOne(); // To wait in general, if, for example, many asynchronous calls // have been made and you want notification of any of them, or, // like this example, because the application domain can be // recycled before the callback can print the result to the // console. //e.WaitOne(); // This simulates some other work going on in this thread while the // async call has not returned. int count = 0; while(!RemAr.IsCompleted){ Console.Write("\rNot completed: " + (++count).ToString()); // Make sure the callback thread can invoke callback. Thread.Sleep(1); } Console.Read(); }
private static void OnQueryRecordReply(ServiceRef sdRef, ServiceFlags flags, uint interfaceIndex, ServiceError errorCode, string fullname, ServiceType rrtype, ServiceClass rrclass, ushort rdlen, IntPtr rdata, uint ttl, IntPtr context) { var handle = GCHandle.FromIntPtr(context); var browseService = handle.Target as BrowseService; switch(rrtype) { case ServiceType.A: IPAddress address; if(rdlen == 4) { // ~4.5 times faster than Marshal.Copy into byte[4] uint address_raw = (uint)(Marshal.ReadByte (rdata, 3) << 24); address_raw |= (uint)(Marshal.ReadByte (rdata, 2) << 16); address_raw |= (uint)(Marshal.ReadByte (rdata, 1) << 8); address_raw |= (uint)Marshal.ReadByte (rdata, 0); address = new IPAddress(address_raw); } else if(rdlen == 16) { byte [] address_raw = new byte[rdlen]; Marshal.Copy(rdata, address_raw, 0, rdlen); address = new IPAddress(address_raw, interfaceIndex); } else { break; } if(browseService.hostentry == null) { browseService.hostentry = new IPHostEntry(); browseService.hostentry.HostName = browseService.hosttarget; } if(browseService.hostentry.AddressList != null) { ArrayList list = new ArrayList(browseService.hostentry.AddressList); list.Add(address); browseService.hostentry.AddressList = list.ToArray(typeof(IPAddress)) as IPAddress []; } else { browseService.hostentry.AddressList = new IPAddress [] { address }; } Log.To.Discovery.V(Tag, "Query record reply received for {0} (0x{1})", browseService, sdRef.Raw.ToString("X")); ServiceResolvedEventHandler handler = browseService._resolved; if(handler != null) { handler(browseService, new ServiceResolvedEventArgs(browseService)); } break; case ServiceType.TXT: if(browseService.TxtRecord != null) { browseService.TxtRecord.Dispose(); } browseService.TxtRecord = new TxtRecord(rdlen, rdata); break; default: break; } sdRef.Deallocate(); }
private void OnQueryRecordReply(ServiceRef sdRef, ServiceFlags flags, uint interfaceIndex, ServiceError errorCode, string fullname, ServiceType rrtype, ServiceClass rrclass, ushort rdlen, IntPtr rdata, uint ttl, IntPtr context) { switch(rrtype) { case ServiceType.A: IPAddress address; if(rdlen == 4) { // ~4.5 times faster than Marshal.Copy into byte[4] uint address_raw = (uint)(Marshal.ReadByte (rdata, 3) << 24); address_raw |= (uint)(Marshal.ReadByte (rdata, 2) << 16); address_raw |= (uint)(Marshal.ReadByte (rdata, 1) << 8); address_raw |= (uint)Marshal.ReadByte (rdata, 0); address = new IPAddress(address_raw); } else if(rdlen == 16) { byte [] address_raw = new byte[rdlen]; Marshal.Copy(rdata, address_raw, 0, rdlen); address = new IPAddress(address_raw, interfaceIndex); } else { break; } if(hostentry == null) { hostentry = new IPHostEntry(); hostentry.HostName = hosttarget; } if(hostentry.AddressList != null) { ArrayList list = new ArrayList(hostentry.AddressList); list.Add(address); hostentry.AddressList = list.ToArray(typeof(IPAddress)) as IPAddress []; } else { hostentry.AddressList = new IPAddress [] { address }; } ServiceResolvedEventHandler handler = Resolved; if(handler != null) { handler(this, new ServiceResolvedEventArgs(this)); } break; case ServiceType.TXT: if(TxtRecord != null) { TxtRecord.Dispose(); } TxtRecord = new TxtRecord(rdlen, rdata); break; default: break; } sdRef.Deallocate(); }