Search Results

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

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

  • Importing into a Exported object with MEF

    - by Nathan W
    I'm sorry if this question has already been asked 100 times, but I'm really struggling to get it to work. Say I have have three projects. Core.dll Has common interfaces Shell.exe Loads all modules in assembly folder. References Core.dll ModuleA.dll Exports Name, Version of module. References Core.dll Shell.exe has a [Export] that contains an single instance of a third party application that I need to inject into all loaded modules. So far the code that I have in Shell.exe is: static void Main(string[] args) { ThirdPartyApp map = new ThirdPartyApp(); var ad = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var dircatalog = new DirectoryCatalog("."); var a = new AggregateCatalog(dircatalog, ad); // Not to sure what to do here. } class Test { [Export(typeof(ThirdPartyApp))] public ThirdPartyApp Instance { get; set; } [Import(typeof(IModule))] public IModule Module { get; set; } } I need to create a instance of Test, and load Instance with map from the Main method then load the Module from ModuleA.dll that is in the executing directory then [Import] Instance into the loaded module. In ModuleA I have a class like this: [Export(IModule)] class Module : IModule { [Import(ThirdPartyApp)] public ThirdPartyApp Instance {get;set;} } I know I'm half way there I just don't know how to put it all together, mainly with loading up test with a instance of map from Main. Could anyone help me with this.

    Read the article

  • Sorting in dataview not happening properly(C#3.0)

    - by Newbie
    I have the following DataTable dt = new DataTable(); dt.Columns.Add("col1", typeof(string)); dt.Columns.Add("col2", typeof(string)); dt.Rows.Add("1", "r1"); dt.Rows.Add("1", "r2"); dt.Rows.Add("1", "r3"); dt.Rows.Add("1", "r4"); dt.Rows.Add("2", "r1"); dt.Rows.Add("2", "r2"); dt.Rows.Add("2", "r3"); dt.Rows.Add("2", "r4"); dt.Rows.Add("3", "r1"); dt.Rows.Add("3", "r2"); dt.Rows.Add("3", "r3"); dt.Rows.Add("3", "r4"); dt.Rows.Add("1", "r1"); dt.Rows.Add("1", "r2"); DataView dv = new DataView(dt); dv.Sort = "col1"; DataTable dResult = dv.Table; I am trying to sort the datatable with the help of dataview so that the result will be 1 r1 1 r2 ... 2 r1 2 r2 ... 3 r1 3 r2 ...... Means all 1's first followed by 2's and 3r's Even I tried with dt.DefaultView.Sort = "col1"; but no luck. But it is not happening. Only the result i am able to view in dv.Sort and not the datatable (dResult) I am using C#3.0. Please help Thanks

    Read the article

  • NHibernate's ISQLQuery returns instances that are of an unexpected type.

    - by Frederik Gheysels
    Hi all, I'm using NHibernate 2.1.2.400, and I'm having an issue with a an ISQLQuery query. The reason why I use an ISQLQuery here, is that this query uses a table for which I have no entity mapped in NHibernate. The query looks like this: ISQLQuery query = session.CreateSQLQuery ( "select p.*, price.* " + "from prestation p left outer join prestationprice price on p.PrestationId = price.PrestationId " + "where p.Id IN ( select id from prestationregistry where ..."); 'Prestationregistry' is the table that is not known by NHibernate (unmapped, so therefore the native SQL Query). my code continues like this: query.AddEntity ("p", typeof(Prestation)); query.AddJoin ("price", typeof(PrestationPrice)); query.SetResultTransformer (Transformers.DistinctRootEntity); var result = query.List(); So far so good. I expect that I'm given a list of 'Prestation' instances as a result of this query, since I declared 'Prestation' as being the root-object that has to be returned by the AddEntity method. I also expect that the PrestationPrices for each Prestation are eagerly loaded by this query (hence the AddJoin method). To my surprise, the List() method returns a collection of PrestationPrice instances instead of Prestation instances. How come ? Am I doing something wrong ? And if so, could you be so kind to tell me what I'm doing wrong ? Edit: Additional Info: When I debug, and put a watch on the 'query' instance, I can see that the queryReturns member of the query contains 2 items: - one NativeSqlQueryRootReturn instance who'se ReturnEntityName is 'Prestation' - one NativeSqlQueryJoinReturn When I do not specify the 'DistinctRootEntity' result transformer, the query returns instances of 'Prestation' instead of PrestationPrice. However, it contains multiple copies of the same instance.

    Read the article

  • Master Detail same View binding controls

    - by pipelinecache
    Hi everyone, say I have a List View with ItemControls. And a Details part that shows the selected Item from List View. Both are in the same xaml page. I tried everything to accomplish it, but what do I miss? <!-- // List --> <ItemsControl ItemsSource="{Binding Path=Model, ElementName=SomeListViewControl, Mode=Default}" SnapsToDevicePixels="True" Focusable="False" IsTabStop="False"> <ItemsControl.ItemTemplate> <DataTemplate> <SomeListView:SomeListItemControl x:Name=listItem/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <!-- // Details --> <Label Content="Begindatum" FontSize="16" VerticalAlignment="Center" Grid.Row="1" Margin="2,0,0,0"/> <TextBox x:Name="Begindatum" Grid.Column="1" Grid.Row="1" Text="{Binding Path=BeginDate, ElementName=listItem,Converter={StaticResource DateTimeConverter}, ConverterParameter=dd-MM-yyyy}" IsEnabled="False" Style="{DynamicResource TextBoxStyle}" MaxLength="30"/> public event EventHandler<DataEventArgs<SomeEntity>> OnOpenSomething; public ObservableCollection<SomeEntity> Model { get { return (ObservableCollection<SomeEntity>)GetValue(ModelProperty); } set { Model.CollectionChanged -= new NotifyCollectionChangedEventHandler(Model_CollectionChanged); SetValue(ModelProperty, value); Model.CollectionChanged += new NotifyCollectionChangedEventHandler(Model_CollectionChanged); UpdateVisualState(); } } public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof(ObservableCollection<SomeEntity>), typeof(SomeListView), new UIPropertyMetadata(new ObservableCollection<SomeEntity>(), new PropertyChangedCallback(ChangedModel))); private static void ChangedModel(DependencyObject source, DependencyPropertyChangedEventArgs e) { SomeListView someListView = source as SomeListView; if (someListView.Model == null) { return; } CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(someListView.Model); } private void Model_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (Model == null) { return; } }

    Read the article

  • WPF - How do I use the UserControl with a dependency property and view model?

    - by user320849
    Hello, My goal is to have a user select a year and a month. Translate the selection into a date and have the user control send the date back to my view model. That part works for me....However, I cannot get the ViewModel's initial date to set those drop downs. public static readonly DependencyProperty Date = DependencyProperty.Register("ReturnDate", typeof(DateTime), typeof(DatePicker), new FrameworkPropertyMetadata{BindsTwoWayByDefault = true,}); public DateTime ReturnDate { get { return Convert.ToDateTime(GetValue(Date)); } set { SetDropDowns(value); SetValue(Date, value); } } The SetDropDowns(value) just sets the selected items on the combo boxes, however, the program never makes it to that method. On the view I am using: <cc1:DatePicker ReturnDate="{Binding Path=StartDate, Mode=TwoWay}" IsStart="True" /> If this has been answered, then my bad. I looked around and didn't see anything that worked for me. Thus, when the program loads how do I get the value from the view model to a method in order to set the combo boxes? Thanks, -Scott

    Read the article

  • How do you deserialize a collection with child collections?

    - by Stuart Helwig
    I have a collection of custom entity objects one property of which is an ArrayList of byte arrays. The custom entity is serializable and the collection property is marked with the following attributes: [XmlArray("Images"), XmlArrayItem("Image",typeof(byte[]))] So I serialize a collection of these custom entities and pass them to a web service, as a string. The web service receives the string and byte array in tact, The following code then attempts to deserialize the collection - back into custom entities for processing... XmlSerializer ser = new XmlSerializer(typeof(List<myCustomEntity>)); StringReader reader = new StringReader(xmlStringPassedToWS); List<myCustomEntity> entities = (List<myCustomEntity>)ser.Deserialize(reader); foreach (myCustomEntity e in entities) { // ...do some stuff... foreach (myChildCollection c in entities.ChildCollection { // .. do some more stuff.... } } I've checked the XML resulting from the initial serialization and it does contain byte array - the child collection, as does the StringReader built above. After the deserialization process, the resulting collection of custom entites is fine, except that each object in the collection does not contain any items in its child collection. (i.e. it doesn't get to "...do some more stuff..." above. Can someone please explain what I am doing wrong? Is it possible to serialize ArrayLists within a generic collection of custom entities?

    Read the article

  • Setting up Inversion of Control (IoC) in ASP.NET MVC with Castle Windsor

    - by Lirik
    I'm going over Sanderson's Pro ASP.NET MVC Framework and in Chapter 4 he discusses Creating a Custom Controller Factory and it seems that the original method, AddComponentLifeStyle or AddComponentWithLifeStyle, used to register controllers is deprecated now: public class WindsorControllerFactory : DefaultControllerFactory { IWindsorContainer container; public WindsorControllerFactory() { container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle"))); // register all the controller types as transient var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where typeof(IController).IsAssignableFrom(t) select t; //[Obsolete("Use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)) instead.")] //IWindsorContainer AddComponentLifeStyle<I, T>(string key, LifestyleType lifestyle) where T : class; foreach (Type t in controllerTypes) { container.Register(Component.For<IController>().ImplementedBy<???>().Named(t.FullName).LifeStyle.Is(LifestyleType.Transient)); } } // Constructs the controller instance needed to service each request protected override IController GetControllerInstance(Type controllerType) { return (IController)container.Resolve(controllerType); } } The new suggestion is to use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)), but I can't figure out how to present the implementing controller type in the ImplementedBy<???>() method. I tried ImplementedBy<t>() and ImplementedBy<typeof(t)>(), but I can't find the appropriate way to pass int he implementing type. Any ideas?

    Read the article

  • GetAccessControl error with NTAccount

    - by Adam Witko
    private bool HasRights(FileSystemRights fileSystemRights_, string fileName_, bool isFile_) { bool hasRights = false; WindowsIdentity WinIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); WindowsPrincipal WinPrincipal = new WindowsPrincipal(WinIdentity); AuthorizationRuleCollection arc = null; if (isFile_) { FileInfo fi = new FileInfo(@fileName_); arc = fi.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryInfo di = new DirectoryInfo(@fileName_); arc = di.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); } foreach (FileSystemAccessRule rule in arc) { if (WinPrincipal.IsInRole(rule.IdentityReference.Value)) { if (((int)rule.FileSystemRights & (int)fileSystemRights_) > 0) { if (rule.AccessControlType == AccessControlType.Allow) hasRights = true; else if (rule.AccessControlType == AccessControlType.Deny) { hasRights = false; break; } } } } return hasRights; } The above code block is causing me problems. When the WinPrincipal.IsInRole(rule.IdentityReference.Value) is executed the following exception occurs: "The trust relationship between the primary domain and the trusted domain failed.". I'm very new to using identities, principles and such so I don't know what's the problem. I'm assuming it's with the use of NTAccount? Thanks

    Read the article

  • Can a WebServiceHost be changed to avoid the use of HttpListener?

    - by sbyse
    I am looking for a way to use a WCF WebServiceHost without having to rely on the HttpListener class and it's associated permission problems (see this question for details). I'm working on a application which communicates locally with another (third-party) application via their REST API. At the moment we are using WCF as an embedded HTTP server. We create a WebServiceHost as follows: String hostPath = "http://localhost:" + portNo; WebServiceHost host = new WebServiceHost(typeof(IntegrationService), new Uri(hostPath)); // create a webhttpbinding for rest/pox and enable cookie support for session management WebHttpBinding webHttpBinding = new WebHttpBinding(); webHttpBinding.AllowCookies = true; ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IIntegrationService), webHttpBinding, ""); host.Open() ChannelFactory<IIntegrationService> cf = new ChannelFactory<IIntegrationService>(webHttpBinding, hostPath); IIntegrationService channel = cf.CreateChannel(); Everything works nicely as long as our application is run as administrator. If we run our application on a machine without administrative privileges the host.Open() will throw an HttpListenerException with ErrorCode == 5 (ERROR_ACCESS_DENIED). We can get around the problem by running httpcfg.exe from the command line but this is a one-click desktop application and that's not really as long term solution for us. We could ditch WCF and write our own HTTP server but I'd like to avoid that if possible. What's the easiest way to replace HttpListener with a standard TCP socket while still using all of the remaining HTTP scaffolding that WCF provides?

    Read the article

  • Multiple exports with MEF does some really heinous stuff -- why, and why is it allowed?

    - by Dave
    I have an interesting situation where I need to do something like this: [Export[typeof(ICandy1)] [Export[typeof(ICandy2)] public class Candy : ICandy2 { ... } where public interface ICandy1 { ... } public interface ICandy2 : ICandy1 { ... } I couldn't find any posts anywhere regarding using multiple [Export] attributes, so I figured, what the hell, might as well try it. At first glance, it actually seemed to work. I have a couple of methods that call into both interfaces of a Candy instance, and it was fine. However, as I started to test the app, I saw that the behavior wasn't right, and when looking at the Output window, I saw that I was getting tons of COMExceptions. I couldn't track down where they were all coming from, but they always occurred when a worker thread was sleeping. I figured that it had to be from the main thread, then, but didn't know how to debug this at all. Nothing should have been going on in the GUI, and I disabled my DispatchTimers just in case -- same thing. Even more strange than the COMExceptions was the really, really erratic behavior when stepping through code. About 30% of the time, when I single stepped, it would pop out of the method, or it would single step over two lines of code! Totally weird stuff that I am not used to seeing. The only thing that changed between working and non-working code was the introduction of MEF through my plugin loading code. So as a test, I changed my plugin assembly to only export one interface, and I hardcoded everything in the app that relied on the other (now not-implemented) interface. And now the COMExceptions are gone, and the weird debugging behavior is gone. Is this something people here have seen before? If MEF is not expected to allow a class to Export multiple interfaces, then shouldn't a CompositionException get raised when composing the parts? Can anyone explain why MEF would cause these weird problems???

    Read the article

  • How to get rid of the 'progress' cursor?

    - by Ivan
    I have an interval that launches an AJAX call to check if there is any update for the page (I imagine that it's similar to the mechanism used by Facebook or StackExchange to check for new notifications). The problem is that this call changes the cursor to the 'progress' or 'busy' cursor (visual problem) and disables to option to click on links (functional problem). I suppose both problems are related. How can get rid of this effect or at least minimize the consequences? Some code: setInterval(function() { try { var mid = $($("ul#alert-messages li.regular")[0]).attr('ref'); call_ajax('/load_alerts', {num:0, id:mid}, function (data) { if (data.ok) { for (var i=0; i<data.result.length; i++) { // .... } // ... } }, function() {}, // Do not show any error for this!! false); // Do not change cursor! } catch (e) {} }, 15000); function call_ajax(url, data, fnSuccess, fnError) { $.ajax({ 'url': url, 'type': 'POST', 'data': data, 'dataType': "json", 'success' : function(data) { if (fnSuccess) { fnSuccess(data); } else { if (typeof data.msg != 'undefined') { topBar(data.msg, typeof data.ok != 'undefined' && data.ok? 'message' : 'error'); } } }, error : function (jqXHR, textStatus, errorThrown) { console.log(errorThrown); if (fnError) { fnError(STR_ERROR_AJAX + textStatus); } else { topBar(STR_ERROR_AJAX + textStatus, 'error'); } } }); }

    Read the article

  • Passing javascript object to webservice via Jquery ajax

    - by kralco626
    I have a webservice that returns an object [WebMethod] public List<User> ContractorApprovals() I also have a webservice that accepcts an object [WebMethod] public bool SaveContractor(Object u) When I make my webservice calls via Jquery: function ServiceCall(method, parameters, onSucess, onFailure) { var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json $.ajax({ type: "POST", url: "services/"+method, data: parms, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { if (typeof onSucess == 'function' || typeof onSucess == 'object') onSucess(msg.d); }, error: function(msg, err) { $("#dialog-error").dialog('open');} }); I can call the first one just fine. My onSucess function gets passed a javascript object exactly structured like my User object on the service. However, I am now having trouble getting the object back to the server. I'm accepting Object as a parameter on the server side so I can't inagine there is an issue there. So I'm thinking something is wrong with the parms on the client side but i'm not sure what... I am doing something to the effect ServiceCall("AuthorizationManagerWorkManagement.asmx/ContractorApprovals", "", function(data,args){$("#div").data('user',data[0])}, null) then ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor", $("#div").data('user'), //These also do not work: "{'u': ' + $("#div").data("user") + '}", NOR JSON.stringify({u: userObject}) function(data,args){(alert(data)}, null) I know the first service call works, I can get the data. The second one is causing the "onFailure" method to execute rather then "OnSuccess". Any ideas?

    Read the article

  • WPF Binding to variable / DependencyProperty

    - by Peter
    I'm playing around with WPF Binding and variables. Apparently one can only bind DependencyProperties. I have come up with the following, which works perfectly fine: The code-behind file: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public string Test { get { return (string)this.GetValue(TestProperty); } set { this.SetValue(TestProperty, value); } //set { this.SetValue(TestProperty, "BBB"); } } public static readonly DependencyProperty TestProperty = DependencyProperty.Register( "Test", typeof(string), typeof(MainWindow), new PropertyMetadata("CCC")); private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show(Test); Test = "AAA"; MessageBox.Show(Test); } } XAML: <Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Grid> <TextBox Height="31" HorizontalAlignment="Left" Margin="84,86,0,0" Name="textBox1" VerticalAlignment="Top" Width="152" Text="{Binding Test, Mode=TwoWay, diag:PresentationTraceSources.TraceLevel=High}"/> <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="320,85,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> <TextBox Height="31" HorizontalAlignment="Left" Margin="84,138,0,0" Name="textBox2" Text="{Binding Test, Mode=TwoWay}" VerticalAlignment="Top" Width="152" /> </Grid> The two TextBoxes update one an other. And the Button sets them to "AAA". But now I replaced the Setter function with the one that is commented out (simulating some manipulation of the given value). I would expect that whenever the property value is changed it will be reset to "BBB". It does so when you press the button, that is when you set the property in code. But it does for some reason not affect the WPF Bindings, that is you can change the TextBox contents and thus the property, but apparently the Setter is never called. I wonder why that is so, and how one would go about to achive the expected behaviour.

    Read the article

  • Reading a C/C++ data structure in C# from a byte array

    - by Chris Miller
    What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12];} And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]public struct NewStuff{ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking;} What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle;NewStuff MyStuff;int BufferSize = Marshal.SizeOf(typeof(NewStuff));byte[] buff = new byte[BufferSize];Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);handle = GCHandle.Alloc(buff, GCHandleType.Pinned);MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));handle.Free(); Is there better way to accomplish this?

    Read the article

  • C# function called after dependency property have been set

    - by mizipzor
    My code currently looks like this: private Foo myFoo; public Foo CurrentFoo { get { return myFoo; } set { SetFoo(value); } } private void SetFoo(Foo newFoo) { // Do stuff // Here be dragons myFoo = newFoo; } To be able to bind it in XAML/WPF I need to turn Foo into a dependency property: public static DependencyProperty CurrentFooProperty = DependencyProperty.Register("CurrentFoo", typeof(Foo), typeof(FooHandler), new PropertyMetadata(false)); public Foo CurrentFoo { get { return (Foo)GetValue(CurrentFooProperty); } set { SetValue(CurrentFooProperty, value); } } Ive heard that you shouldnt do magic inside the actual C# property set {}, since it might not be called but the value is written directly to the dependency property. If this is false, let me know, it seems like the most obvious and simple route to take. I know I can add a validation function to the dependency property but I assume that it shouldnt be used for this? I need to communicate the change to legacy systems that cannot yet be bound in XAML. Whats the best way to approach this problem?

    Read the article

  • User Control - dependency property to Change Image Issues

    - by mflair2000
    i'm having issues setting the Image from a dependency property. It seems like the trigger doesnt fire. I just want hide/show and image, or set the source if possible. public static readonly DependencyProperty HasSingleValueProperty = DependencyProperty.Register("HasSingleValue", typeof(bool), typeof(LevelControl), new FrameworkPropertyMetadata(false,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public bool HasSingleValue { get { return (bool)GetValue(HasSingleValueProperty); } set { SetValue(HasSingleValueProperty, value); } } public LevelControl() { this.InitializeComponent(); //this.DataContext = this; LayoutRoot.DataContext = this; } //Control Markup <Grid x:Name="LayoutRoot"> <Image x:Name="xGreenBarClientTX" HorizontalAlignment="Stretch" Height="13" Margin="7,8.5,7,0" Stretch="Fill" VerticalAlignment="Top" Width="47" Canvas.Left="181.67" d:LayoutOverrides="Height" > <Image.Style> <Style TargetType="{x:Type Image}"> <Style.Triggers> <DataTrigger Binding="{Binding HasSingleValue}" Value="True"> <Setter Property="Opacity" Value="100"/> </DataTrigger> <DataTrigger Binding="{Binding HasSingleValue}" Value="False"> <Setter Property="Opacity" Value="0"/> </DataTrigger> </Style.Triggers> </Style> </Image.Style> </Image>

    Read the article

  • Calling private constructors with Reflection.Emit?

    - by Jakob Botsch Nielsen
    I'm trying to emit the following IL: LocalBuilder pointer = il.DeclareLocal(typeof(IntPtr)); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Stloc, pointer); il.Emit(OpCodes.Ldloca, pointer); il.Emit(OpCodes.Call, typeof(IntPtr).GetMethod("ToPointer")); il.Emit(OpCodes.Ret); The delegate I bind with has the signature void* TestDelegate(IntPtr ptr) It throws the exception Operation could destabilize the runtime. Anyone knows what's wrong? EDIT: Alright, so I got the IL working now. The entire goal of this was to be able to call a private constructor. The private constructor takes a pointer so I can't use normal reflection. Now.. When I call it, I get an exception saying Attempt by method <built method> to access method <private constructor> failed. Apparently it's performing security checks - but from experience I know that Reflection is able to do private stuff like this normally, so hopefully there is a way to disable that check?

    Read the article

  • What to pass parameters to start an workflow through WCF

    - by Rubens Farias
    It's possible to define some start values to an workflow using WorkflowInstance.CreateWorkflow, like this: using(WorkflowRuntime runtime = new WorkflowRuntime()) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("First", "something"); parameters.Add("Second", 42); WorkflowInstance instance = runtime.CreateWorkflow(typeof(MyStateMachineWorkflow), parameters); instance.Start(); waitHandle.WaitOne(); } This way, a MyStateMachineWorkflow instance is created and First and Second public properties gets that dictionary values. But I'm using WCF; so far, I managed to create a Start method which accepts that two arguments and I set that required fields by using bind on my ReceiveActivity: using (WorkflowServiceHost host = new WorkflowServiceHost(typeof(MyStateMachineWorkflow))) { host.Open(); ChannelFactory<IMyStateMachineWorkflow> factory = new ChannelFactory<IMyStateMachineWorkflow>("MyStateMachineWorkflow"); IMyStateMachineWorkflow proxy = factory.CreateChannel(); // set this values through binding on my ReceiveActivity proxy.Start("something", 42); } While this works, that create an anomaly: that method should be called only and exactly once. How can I start an workflow instance through WCF passing those arguments? On my tests, I just actually interact with my workflow through wire after I call that proxy method. Is there other way?

    Read the article

  • JS: Object itteration fails

    - by Newbie
    Hello! In my JS, I have an object called box_object. It looks like this: ({ id:"3", text:"this is a box object", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", linepoint:"bottom"}, 1:{id:"6", linepoint:"bottom"}}, connectiondata_parent:{ 0:{id:"1", linepoint:"top"}, 1:{id:"2", linepoint:"top"}} }) Now, I want to add some position values to box_object.connectiondata_parent. Using jQuery I can use the .each() method. So I tried it, but it failed. In my function I do the following: $(box_object.connectiondata_parent).each(function(it, obj){ if(typeof(obj[it]) != "undefined" && obj[it].linepoint == "top"){ var point_position_top = new Object(); point_position_top.left = startingpoint_left; point_position_top.top = startingpoint_top; obj[it].position = point_position_top; }else if(typeof(obj[it]) != "undefined" && obj[it].linepoint == "bottom"){ var point_position_bottom = new Object(); point_position_bottom.left = startingpoint_left; point_position_bottom.top = startingpoint_bottom; obj[it].position = point_position_bottom; }else{} }); After the function my box_object looks like this: ({ id:"3", text:"this is third box", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", linepoint:"bottom"}, 1:{id:"6", linepoint:"bottom"}}, connectiondata_parent:{ 0:{id:"1", linepoint:"top", position:{left:500, top:104}}, 1:{id:"2", linepoint:"top"}} }) It seems it only writes the values to the first "value". Any Ideas why?

    Read the article

  • Why does my jQuery/YQL call not return anything?

    - by tastyapple
    I'm trying to access YQL with jQuery but am not getting a response: http://jsfiddle.net/tastyapple/grMb3/ Anyone know why? $(function(){ $.extend( { _prepareYQLQuery: function (query, params) { $.each( params, function (key) { var name = "#{" + key + "}"; var value = $.trim(this); if (!value.match(/^[0-9]+$/)) { value = '"' + value + '"'; } query = query.replace(name, value); } ); return query; }, yql: function (query) { var $self = this; var successCallback = null; var errorCallback = null; if (typeof arguments[1] == 'object') { query = $self._prepareYQLQuery(query, arguments[1]); successCallback = arguments[2]; errorCallback = arguments[3]; } else if (typeof arguments[1] == 'function') { successCallback = arguments[1]; errorCallback = arguments[2]; } var doAsynchronously = successCallback != null; var yqlJson = { url: "http://query.yahooapis.com/v1/public/yql", dataType: "jsonp", success: successCallback, async: doAsynchronously, data: { q: query, format: "json", env: 'store://datatables.org/alltableswithkeys', callback: "?" } } if (errorCallback) { yqlJson.error = errorCallback; } $.ajax(yqlJson); return $self.toReturn; } } ); $.yql( "SELECT * FROM github.repo WHERE id='#{username}' AND repo='#{repository}'", { username: "jquery", repository: "jquery" }, function (data) { if (data.results.repository["open-issues"].content > 0) { alert("Hey dude, you should check out your new issues!"); } } ); });

    Read the article

  • Cannont Update control in WPF custom control

    - by Fazi
    I have created a custom control which holds a button in it. The button is styled, so as to hold a grid with two rows, an image in the first and a TextBlock in the second. I have written an Event Handler for the custom control. When the mouse enters the path of the object the MouseEnter event fires, where I try to change the TextBlock's FontSize and Foreground color, however the control does not update. In contrast, I have tried to modify an regular TextBlock's(not part a custom control and controltemplate) properties, and they update correctly, on the fly. What am I missing here?? Here is the code for the event handler: private void ThemeButton_MouseEnter(object sender, MouseEventArgs e) { InitializeProperties(); TextElement.FontSize = 16; TextElement.Text = "new text"; TextElement.Foreground = Brushes.Red; TextBlock element = MainWindow.FindChild<TextBlock>(MainWindow.StartWindow, "textField"); element.Text = "new text for regular textblock"; element.Foreground = Brushes.Red; } InitializeProperties is a methid that initializes TextElement(typeof TextBlock) and ImageElement(typeof Image) properties. They are not null. The properties are just regular .NET properties.

    Read the article

  • TypeError when using v 0.8.1 of FLOT library, but no error with v. 0.7

    - by DanielAttard
    I need some help to figure out why I am getting an error when trying to create a simple graph using the jQuery FLOT library. When I reference version 0.7 of the FLOT library, the page renders correctly: http://attardpropertytax.ca/flot07.html But when I switch to version 0.8.1 of the FLOT library, the page returns an error saying: Uncaught TypeError: Cannot read property 'left' of null http://attardpropertytax.ca/flot81.html The HTML is the same for both pages, so I cannot figure out why the new version 0.8.1 of FLOT returns an error, but the old version 0.7 does not. Any ideas? I somehow stumbled across a work-around that managed to fix my problem. I'm nut sure why, but I had to comment-out the following two sections of code from the v. 0.8.1 FLOT library: This was the first spot: // If the grid is visible, add its border width to the offset for (var a in plotOffset) { if(typeof(options.grid.borderWidth) == "object") { plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0; } else { plotOffset[a] += showGrid ? options.grid.borderWidth : 0; } } And this was the second spot: if (isNaN(v) || v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0) && (v == axis.min || v == axis.max))) continue; I'm sure eventually @DNS will be taking a look at this question and maybe he will be able to help me understand what is going wrong with my code. Thanks.

    Read the article

  • Factorial function - design and test.

    - by lukas
    I'm trying to nail down some interview questions, so I stared with a simple one. Design the factorial function. This function is a leaf (no dependencies - easly testable), so I made it static inside the helper class. public static class MathHelper { public static int Factorial(int n) { Debug.Assert(n >= 0); if (n < 0) { throw new ArgumentException("n cannot be lower that 0"); } Debug.Assert(n <= 12); if (n > 12) { throw new OverflowException("Overflow occurs above 12 factorial"); } //by definition if (n == 0) { return 1; } int factorialOfN = 1; for (int i = 1; i <= n; ++i) { //checked //{ factorialOfN *= i; //} } return factorialOfN; } } Testing: [TestMethod] [ExpectedException(typeof(OverflowException))] public void Overflow() { int temp = FactorialHelper.MathHelper.Factorial(40); } [TestMethod] public void ZeroTest() { int factorialOfZero = FactorialHelper.MathHelper.Factorial(0); Assert.AreEqual(1, factorialOfZero); } [TestMethod] public void FactorialOf5() { int factOf5 = FactorialHelper.MathHelper.Factorial(5); Assert.AreEqual(120,factOf5); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void NegativeTest() { int factOfMinus5 = FactorialHelper.MathHelper.Factorial(-5); } I have a few questions: Is it correct? (I hope so ;) ) Does it throw right exceptions? Should I use checked context or this trick ( n 12 ) is ok? Is it better to use uint istead of checking for negative values? Future improving: Overload for long, decimal, BigInteger or maybe generic method? Thank you

    Read the article

  • Why are we getting a WCF "Framing error" on some machines but not others

    - by Ian Ringrose
    We have just found we are getting “framing errors” (as reported by the WCF logs) when running our system on some customer test machine. It all works ok on our development machines. We have an abstract base class, with KnownType attributes for all its sub classes. One of it’s subclass is missing it’s DataContract attribute. However it all worked on our test machine! On the customers test machine, we got “framing error” showing up the WCF logs, this is not the error message I have seen in the past when missing a DataContract attribute, or a KnownType attribute. I wish to get to the bottom of this, as we can no longer have confidence in our ability to test the system before giving it to the customer until we can make our machines behave the some as the customer’s machines. Code that try to show what I am talking about, (not the real code) [DataContract()] [KnownType(typeof(SubClass1))] [KnownType(typeof(SubClass2))] // other subclasses with data members public abstract class Base { [DataMember] public int LotsMoreItemsThenThisInRealLife; } /// <summary> /// This works on some machines (not not others) when passed to Contract::DoIt, /// note the missing [DataContract()] /// </summary> public class SubClass1 : Base { // has no data members } /// <summary> /// This works in all cases when passed to Contract::DoIt /// </summary> [DataContract()] public class SubClass2 : Base { // has no data members } public interface IContract { void DoIt(Base[] items); } public static class MyProgram { public static IContract ConntectToServerOverWCF() { // lots of code ... return null; } public static void Startup() { IContract server = ConntectToServerOverWCF(); // this works all of the time server.DoIt(new Base[]{new SubClass2(){LotsMoreItemsThenThisInRealLife=2}}); // this works "in develperment" e.g. on our machines, but not on the customer's test machines! server.DoIt(new Base[] { new SubClass1() { LotsMoreItemsThenThisInRealLife = 2 } }); } }

    Read the article

  • Ninject: How do I inject into a class library ?

    - by DennyDotNet
    To start I'm using Ninject 1.5. I have two projects: Web project and a Class library. My DI configuration is within the Web project. Within my class library I have the following defined: public interface ICacheService<T> { string Identifier { get; } T Get(); void Set( T objectToCache, TimeSpan timeSpan ); bool Exists(); } And then a concrete class called CategoryCacheService. In my web project I bind the two: Bind( typeof( ICacheService<List<Category>> ) ).To( typeof(CategoryCacheService)).Using<SingletonBehavior>(); In my class library I have extension methods for the HtmlHelper class, for example: public static class Category { [Inject] public static ICacheService Categories { get; set; } public static string RenderCategories(this HtmlHelper htmlHelper) { var c = Categories.Get(); return string.Join(", ", c.Select(s = s.Name).ToArray()); } } I've been told that you cannot inject into static properties, instead I should use Kernel.Get<() - However... Since the code above is in a class library I don't have access to the Kernel. How can I get the Kernel from this point or is there a better way of doing this? Thanks!

    Read the article

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