Search Results

Search found 577 results on 24 pages for 'delegates'.

Page 9/24 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • LINQ to objects: Is there

    - by Charles
    I cannot seem to find a way to have LINQ return the value from a specified accessor. I know the name of the accessors for each object, but am unsure if it is possible to pass the requested accessor as a variable or otherwise achieve the desired refactoring. Consider the following code snippet: // "value" is some object with accessors like: format, channels, language row = new List<String> { String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.format).ToArray()), String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.channels).ToArray()), String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.language).ToArray()), // ... } I'd like to refactor this into a method that uses the specified accessor, or perhaps pass a delegate, though I don't see how that could work. string niceRefactor(myObj myObject, string /* or whatever type */ ____ACCESSOR) { return String.Join(innerSeparator, (from item in myObject.Audio orderby item.Key ascending select item.Value.____ACCESSOR).ToArray()); } I have written a decent amount of C#, but am still new to the magic of LINQ. Is this the right approach? How would you refactor this?

    Read the article

  • Checking if an object has been released before sending a message to it

    - by Tom Irving
    I've only recently noticed a crash in one of my apps when an object tried to message its delegate and the delegate had already been released. At the moment, just before calling any delegate methods, I run this check: if (delegate && [delegate respondsToSelector:...]){ [delegate ...]; } But obviously this doesn't account for if the delegate isn't nil, but has been deallocated. Besides setting the object's delegate to nil in the delegate's dealloc method, is there a way to check if the delegate has already been released just incase I no longer have a reference to the object.

    Read the article

  • How to prevent duplicates, macro or something?

    - by blez
    Well, the problem is that I've got a lot of code like this for each event passed to the GUI, how can I shortify this? Macros wont do the work I guess. Is there a more generic way to do something like a 'template' ? private delegate void DownloadProgressDelegate(object sender, DownloaderProgressArgs e); void DownloadProgress(object sender, DownloaderProgressArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new DownloadProgressDelegate(DownloadProgress), new object[] { sender, e }); return; } label2.Text = d.speedOutput.ToString(); } private delegate void DownloadSpeedDelegate(object sender, DownloaderProgressArgs e); void DownloadSpeed(object sender, DownloaderProgressArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new DownloadSpeedDelegate(DownloadSpeed), new object[] { sender, e }); return; } string speed = ""; speed = (e.DownloadSpeed / 1024).ToString() + "kb/s"; label3.Text = speed; }

    Read the article

  • C# - Silverlight - Dynamically calling a method

    - by cmaduro
    Is there anyway in C# to call a method based on a Enum and/or class? Say if I were to call Controller<Actions.OnEdit, Customer>(customer); Could I do something like this then? public void Controller<TAction, TParam>(TParam object) { Action<TParam> action = FindLocalMethodName(TAction); action(object); } private Action<T> FindLocalMethodName(Enum method) { //Use reflection to find a metode with //the name corresponding to method.ToString() //which accepts a parameters type T. }

    Read the article

  • How do you pass a generic delegate argument to a method in .NET 2.0 - UPDATED

    - by Seth Spearman
    Hello, I have a class with a delegate declaration as follows... Public Class MyClass Public Delegate Function Getter(Of TResult)() As TResult ''#the following code works. Public Shared Sub MyMethod(ByVal g As Getter(Of Boolean)) ''#do stuff End Sub End Class However, I do not want to explicitly type the Getter delegate in the Method call. Why can I not declare the parameter as follows... ... (ByVal g As Getter(Of TResult)) Is there a way to do it? My end goal was to be able to set a delegate for property setters and getters in the called class. But my reading indicates you can't do that. So I put setter and getter methods in that class and then I want the calling class to set the delegate argument and then invoke. Is there a best practice for doing this. I realize in the above example that I can set set the delegate variable from the calling class...but I am trying to create a singleton with tight encapsulation. For the record, I can't use any of the new delegate types declared in .net35. Answers in C# are welcome. Any thoughts? Seth

    Read the article

  • How to subscribe to EventHandler of a private control outside of Form

    - by randooom
    Hi all, maybe my design is not good, or I don't see the obvious solution, but I want to subscribe to a buttonClick EventHandler of Form1 from outside form1. For example I have a Controller and Form1 who are both instanced in the main function. Now I want to subscribe a function from Controller to the buttonClick event from Button1_Click in Form1. But the button1 is declarded private, so i can't do form1->Button1->Click += gcnew EventHandler(controller->function) Is there any way to get around this? Ok I could write a setter or something in Form1, but is there any other solution? I read some examples, but they are all calling events from within the same class so they don't address my specific problem.

    Read the article

  • Is there a downside to adding an anonymous empty delegate on event declaration?

    - by serg10
    I have seen a few mentions of this idiom (including on SO): // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; The upside is clear - it avoids the need to check for null before raising the event. However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?

    Read the article

  • how to tell which object called a delegate method (objective c)

    - by user353877
    Let's say you have two objects (UITextviews) in your class. When the text view changes, you have a delegate method that catches the change.. but how can you tell programatically WHICH object was changed and called the delegate ?? I have to be missing something, because this should be trivial, but I couldnt find anything. Note: In this case, its not possible to just break up the class to only have one object (there by bypassing ambiguity).. I looked for things like assigned variable names for nsobjects, nothing there

    Read the article

  • How to pass event to method?

    - by tomaszs
    I would like to create a method that takes as a argument an event an adds eventHandler to it to handle it properly. Like this: I have 2 events: public event EventHandler Click; public event EventHandler Click2; Now i would like to pass particular event to my method like this (pseudocode): public AttachToHandleEvent(EventHandler MyEvent) { MyEvent += Item_Click; } private void Item_Click(object sender, EventArgs e) { MessageBox.Show("lalala"); } ToolStripMenuItem tool = new ToolStripMenuItem(); AttachToHandleEvent(tool.Click); Is it possible or do I not understand it good? Edit: I've noticed with help of you that this code worked fine, and returned to my project and noticed that when I pass event declared in my class it works, but when I pass event from other class id still does not work. Updated above example to reflect this issue. What I get is this error: The event 'System.Windows.Forms.ToolStripItem.Click' can only appear on the left hand side of += or -=

    Read the article

  • How to use Delegate in C# for Dictionary<int, List<string>>

    - by Emanuel
    The code: private delegate void ThreadStatusCallback(ReceiveMessageAction action, Dictionary<int, List<string>> message); ... Dictionary<int, List<string>> messagesForNotification = new Dictionary<int, List<string>>(); ... Invoke(new ThreadStatusCallback(ReceivesMessagesStatus), ReceiveMessageAction.Notification , messagesForNotification ); ... private void ReceivesMessagesStatus(ReceiveMessageAction action, object value) { ... } How can I send the two variable of type ReceiveMessageAction respectively Dictionary<int, List<string>> to the ReceivesMessagesStatus method. Thanks.

    Read the article

  • In .NET, what thread will Events be handled in?

    - by Ben
    I have attempted to implement a producer/consumer pattern in c#. I have a consumer thread that monitors a shared queue, and a producer thread that places items onto the shared queue. The producer thread is subscribed to receive data...that is, it has an event handler, and just sits around and waits for an OnData event to fire (the data is being sent from a 3rd party api). When it gets the data, it sticks it on the queue so the consumer can handle it. When the OnData event does fire in the producer, I had expected it to be handled by my producer thread. But that doesn't seem to be what is happening. The OnData event seems as if it's being handled on a new thread instead! Is this how .net always works...events are handled on their own thread? Can I control what thread will handle events when they're raised? What if hundreds of events are raised near-simultaneously...would each have its own thread?

    Read the article

  • how do I set a delegate in a view that is not my main view

    - by orangecl4now
    I have a xib. the xib has a button that swaps another xib. the second xib has a uitextfield and a uilabel. how do I make the keyboard go away when I'm done typing? what do I need to wire or code? the second xib has it's own class (called CustomSign.m) Inside CustomSign.m, I've implemented the following method -(void)textFieldDidEndEditing:(UITextField *)textField { [customText resignFirstResponder]; signedLabel.text = customText.text; } - (void)awakeFromNib { //assume textField is an ivar that is connected to the textfield in IB [customText setDelegate:self]; } I get the following warning Class "CustomSign" does not implement the UITextFieldDelegate protocol

    Read the article

  • Why does a delegate with no parameters compile?

    - by Ryan
    I'm confused why this compiles: private delegate int MyDelegate(int p1, int p2); private void testDelegate() { MyDelegate imp = delegate { return 1; }; } MyDelegate should be a pointer to a method that takes two int parameters and returns another int, right? Why am I allowed to assign a method that takes no parameters? Interestingly, these doesn't compile (it complains about the signature mismatches, as I'd expect) private void testDelegate() { // Missing param MyDelegate imp = delegate(int p1) { return 1; }; // Wrong return type MyDelegate imp2 = delegate(int p1, int p2) { return "String"; }; } Thanks for any help! Ryan

    Read the article

  • Can an asynchronously fired event run synchronously on a form?

    - by cyclotis04
    [VS 2010 Beta with .Net Framework 3.5] I've written a C# component to asynchronously monitor a socket and raise events when data is received. I set the VB form to show message boxes when the event is raised. What I've noticed is that when the component raises the event synchronously, the message box blocks the component code and locks the form until the user closes the message. When it's raised asynchronously, it neither blocks the code, nor locks the form. What I want is a way to raise an event in such a way that it does not block the code, but is called on the same thread as the form (so that it locks the form until the user selects an option.) Can you help me out? Thanks. [Component] using System; using System.Threading; using System.ComponentModel; namespace mySpace { public delegate void SyncEventHandler(object sender, SyncEventArgs e); public delegate void AsyncEventHandler(object sender, AsyncEventArgs e); public class myClass { readonly object syncEventLock = new object(); readonly object asyncEventLock = new object(); SyncEventHandler syncEvent; AsyncEventHandler asyncEvent; private delegate void WorkerDelegate(string strParam, int intParam); public void DoWork(string strParam, int intParam) { OnSyncEvent(new SyncEventArgs()); AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null); WorkerDelegate delWorker = new WorkerDelegate(ClientWorker); IAsyncResult result = delWorker.BeginInvoke(strParam, intParam, null, null); } private void ClientWorker(string strParam, int intParam) { Thread.Sleep(2000); OnAsyncEvent(new AsyncEventArgs()); OnAsyncEvent(new AsyncEventArgs()); } public event SyncEventHandler SyncEvent { add { lock (syncEventLock) syncEvent += value; } remove { lock (syncEventLock) syncEvent -= value; } } public event AsyncEventHandler AsyncEvent { add { lock (asyncEventLock) asyncEvent += value; } remove { lock (asyncEventLock) asyncEvent -= value; } } protected void OnSyncEvent(SyncEventArgs e) { SyncEventHandler handler; lock (syncEventLock) handler = syncEvent; if (handler != null) handler(this, e, null, null); // Blocks and locks //if (handler != null) handler.BeginInvoke(this, e, null, null); // Neither blocks nor locks } protected void OnAsyncEvent(AsyncEventArgs e) { AsyncEventHandler handler; lock (asyncEventLock) handler = asyncEvent; //if (handler != null) handler(this, e, null, null); // Blocks and locks if (handler != null) handler.BeginInvoke(this, e, null, null); // Neither blocks nor locks } } } [Form] Imports mySpace Public Class Form1 Public WithEvents component As New mySpace.myClass() Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click component.DoWork("String", 1) End Sub Private Sub component_SyncEvent(ByVal sender As Object, ByVal e As pbxapi.SyncEventArgs) Handles component.SyncEvent MessageBox.Show("Synchronous event", "Raised:", MessageBoxButtons.OK) End Sub Private Sub component_AsyncEvent(ByVal sender As Object, ByVal e As pbxapi.AsyncEventArgs) Handles component.AsyncEvent MessageBox.Show("Asynchronous event", "Raised:", MessageBoxButtons.OK) End Sub End Class

    Read the article

  • Can i access outer class objects in inner class

    - by Shantanu Gupta
    I have three classes like this. class A { public class innerB { //Do something } public class innerC { //trying to access objB here directly or indirectly over here. //I dont have to create an object of innerB, but to access the object created by A //i.e. innerB objInnerB = objB; //not like this innerB objInnerB= new innerB(); } public innerB objB{get;set;} } I want to access the object of class B in Class C that is created by class A. Is it possible somehow to make changes on object of Class A in Class C. Can i get Class A's object by creating event or anyhow.

    Read the article

  • How to make item view render rich (html) text in PyQt?

    - by Giorgio Gelardi
    I'm trying to translate code from this thread in python: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * __data__ = [ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ] def get_html_box(text): return '''<table border="0" width="100%"><tr width="100%" valign="top"> <td width="1%"><img src="softwarecenter.png"/></td> <td><table border="0" width="100%" height="100%"> <tr><td><b><a href="http://www.google.com">titolo</a></b></td></tr> <tr><td>{0}</td></tr><tr><td align="right">88/88/8888, 88:88</td></tr> </table></td></tr></table>'''.format(text) class HTMLDelegate(QStyledItemDelegate): def paint(self, painter, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) painter.save() ctx = QAbstractTextDocumentLayout.PaintContext() ctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height()) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore() def sizeHint(self, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) class MyListModel(QAbstractListModel): def __init__(self, parent=None, *args): super(MyListModel, self).__init__(parent, *args) self.listdata = __data__ def rowCount(self, parent=QModelIndex()): return len(self.listdata) def data(self, index, role=Qt.DisplayRole): return index.isValid() and QVariant(self.listdata[index.row()]) or QVariant() class MyWindow(QWidget): def __init__(self, *args): super(MyWindow, self).__init__(*args) # listview self.lv = QListView() self.lv.setModel(MyListModel(self)) self.lv.setItemDelegate(HTMLDelegate(self)) self.lv.setResizeMode(QListView.Adjust) # layout layout = QVBoxLayout() layout.addWidget(self.lv) self.setLayout(layout) if __name__ == "__main__": app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) Element's size and position are not calculated correctly I guess, perhaps because I haven't understand at all the style related parts from original code. Can someone help me?

    Read the article

  • c++/cli pass (managed) delegate to unmanaged code

    - by Ron Klein
    How do I pass a function pointer from managed C++ (C++/CLI) to an unmanaged method? I read a few articles, like this one from MSDN, but it describes two different assemblies, while I want only one. Here is my code: 1) Header (MyInterop.ManagedCppLib.h): #pragma once using namespace System; namespace MyInterop { namespace ManagedCppLib { public ref class MyManagedClass { public: void DoSomething(); }; }} 2) CPP Code (MyInterop.ManagedCppLib.cpp) #include "stdafx.h" #include "MyInterop.ManagedCppLib.h" #pragma unmanaged void UnmanagedMethod(int a, int b, void (*sum)(const int)) { int result = a + b; sum(result); } #pragma managed void MyInterop::ManagedCppLib::MyManagedClass::DoSomething() { System::Console::WriteLine("hello from managed C++"); UnmanagedMethod(3, 7, /* ANY IDEA??? */); } I tried creating my managed delegate and then I tried to use Marshal::GetFunctionPointerForDelegate method, but I couldn't compile.

    Read the article

  • How do I combine similar method calls into a delegate pattern?

    - by Daniel T.
    I have three methods: public void Save<T>(T entity) { using (new Transaction()) { Session.Save(entity); } } public void Create<T>(T entity) { using (new Transaction()) { Session.Create(entity); } } public void Delete<T>(T entity) { using (new Transaction()) { Session.Delete(entity); } } As you can see, the only thing that differs is the method call inside the using block. How can I rewrite this so it's something like this instead: public void Save<T>(T entity) { TransactionWrapper(Session.Save(entity)); } public void Create<T>(T entity) { TransactionWrapper(Session.Create(entity)); } public void Save<T>(T entity) { TransactionWrapper(Session.Save(entity)); } So in other words, I pass a method call as a parameter, and the TransactionWrapper method wraps a transaction around the method call.

    Read the article

  • a constructor as a delegate - is it possible in C#?

    - by akavel
    I have a class like below: class Foo { public Foo(int x) { ... } } and I need to pass to a certain method a delegate like this: delegate Foo FooGenerator(int x); Is it possible to pass the constructor directly as a FooGenerator value, without having to type: delegate(int x) { return new Foo(x); } ? EDIT: For my personal use, the question refers to .NET 2.0, but hints/responses for 3.0+ are welcome as well.

    Read the article

  • NSXMLParser 's delegate and memory leak

    - by dizzy_fingers
    Hello, I am using a NSXMLParser class in my program and I assign a delegate to it. This delegate, though, gets retained by the setDelegate: method resulting to a minor, yet annoying :-), memory leak. I cannot release the delegate class after the setDelegate: because the program will crash. Here is my code: self.parserDelegate = [[ParserDelegate alloc] init]; //retainCount:1 self.xmlParser = [[NSXMLParser alloc] initWithData:self.xmlData]; [self.xmlParser setDelegate:self.parserDelegate]; //retainCount:2 [self.xmlParser parse]; [self.xmlParser release]; ParserDelegate is the delegate class. Of course if I set 'self' as the delegate, I will have no problem but I would like to know if there is a way to use a different class as delegate with no leaks. Thank you in advance.

    Read the article

  • iphone: Implement delegate in class

    - by Nic Hubbard
    I am trying to call up a modal table view controller using presentModalViewController but I am not sure what to do about the delegate. The following code gives me an error: MyRidesListView *controller = [[MyRidesListView alloc] init]; controller.delegate = self; [self presentModalViewController:controller animated:YES]; [controller release]; Error: Request for member 'delegate' is something not a structure or union Now, I realized there is no delegate property in my MyRidesListView class. So, how would I add a reference to my delegate there? What am I missing here?

    Read the article

  • iPhone: Run method from another view

    - by Nic Hubbard
    I have two views that I am loading, the first is a view with an MKMapView, the second has a table view. I would like to access a method in the first views controller, from the second view. I have been told to use the delegate for this, but I can't get it right. In my app delegate, I have set up added properties for the class of my first view. Then, in my second view, I try to access the first view using the delegate: MyAppDelegate *mainDelegate = (MyAppDelegate*) [[UIApplication sharedApplication] delegate]; Then try: [mainDelegate.mapViewControllerClass myMethodToRun]; It seems to me that it should be calling the myMethodToRun method, which is in my map view. But, it does not work. What is wrong with what I am doing here? There must be a way to access a method of another view...

    Read the article

  • Event consumption in WPF

    - by webaloman
    I have a very simple app written in Silverlight for Windows Phone, where I try to use events. In my App.xaml.cs code behind I have implemented a GeoCoordinateWatcher which registers a gCWatche_PositionChanged method. This works ok, method is called after the position has been changed. What I want to do is fire an other event lets say DBUpdatedEvent after DB has been updated in the gCWatche_PositionChanged method. For this i delclared in the App.xaml.cs public delegate void DBUpdateEventHandler(object sender, EventArgs e); and I have in my App class: public event DBUpdateEventHandler DBUpdated; the event is fired like this in the end of gCWatche_PositionChanged method like this: OnDBUpdateEvent(new EventArgs()); and also I have declared : protected virtual void OnDBUpdateEvent(EventArgs e) { if (DBUpdated != null) { DBUpdated(this, e); } } Now I need to consume this event in my other Windows Phone app page which is a separate class PhoneApplicationPage. So I declared this method in this other Phone Page: public void DBHasBeenUpdated(object sender, EventArgs e) { Debug.WriteLine("DB UPDATE EVENT CATCHED"); } And in the constructor of this page I declared: DBUpdateEventHandler dbEH = new DBUpdateEventHandler(DBHasBeenUpdated); But when I test the application event is fired (OnDBUpdateEvent is called, but DBUpdated is null, therefore DBUpdated is not called - strange) and I have a problem that the other Phone Page is not catching the event at all... Any suggestions? How to catch that event. Thanks.

    Read the article

  • How do you pass a generic delegate argument to a method in .NET 2.0

    - by Seth Spearman
    Hello, I have a class with a delegate declaration as follows... Public Class MyClass Public Delegate Function Getter(Of TResult)() As TResult 'the following code works. Public Shared Sub MyMethod(ByVal g As Getter(Of Boolean)) 'do stuff End Sub End Class However, I do not want to explicitly type the Getter delegate in the Method call. Why can I not declare the parameter as follows... ... (ByVal g As Getter(Of TResult)) Is there a way to do it? My end goal was to be able to set a delegate for property setters and getters in the called class. But my reading indicates you can't do that. So I put setter and getter methods in that class and then I want the calling class to set the delegate argument and then invoke. Is there a best practice for doing this. I realize in the above example that I can set set the delegate variable from the calling class...but I am trying to create a singleton with tight encapsulation. For the record, I can't use any of the new delegate types declared in .net35. Answers in C# are welcome. Any thoughts? Seth

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >