Search Results

Search found 1919 results on 77 pages for 'typeof'.

Page 24/77 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • What is the best way to attach static methods to classes rather than to instances of a class?

    - by John Gietzen
    If I have a method for calculating the greatest common divisor of two integers as: public static int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } What would be the best way to attach that to the System.Math class? Here are the three ways I have come up with: public static int GCD(this int a, int b) { return b == 0 ? a : b.GCD(a % b); } // Lame... var gcd = a.GCD(b); and: public static class RationalMath { public static int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } } // Lame... var gcd = RationalMath.GCD(a, b); and: public static int GCD(this Type math, int a, int b) { return b == 0 ? a : typeof(Math).GCD(b, a % b); } // Neat? var gcd = typeof(Math).GCD(a, b); The desired syntax is Math.GCD since that is the standard for all mathematical functions. Any suggestions? What should I do to get the desired syntax?

    Read the article

  • What is the best way to attach extenstion methods to static classes rather than to instances of a cl

    - by John Gietzen
    If I have a method for calculating the greatest common divisor of two integers as: public static int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } What would be the best way to attach that to the System.Math class? Here are the three ways I have come up with: public static int GCD(this int a, int b) { return b == 0 ? a : b.GCD(a % b); } // Lame... var gcd = a.GCD(b); and: public static class RationalMath { public static int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } } // Lame... var gcd = RationalMath.GCD(a, b); and: public static int GCD(this Type math, int a, int b) { return b == 0 ? a : typeof(Math).GCD(b, a % b); } // Neat? var gcd = typeof(Math).GCD(a, b); The desired syntax is Math.GCD since that is the standard for all mathematical functions. Any suggestions? What should I do to get the desired syntax?

    Read the article

  • How can I inject multiple repositories in a NServicebus message handler?

    - by Paco
    I use the following: public interface IRepository<T> { void Add(T entity); } public class Repository<T> { private readonly ISession session; public Repository(ISession session) { this.session = session; } public void Add(T entity) { session.Save(entity); } } public class SomeHandler : IHandleMessages<SomeMessage> { private readonly IRepository<EntityA> aRepository; private readonly IRepository<EntityB> bRepository; public SomeHandler(IRepository<EntityA> aRepository, IRepository<EntityB> bRepository) { this.aRepository = aRepository; this.bRepository = bRepository; } public void Handle(SomeMessage message) { aRepository.Add(new A(message.Property); bRepository.Add(new B(message.Property); } } public class MessageEndPoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization { public void Init() { ObjectFactory.Configure(config => { config.For<ISession>() .CacheBy(InstanceScope.ThreadLocal) .TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<ISessionFactory>().OpenSession()); config.ForRequestedType(typeof(IRepository<>)) .TheDefaultIsConcreteType(typeof(Repository<>)); } } My problem with the threadlocal storage is, is that the same session is used during the whole application thread. I discovered this when I saw the first level cache wasn't cleared. What I want is using a new session instance, before each call to IHandleMessages<.Handle. How can I do this with structuremap? Do I have to create a message module?

    Read the article

  • How to get around the jslint error 'Don't make functions within a loop.'

    - by Ernelli
    I am working on making all of our JS code pass through jslint, sometimes with a lot of tweaking with the options to get legacy code pass for now on with the intention to fix it properly later. There is one thing that jslint complains about that I do not have a workround for. That is when using constructs like this, we get the error 'Don't make functions within a loop.' for (prop in newObject) { // Check if we're overwriting an existing function if (typeof newObject[prop] === "function" && typeof _super[prop] === "function" && fnTest.test(newObject[prop])) { prototype[prop] = (function (name, func) { return function () { var result, old_super; old_super = this._super; this._super = _super[name]; result = func.apply(this, arguments); this._super = old_super; return result; }; })(prop, newObject[prop]); } This loop is part of a JS implementation of classical inheritance where classes that extend existing classes retain the super property of the extended class when invoking a member of the extended class. Just to clarify, the implementation above is inspired by this blog post by John Resig. But we also have other instances of functions created within a loop. The only workaround so far is to exclude these JS files from jslint, but we would like to use jslint for code validation and syntax checking as part of our continuous integration and build workflow. Is there a better way to implement functionality like this or is there a way to tweak code like this through jslint?

    Read the article

  • How to disable auto-generated WCF configuration

    - by user351025
    Every time my program runs vs adds the default configuration to my app.config file. At that run it works fine, but at the next run it actually tries to read the config. The problem is that the default configuration has errors, it adds the attribute "Address", but attritbutes are not allowed to have capitals so it throws an exception. This means I have to remove the bad section every run! I've tried to configure the .config but it gives errors. Here is the code that I use to host the server: private static System.Threading.AutoResetEvent stopFlag = new System.Threading.AutoResetEvent(false); ServiceHost host = new ServiceHost(typeof(Service), new Uri("http://localhost:8000")); host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "ChessServer"); host.Open(); stopFlag.WaitOne(); host.Close(); Here is the client code that calls the server: ChannelFactory<IChessServer> scf; scf = new ChannelFactory<IService> (new BasicHttpBinding(), "http://localhost:8000"); IService service = scf.CreateChannel(); Thanks for any help.

    Read the article

  • "Ambigous type variable" error when defining custom "read" function

    - by Tener
    While trying to compile the following code, which is enhanced version of read build on readMay from Safe package. readI :: (Typeable a, Read a) => String -> a readI str = case readMay str of Just x -> x Nothing -> error ("Prelude.read failed, expected type: " ++ (show (typeOf > (undefined :: a))) ++ "String was: " ++ str) I get an error from GHC: WavefrontSimple.hs:54:81: Ambiguous type variable `a' in the constraint: `Typeable a' arising from a use of `typeOf' at src/WavefrontSimple.hs:54:81-103 Probable fix: add a type signature that fixes these type variable(s)` I don't understand why. What should be fixed to get what I meant? EDIT: Ok, so the solution to use ScopedTypeVariables and forall a in type signature works. But why the following produces very similar error to the one above? The compiler should infer the right type since there is asTypeOf :: a -> a -> a used. readI :: (Typeable a, Read a) => String -> a readI str = let xx = undefined in case readMay str of Just x -> x `asTypeOf` xx Nothing -> error ("Prelude.read failed, expected type: " ++ (show (typeOf xx)) ++ "String was: " ++ str)

    Read the article

  • MVVM- How can I bind to a property, which is not a DependancyProperty?

    - by highone
    I have found this question http://stackoverflow.com/questions/2245928/mvvm-and-the-textboxs-selectedtext-property. However, I am having trouble getting the solution given to work. This is my non-working code: View: SelectedText and Text are just string properties from my ViewModel. <TextBox Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}" Height="155" HorizontalAlignment="Left" Margin="68,31,0,0" Name="textBox1" VerticalAlignment="Top" Width="264" AcceptsReturn="True" AcceptsTab="True" local:TextBoxHelper.SelectedText="{Binding SelectedText, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding SelectedText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Height="154" HorizontalAlignment="Left" Margin="82,287,0,0" Name="textBox2" VerticalAlignment="Top" Width="239" /> TextBoxHelper public static class TextBoxHelper { #region "Selected Text" public static string GetSelectedText(DependencyObject obj) { return (string)obj.GetValue(SelectedTextProperty); } public static void SetSelectedText(DependencyObject obj, string value) { obj.SetValue(SelectedTextProperty, value); } // Using a DependencyProperty as the backing store for SelectedText. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.RegisterAttached( "SelectedText", typeof(string), typeof(TextBoxHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedTextChanged)); private static void SelectedTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { TextBox tb = obj as TextBox; if (tb != null) { if (e.OldValue == null && e.NewValue != null) { tb.SelectionChanged += tb_SelectionChanged; } else if (e.OldValue != null && e.NewValue == null) { tb.SelectionChanged -= tb_SelectionChanged; } string newValue = e.NewValue as string; if (newValue != null && newValue != tb.SelectedText) { tb.SelectedText = newValue as string; } } } static void tb_SelectionChanged(object sender, RoutedEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { SetSelectedText(tb, tb.SelectedText); } } #endregion } What am I doing wrong?

    Read the article

  • How do I add a default namespace with no prefix using XMLSerializer

    - by OldBob
    Hi Using C# and .Net 3.5; I am trying to generate an XML document that contains the default namespace without a prefix using XMLSerializer. eg. <?xml version="1.0" encoding="utf-8" ?> <MyRecord ID="9266" xmlns="http://www.website.com/MyRecord"> <List> <SpecificItem> using the following code string xmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord)); XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces(); xmlnsEmpty.Add(string.Empty, string.Empty); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray()); and class structure [Serializable] [XmlRoot("MyRecord")] public class ExportMyRecord { [XmlAttribute("ID")] public int ID { get; set; } Now, I've tried various options XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord),"http://www.website.com/MyRecord"); or [XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")] gives me <?xml version="1.0" encoding="utf-8"?> <q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord"> <q1:List> <q1:SpecificItem> I need the XML to have the namespace without the prefix as it's going to a third party provider and they reject all other alternatives. Any suggestions? No responses so far. Has anyone experienced this or know how to solve it?

    Read the article

  • Localizing DataAnnotations Custom Validator

    - by Gabe G
    Hello SO, I'm currently working in an MVC 2 app which has to have everything localized in n-languages (currently 2, none of them english btw). I validate my model classes with DataAnnotations but when I wanted to validate a DateTime field found out that the DataTypeAttribute returns always true, no matter it was a valid date or not (that's because when I enter a random string "foo", the IsValid() method checks against "01/01/0001 ", dont know why). Decided to write my own validator extending ValidationAtribute class: public class DateTimeAttribute : ValidationAttribute { public override bool IsValid(object value) { DateTime result; if (value.ToString().Equals("01/01/0001 0:00:00")) { return false; } return DateTime.TryParse(value.ToString(), out result); } } Now it checks OK when is valid and when it's not, but my problem starts when I try to localize it: [Required(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_Required")] [CustomValidation.DateTime(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_DataType")] public DateTime INS_DATA { get; set; } If I put nothing in the field I get a localized MSG (MSG being my resource class) for the key=INS_DATA_Required but if I put a bad-formatted date I get the "The value 'foo' is not valid for INS_DATA" default message and not the localized MSG. What am I misssing?

    Read the article

  • Resolving Circular References for Objects Implementing ISerializable

    - by Chris
    I'm writing my own IFormatter implementation and I cannot think of a way to resolve circular references between two types that both implement ISerializable. Here's the usual pattern: [Serializable] class Foo : ISerializable { private Bar m_bar; public Foo(Bar bar) { m_bar = bar; m_bar.Foo = this; } public Bar Bar { get { return m_bar; } } protected Foo(SerializationInfo info, StreamingContext context) { m_bar = (Bar)info.GetValue("1", typeof(Bar)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("1", m_bar); } } [Serializable] class Bar : ISerializable { private Foo m_foo; public Foo Foo { get { return m_foo; } set { m_foo = value; } } public Bar() { } protected Bar(SerializationInfo info, StreamingContext context) { m_foo = (Foo)info.GetValue("1", typeof(Foo)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("1", m_foo); } } I then do this: Bar b = new Bar(); Foo f = new Foo(b); bool equal = ReferenceEquals(b, b.Foo.Bar); // true // Serialise and deserialise b equal = ReferenceEquals(b, b.Foo.Bar); If I use an out-of-the-box BinaryFormatter to serialise and deserialise b, the above test for reference-equality returns true as one would expect. But I cannot conceive of a way to achieve this in my custom IFormatter. In a non-ISerializable situation I can simply revisit "pending" object fields using reflection once the target references have been resolved. But for objects implementing ISerializable it is not possible to inject new data using SerializationInfo. Can anyone point me in the right direction?

    Read the article

  • "Pattern matching" of algebraic type data constructors

    - by jetxee
    Let's consider a data type with many constructors: data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int I want to write a function to check if two values are produced with the same constructor: sameK (Alpha _) (Alpha _) = True sameK (Beta _) (Beta _) = True sameK (Gamma _ _) (Gamma _ _) = True sameK _ _ = False Maintaining sameK is not much fun, it is potentially buggy. For example, when new constructors are added to T, it's easy to forget to update sameK. I omitted one line to give an example: -- it’s easy to forget: -- sameK (Delta _) (Delta _) = True The question is how to avoid boilerplate in sameK? Or how to make sure it checks for all T constructors? The workaround I found is to use separate data types for each of the constructors, deriving Data.Typeable, and declaring a common type class, but I don't like this solution, because it is much less readable and otherwise just a simple algebraic type works for me: {-# LANGUAGE DeriveDataTypeable #-} import Data.Typeable class Tlike t where value :: t -> t value = id data Alpha = Alpha Int deriving Typeable data Beta = Beta Int deriving Typeable data Gamma = Gamma Int Int deriving Typeable data Delta = Delta Int deriving Typeable instance Tlike Alpha instance Tlike Beta instance Tlike Gamma instance Tlike Delta sameK :: (Tlike t, Typeable t, Tlike t', Typeable t') => t -> t' -> Bool sameK a b = typeOf a == typeOf b

    Read the article

  • Most efficient way to check for DBNull and then assign to a variable?

    - by ilitirit
    This question comes up occasionally but I haven't seen a satisfactory answer. A typical pattern is (row is a DataRow): if (row["value"] != DBNull.Value) { someObject.Member = row["value"]; } My first question is which is more efficient (I've flipped the condition): row["value"] == DBNull.Value; // Or row["value"] is DBNull; // Or row["value"].GetType() == typeof(DBNull) // Or... any suggestions? This indicates that .GetType() should be faster, but maybe the compiler knows a few tricks I don't? Second question, is it worth caching the value of row["value"] or does the compiler optimize the indexer away anyway? eg. object valueHolder; if (DBNull.Value == (valueHolder = row["value"])) {} Disclaimers: row["value"] exists. I don't know the column index of the column (hence the column name lookup) I'm asking specifically about checking for DBNull and then assignment (not about premature optimization etc). Edit: I benchmarked a few scenarios (time in seconds, 10000000 trials): row["value"] == DBNull.Value: 00:00:01.5478995 row["value"] is DBNull: 00:00:01.6306578 row["value"].GetType() == typeof(DBNull): 00:00:02.0138757 Object.ReferenceEquals has the same performance as "==" The most interesting result? If you mismatch the name of the column by case (eg. "Value" instead of "value", it takes roughly ten times longer (for a string): row["Value"] == DBNull.Value: 00:00:12.2792374 The moral of the story seems to be that if you can't look up a column by it's index, then ensure that the column name you feed to the indexer matches the DataColumn's name exactly. Caching the value also appears to be nearly twice as fast: No Caching: 00:00:03.0996622 With Caching: 00:00:01.5659920 So the most efficient method seems to be: object temp; string variable; if (DBNull.Value != (temp = row["value"]) { variable = temp.ToString(); } This was a good learning experience.

    Read the article

  • WCF Discovery finds endpoint but host is "localhost"

    - by Flo
    I am trying to use the Discovery feature in WCF using http://msdn.microsoft.com/en-us/library/dd456783(v=VS.100).aspx as a starting point. It works fine on my machine, but then I wanted to run the service on a different machine. The service was discovered properly but the hostname of the found service is always "localhost" which is of course not much use. Service Endpoint: var endpointAddress = new EndpointAddress(new UriBuilder { Scheme = Uri.UriSchemeNetTcp, Port = port}.Uri); var endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IServiceInterface)), new NetTcpBinding (), endpointAddress); Client: static EndpointAddress FindServiceAddress<T>() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint()); // Find endpoints FindResponse findResponse = discoveryClient.Find(new FindCriteria(typeof(T))); Console.WriteLine(string.Format("Searched for {0} seconds. Found {1} Endpoint(s).",stopwatch.ElapsedMilliseconds / 1000,findResponse.Endpoints.Count)); if (findResponse.Endpoints.Count > 0) { return findResponse.Endpoints[0].Address; } return null; } Should I simply set the Host to System.Environment.MachineName?

    Read the article

  • Adding IoC Support to my WCF service hosted in a windows service (Autofac)

    - by user137348
    I'd like to setup my WCF services to use an IoC Container. There's an article in the Autofac wiki about WCF integration, but it's showing just an integration with a service hosted in IIS. But my services are hosted in a windows service. Here I got an advice to hook up the opening event http://groups.google.com/group/autofac/browse_thread/thread/23eb7ff07d8bfa03 I've followed the advice and this is what I got so far: private void RunService<T>() { var builder = new ContainerBuilder(); builder.Register(c => new DataAccessAdapter("1")).As<IDataAccessAdapter>(); ServiceHost serviceHost = new ServiceHost(typeof(T)); serviceHost.Opening += (sender, args) => serviceHost.Description.Behaviors.Add( new AutofacDependencyInjectionServiceBehavior(builder.Build(), typeof(T), ??? )); serviceHost.Open(); } The AutofacDependencyInjectionServiceBehavior has a ctor which takes 3 parameters. The third one is of type IComponentRegistration and I have no idea where can I get it from. Any ideas ? Thanks in advance.

    Read the article

  • C# - Class Type as Parameter in methods

    - by Claudio
    Hi guys, I'm using SQLite.cs wrapper for helping me with the database and I have this method for create XML from a table, that is working fine. public void GenerateInvoiceXML(string filePath) { var invoices = app.db.Table<Invoice>().ToList(); XmlSerializer serializer = new XmlSerializer( typeof(List<Invoice>) ); TextWriter writer = new StreamWriter(filePath); serializer.Serialize(writer,invoices); writer.Close(); } All tables that I have are defined like this: [Serializable] public class Invoice { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Supplier {get; set;} public string Date {get; set;} public string PaymentMethod {get; set;} public string Notes {get; set;} public Invoice(int newID) { Id = newID; } public Invoice() { } } But I want to change this method for something like this: public void GenerateInvoiceXML(string filePath, Type table) { var dataForXML = app.db.Table<table>().ToList(); XmlSerializer serializer = new XmlSerializer( typeof(List<table>) ); TextWriter writer = new StreamWriter(filePath); serializer.Serialize(writer,dataForXML); writer.Close(); } Does anybody have an idea how to do it? Kind Regards, Claudio

    Read the article

  • Correct usage of addEventListener() /attachEvent()?

    - by ginny
    Hi guys! I'm wondering how to use "addEventListener" resp. "attachEvent" correctly!? window.onload=function(myFunc1){ // do something } function myFunc2(){ // do something } if (window.addEventListener){ window.addEventListener('load', myFunc2, false); } else if (window.attachEvent){ window.attachEvent('onload', myFunc2); } ... or function myFunc1(){ // do something } if (window.addEventListener){ window.addEventListener('load', myFunc1, false); } else if (window.attachEvent){ window.attachEvent('onload', myFunc1); } function myFunc2(){ // do something } if (window.addEventListener){ window.addEventListener('load', myFunc2, false); } else if (window.attachEvent){ window.attachEvent('onload', myFunc2); } ... ? Is this cross-browser secure or should I better go with sth. like this: function myFunc1(){ // do something } function myFunc2(){ // do something } ... function addOnloadEvent(fnc){ if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", fnc, false ); else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", fnc ); } else { if ( window.onload != null ) { var oldOnload = window.onload; window.onload = function ( e ) { oldOnload( e ); window[fnc](); }; } else window.onload = fnc; } } addOnloadEvent(myFunc1); addOnloadEvent(myFunc2); ... AND: Say "myfunc2" is for IE 7 only. How to modify the correct/preferred method accordingly? Thank you so much!

    Read the article

  • jquery ready function: script not detecting a function

    - by deostroll
    There is a web page with place holder (a normal div). Via ajax calls I am loading a <form> and a <script> into the place holder. The script contains necessary javascript to initialize the form (i.e. for e.g. disable the controls so as to make form read-only, etc). Here is a piece of code I have; it works, but the commented part doesn't work. Because the script engine cannot find the object tristate_DisableControl which is a function in one of those scripts I call via ajax. $(document).ready(function() { // $('#site_preferences_content div').each(function() { // if (typeof (window.tristate_DisableControl) == 'undefined') { // if (typeof (window.console) != 'undefnied') // console.log((new Date()).toTimeString() + ' not logable'); // pausecomp(1000); // } // else // tristate_DisableControl(this); // }); //end $('#site_prefrences_content div').each() setTimeout(function() { $('#site_preferences_content div').each(function() { tristate_DisableControl(this); }) }, 1000); }); I thought by the time $(document).ready() executes the DOM will be properly loaded...

    Read the article

  • C# Serialization lock out

    - by Greycrow
    When I try to Serialize a class to an xml file I get the exception: The process cannot access the file 'C:\settings.xml' because it is being used by another process. Settings currentSettings = new Settings(); public void LoadSettings() { //Load Settings from XML file try { Stream stream = File.Open("settings.xml", FileMode.Open); XmlSerializer s = new XmlSerializer(typeof(Settings)); currentSettings = (Settings)s.Deserialize(stream); stream.Close(); } catch //Can't read XML - use default settings { currentSettings.Name = GameSelect.Items[0].ToString(); currentSettings.City = MapSelect.Items[0].ToString(); currentSettings.Country = RaceSelect.Items[0].ToString(); } } public void SaveSettings() { //Save Settings to XML file try { Stream stream = File.Open("settings.xml", FileMode.Create); XmlSerializer x = new XmlSerializer(typeof(Settings)); x.Serialize(stream, currentSettings); stream.Close(); } catch { MessageBox.Show("Unable to open XML File - File in use by other process"); } It appears that when I Deserialize it locks the file for writing back, even if I closed the stream. Thanks in advance.

    Read the article

  • TimeoutException when WCF Host and Client are in the same process

    - by Pharao2k
    I've ran into a really weird problem. I am building a heavily distributed application where each app instance can either be a Host and/or Client to a WCF-Service (very p2p-like). Everything works fine, as long as the Client and the targeted Host (By which I mean the app, not the Host, since currently everything runs on a single computer (so no Firewall problems etc.)) are NOT the same. IF they are the same, then the app hangs for exactly 1 Minute and then throws a TimeoutException. WCF-Logging did not produce anything helpful. Here is a small app which demonstrates the Problem: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { var binding = new NetTcpBinding(); var baseAddress = new Uri(@"net.tcp://localhost:4000/Test"); ServiceHost host = new ServiceHost(typeof(TestService), baseAddress); host.AddServiceEndpoint(typeof(ITestService), binding, baseAddress); var debug = host.Description.Behaviors.Find<ServiceDebugBehavior>(); if (debug == null) host.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); else debug.IncludeExceptionDetailInFaults = true; host.Open(); var clientBinding = new NetTcpBinding(); var testProxy = new TestProxy(clientBinding, new EndpointAddress(baseAddress)); testProxy.Test(); } } [ServiceContract] public interface ITestService { [OperationContract] void Test(); } public class TestService : ITestService { public void Test() { MessageBox.Show("foo"); } } public class TestProxy : ClientBase<ITestService>, ITestService { public TestProxy(NetTcpBinding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public void Test() { Channel.Test(); } } What am I doing wrong? Regards, Pharao2k

    Read the article

  • DeSerialization doesn't work though i Implement GetObjectData method and Constructor

    - by Punit Singhi
    Hi, I have a static generic dictionary in a class. As static memeber cannot serialized so i have implented ISerializable interface and method GetObjectData to serialize. I have a constructor which will also accept SerializationInfo and StreamingContext to deserliaze the dictionay. Now when i try to serialize and deserialize , it always return 1(thoug i added 2 entries). please find the pseduo code- [Serializable] public class MyClass : ISerializable { internal static Dictionary<long, string> dict = new Dictionary<long,string>(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("static.dic", MyClass1.dict, typeof(Dictionary<long, string>)); } public MyClass(SerializationInfo info, StreamingContext context) { MyClass.dict= (Dictionary<long, string>)info.GetValue("static.dic", typeof(Dictionary<long, string>)); } public void Add() { dict.Add(21, "11"); } public MyClass() { dict.Add(21, "11"); } } public class MyClass { MyClass myClass = new MyClass(); public static void Main() { myClass.Add(); FileStream fileStream = new FileStream("test.binary", FileMode.Create); IFormatter bf = new BinaryFormatter(); bf.Serialize(fileStream, myClass); fileStream.Dispose(); fileStream.Close(); fileStream = new FileStream("test.binary", FileMode.Open); bf = new BinaryFormatter(); myClass = (MyClass1)bf.Deserialize(fileStream); } }

    Read the article

  • .NET Remoting Connecting to Wrong Host

    - by Dark Falcon
    I have an application I wrote which has been running well for 4 years. Yesterday they moved all their servers around and installed about 60 pending Windows updates, and now it is broken. The application makes use of remoting to update some information on another server (10.0.5.230), but when I try to create my remote object, I get the following exception: Note that it is trying to connect to 127.0.0.1, not the proper server. The server (10.0.5.230) is listening on port 9091 as it should. This same error is happening on all three terminal servers where this application is installed. Here is the code which registers the remoted object: public static void RegisterClient() { string lServer; RegistryKey lKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Shoreline Teleworks\\ShoreWare Client"); if (lKey == null) throw new InvalidOperationException("Could not find Shoretel Call Manager"); object lVal = lKey.GetValue("Server"); if (lVal == null) throw new InvalidOperationException("Shoretel Call Manager did not specify a server name"); lServer = lVal.ToString(); IDictionary props = new Hashtable(); props["port"] = 0; string s = System.Guid.NewGuid().ToString(); props["name"] = s; ChannelServices.RegisterChannel(new TcpClientChannel(props, null), false); RemotingConfiguration.RegisterActivatedClientType(typeof(UpdateClient), "tcp://" + lServer + ":" + S_REMOTING_PORT + "/"); RemotingConfiguration.RegisterActivatedClientType(typeof(Playback), "tcp://" + lServer + ":" + S_REMOTING_PORT + "/"); } Here is the code which calls the remoted object: UpdateClient lUpdater = new UpdateClient(Settings.CurrentSettings.Extension.ToString()); lUpdater.SetAgentState(false); I have verified that the following URI is passed to RegisterActivatedClientType: "tcp://10.0.5.230:9091/" Why does this application try to connect to the wrong server?

    Read the article

  • C# reflection instantiation

    - by NickLarsen
    I am currently trying to create a generic instance factory for which takes an interface as the generic parameter (enforced in the constructor) and then lets you get instantiated objects which implement that interface from all types in all loaded assemblies. The current implementation is as follows:     public class InstantiationFactory     {         protected Type Type { get; set; }         public InstantiationFactory()         {             this.Type = typeof(T);             if (!this.Type.IsInterface)             {                 // is there a more descriptive exception to throw?                 throw new ArgumentException(/* Crafty message */);             }         }         public IEnumerable GetLoadedTypes()         {             // this line of code found in other stack overflow questions             var types = AppDomain.CurrentDomain.GetAssemblies()                 .SelectMany(a = a.GetTypes())                 .Where(/* lambda to identify instantiable types which implement this interface */);             return types;         }         public IEnumerable GetImplementations(IEnumerable types)         {             var implementations = types.Where(/* lambda to identify instantiable types which implement this interface */                 .Select(x = CreateInstance(x));             return implementations;         }         public IEnumerable GetLoadedImplementations()         {             var loadedTypes = GetLoadedTypes();             var implementations = GetImplementations(loadedTypes);             return implementations;         }         private T CreateInstance(Type type)         {             T instance = default(T);             var constructor = type.GetConstructor(Type.EmptyTypes);             if (/* valid to instantiate test */)             {                 object constructed = constructor.Invoke(null);                 instance = (T)constructed;             }             return instance;         }     } It seems useful to me to have my CreateInstance(Type) function implemented as an extension method so I can reuse it later and simplify the code of my factory, but I can't figure out how to return a strongly typed value from that extension method. I realize I could just return an object:     public static class TypeExtensions     {         public object CreateInstance(this Type type)         {             var constructor = type.GetConstructor(Type.EmptyTypes);             return /* valid to instantiate test */ ? constructor.Invoke(null) : null;         }     } Is it possible to have an extension method create a signature per instance of the type it extends? My perfect code would be this, which avoids having to cast the result of the call to CreateInstance():     Type type = typeof(MyParameterlessConstructorImplementingType);     MyParameterlessConstructorImplementingType usable = type.CreateInstance();

    Read the article

  • How to restart a wcf server from within a client?

    - by djerry
    Hey guys, I'm using Wcf for server - client communication. The server will need to run as a service, so there's no GUI. The admin can change settings using the client program and for those changes to be made on server, it needs to restart. This is my server setup NetTcpBinding binding = new NetTcpBinding(SecurityMode.Message); Uri address = new Uri("net.tcp://localhost:8000"); //_svc = new ServiceHost(typeof(MonitoringSystemService), address); _monSysService = new MonitoringSystemService(); _svc = new ServiceHost(_monSysService, address); publishMetaData(_svc, "http://localhost:8001"); _svc.AddServiceEndpoint(typeof(IMonitoringSystemService), binding, "Monitoring Server"); _svc.Open(); MonitoringSystemService is a class i'm using to handle client - server comm. It looks like this: [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, MaxItemsInObjectGraph = 2147483647)] public class MonitoringSystemService : IMonitoringSystemService {} So i need to call a restart method on the client to the server, but i don't know how to restart (even stop - start) the server. I hope i'm not missing any vital information. Thanks in advance.

    Read the article

  • Dependency Property ListBox

    - by developer
    Hi All, I want to use a dependency property, so that my label displays values selected in the listbox. This is just to more clearly understand the working of a dependency property. <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WPFToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:local="clr-namespace:WpfApplication1" x:Name="MyWindow" Height="200" Width="300" > <StackPanel> <ListBox x:Name="lbColor" Width="248" Height="56" ItemsSource="{Binding TestColor}"/> <StackPanel> <Label Content="{Binding Path=Test, ElementName=lbColor}" /> </StackPanel> </StackPanel> </Window> Code Behind, namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public ObservableCollection<string> TestColor { get; set; } public String Test { get { return (String)GetValue(TestProperty); } set { SetValue(TestProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TestProperty = DependencyProperty.Register("Test", typeof(String), typeof(ListBox), new UIPropertyMetadata("Test1")); public Window1() { InitializeComponent(); TestColor = new ObservableCollection<string>(); DataContext = this; TestColor.Add("Red"); TestColor.Add("Orange"); TestColor.Add("Yellow"); TestColor.Add("Green"); TestColor.Add("Blue"); } } } Can anyone explain me how will I accompalish this using a dependency property. Somehow I am very confused with the Dependency Property concept, and I just wanted to see a working example for that.

    Read the article

  • How can I add the column data type after adding the column headers to my datatable?

    - by Kevin
    Using the code below (from a console app I've cobbled together), I add seven columns to my datatable. Once this is done, how can I set the data type for each column? For instance, column 1 of the datatable will have the header "ItemNum" and I want to set it to be an Int. I've looked at some examples on thet 'net, but most all of them show creating the column header and column data type at once, like this: loadDT.Columns.Add("ItemNum", typeof(Int)); At this point in my program, the column already has a name. I just want to do something like this (not actual code): loadDT.Column[1].ChangeType(typeof(int)); Here's my code so far (that gives the columns their name): // get column headings for datatable by reading first line of csv file. StreamReader sr = new StreamReader(@"c:\load_forecast.csv"); headers = sr.ReadLine().Split(','); foreach (string header in headers) { loadDT.Columns.Add(header); } Obviously, I'm pretty new at this, but trying very hard to learn. Can someone point me in the right direction? Thanks!

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >