Search Results

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

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

  • How I pass a delegate prototype to a method?

    - by Jeff Dahmer
    SO lets say in my class I have: public delegate bool MyFunc(int param); How can I then do this someObj.PassMeADelegateToExamine(this.MyFunc); // not possible!?! SO that I can examine the delegate and perhaps use reflection or something idk to find out it's return type and any params it might have? Basically if I can transform it into an (uncallable) Action object that woul dbe grand

    Read the article

  • C#: Hook up all events from object in single statement.

    - by David
    In my domain layer all domain objects emit events (of type InvalidDomainObjectEventHandler) to indicate invalid state when the IsValid property is called. On an aspx codebehind, I have to manually wire up the events for the domain object like this: _purchaseOrder.AmountIsNull += new DomainObject.InvalidDomainObjectEventHandler(HandleDomainObjectEvent); _purchaseOrder.NoReason += new DomainObject.InvalidDomainObjectEventHandler(HandleDomainObjectEvent); _purchaseOrder.NoSupplier += new DomainObject.InvalidDomainObjectEventHandler(HandleDomainObjectEvent); _purchaseOrder.BothNewAndExistingSupplier += new DomainObject.InvalidDomainObjectEventHandler(HandleDomainObjectEvent); Note that the same method is called in each case since the InvalidDomainobjectEventArgs class contains the message to display. Is there any way I can write a single statement to wire up all events of type InvalidDomainObjectEventHandler in one go? Thanks David

    Read the article

  • Why is there no * in front of delegate declaration ?

    - by gotye
    Hey guys, I just noticed there is no * in front of the declaration for a delegate ... I did something like this : @protocol NavBarHiddenDelegate; @interface AsyncImageView : UIView { NSURLConnection* connection; NSMutableData* data; UIActivityIndicatorView *indicator; id <NavBarHiddenDelegate> delegate; } @property (nonatomic, assign) id <NavBarHiddenDelegate> delegate; - (id)initWithUrl:(NSString*)url; @end @protocol NavBarHiddenDelegate - (void)hideNavBar; @end It works perfectly well but as I am used to always but a * in front of objects I declare, why not for this one ?!? Thank you, Gotye.

    Read the article

  • Understanding Thread/BeginInvoke? [beginner]

    - by Moberg
    Consider the code: class Work { public void DoStuff(string s) { Console.WriteLine(s); // .. whatever } } class Master { private readonly Work work = new Work(); public void Execute() { string hello = "hello"; // (1) is this an ugly hack ? var thread1 = new Thread(new ParameterizedThreadStart(o => this.work.DoStuff((string)o))); thread1.Start(hello); thread1.Join(); // (2) is this similar to the one above? new Action<string>(s => this.work.DoStuff(s)).BeginInvoke(hello, null, null); } } Is (1) an acceptable way of easy starting some work in a seperate thread? If not a better alternative would be much appreciated. Is (2) doing the same? I guess what I ask is if a new thread is started, or.. Hope you can help a beginner to a better understanding :) /Moberg

    Read the article

  • Cocoa/MacRuby: How to write a toolbar which accepts custom items?

    - by Joseph Melettukunnel
    I'm doing my first steps in MacRuby. Does anyone know how I can add a custom Toolbar to my Cocoa/MacRuby application, which will accept "regular" items for e.g. switching the view (see http://www.stevestreeting.com/wp-content/uploads/2011/06/SelectableToolbarDemo001.png). I've read some tutorials and I guess I have to create a custom delegate for the Toolbar and then connect it via the Outlets window, but how does the myCustomDelegate.rb have to look like? Thanks a lot! Cheers

    Read the article

  • Does delegate chaining have to start with a null Delegate?

    - by MCS
    In CLR via C#, Jeffrey Richter gives the following example of delegate chaining (pg. 406): internal delegate void Feedback(Int 32 value); Feedback fb1 = new Feedback(method1); // in the book, these methods Feedback fb2 = new Feedback(method2); // have different names Feedback fb3 = new Feedback(method3); Feedback fbChain = null; fbChain = (Feedback) Delegate.Combine(fbChain, fb1); fbChain = (Feedback) Delegate.Combine(fbChain, fb2); fbChain = (Feedback) Delegate.Combine(fbChain, fb3); Why does the first call to Delegate.Combine have to pass in a null Delegate? Here's how I would have thought it should be written: Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2); fbChain = (Feedback) Delegate.Combine(fbchain, fb3);

    Read the article

  • Delegate methods of NSTextField using NSNotification

    - by hekevintran
    I have an NSTokenField in a window. I am using it to store tags related to a Core Data object. Right now I have it set up such that I can add tags to the objects, but I cannot delete them. I need a delegate method on the NSTokenField that can let me know when the user has moved the focus out of the NSTokenField. Since NSTokenField is a subclass of NSTextField I figured that I could use its delegate methods. It has two that I think could be useful: - (void)textDidChange:(NSNotification *)aNotification - (void)textDidEndEditing:(NSNotification *)aNotification I set my controller class as the delegate of my NSTokenField and put both of these methods into my controller class. I put a basic NSLog into each of them and neither is triggered when I interact with the NSTokenField. I am guessing it has something to do with NSNotification. How do I activate these methods?

    Read the article

  • Delegate won't update page

    - by mat690
    I am trying to change the active index of a multiview by using a delegate and it doesn't work as i expect. this is my code protected void ucWaitPage_FinishedWaiting(PerformAfterWaitDelegate performAfterWait) { performAfterWait.Invoke(); this.SetIndex(); } private void SetIndex() { this.mvwTest.ActiveViewIndex = 0; } The performAfterWait Delegate points to the SetIndex() method. When the performAfterWait delegate gets invoked SetIndex() gets called but when SetIndex() returns this.mvwTest.ActiveViewIndex reverts to being equal to 1. However when i call the SetIndex() method directly it sets this.mvwTest.ActiveViewIndex = 0 and the change persists when the method returns.

    Read the article

  • Accessing ViewController's variables from UIActionSheet delegate

    - by VansFannel
    Hello. I have the following code: @implementation SendMapViewController NSMutableArray *emails; At this method I create emails array and I add some NSStrings: - (BOOL) peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson: (ABRecordRef)person { ABMultiValueRef emailInfo = ABRecordCopyValue(person, kABPersonEmailProperty); NSUInteger emailCount = ABMultiValueGetCount(emailInfo); if (emailCount > 1) { UIActionSheet *emailsAlert = [[UIActionSheet alloc] initWithTitle:@"Select an email" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; emails = [NSMutableArray arrayWithCapacity: emailCount]; for (NSUInteger i = 0; i < emailCount; i++) { NSString *emailFromContact = (NSString *)ABMultiValueCopyValueAtIndex(emailInfo, i); [emails addObject: emailFromContact]; [emailsAlert addButtonWithTitle:emailFromContact]; [emailFromContact release]; } [emailsAlert addButtonWithTitle:@"Cancel"]; [emailsAlert showInView:self.view]; [emailsAlert release]; } else { ... } CFRelease(emailInfo); [self dismissModalViewControllerAnimated:YES]; return NO; } As you can see in code, if there are more than one email I show and UIActionSheet. When user clicks on a button representing and email, I want to execute the following code: - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if ([emails count] >= buttonIndex) { NSString *contactEmail = (NSString *)[emails objectAtIndex:buttonIndex]; ... } } But emails array hasn't got any email. What I'm doing wrong? I'm developing for iPhone.

    Read the article

  • Using Func<...> and params?

    - by grady
    Hello, I wrote this code: public static bool MyMethod(int someid, params string[] types) {...} How could I write that using Func? public static Func < int, ?params?, bool > MyMethod = ??? Thanks :-)

    Read the article

  • Can I "inherit" a delegate? Looking for ways to combine Moq and MSpec without conflicts around It...

    - by Tomas Lycken
    I have started to use MSpec for BDD, and since long ago I use Moq as my mocking framework. However, they both define It, which means I can't have using Moq and using Machine.Specifications in the same code file without having to specify the namespace explicitly each time I use It. Anyone who's used MSpec knows this isn't really an option. I googled for solutions to this problem, and this blogger mentions having forked MSpec for himself, and implemented paralell support for Given, When, Then. I'd like to do this, but I can't figure out how to declare for example Given without having to go through the entire framework looking for references to Establish, and changing code there to match that I want either to be OK. For reference, the Establish, Because and It are declared in the following way: public delegate void Establish(); public delegate void Because(); public delegate void It(); What I need is to somehow declare Given, so that everywhere the code looks for an Establish, Given is also OK.

    Read the article

  • Why is one Func valid and the other (almost identical) not.

    - by runrunraygun
    private static Dictionary<Type, Func<string, object>> _parseActions = new Dictionary<Type, Func<string, object>> { { typeof(bool), value => {Convert.ToBoolean(value) ;}} }; The above gives an error Error 14 Not all code paths return a value in lambda expression of type 'System.Func<string,object>' However this below is ok. private static Dictionary<Type, Func<string, object>> _parseActions = new Dictionary<Type, Func<string, object>> { { typeof(bool), value => Convert.ToBoolean(value) } }; I don't understand the difference between the two. I thought the extra braces in example1 are to allow us to use multiple lines in the anon function so why have they affected the meaning of the code?

    Read the article

  • How to pass an event to a method and then subscribe to it?

    - by Ryan Peschel
    Event Handler public void DeliverEvent(object sender, EventArgs e) { } #1: This Works public void StartListening(Button source) { source.Click += DeliverEvent; } #2: And so does this.. public void StartListening(EventHandler eventHandler) { eventHandler += DeliverEvent; } But in #2, you cannot call the method because if you try something like this: StartListening(button.Click); You get this error: The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -= Is there any way around that error? I want to be able to pass the event and not the object housing the event to the StartListening method.

    Read the article

  • Returning NSNull from actionForLayer:forKey

    - by MrHen
    If I implement the CALayer delegate method actionForLayer:forKey I can return [NSNull null] to force the CALayer to not animate any changes. Unfortunately, [NSNull null] doesn't implement the CAAction delegate and XCode kicks out the following warning: warning: class 'NSNull' does not implement the 'CAAction' protocol Here is the method code: - (id<CAAction>)actionForLayer:(CALayer *)theLayer forKey:(NSString *)theKey { //This disables the animations when moving things around //Also, don't animate the selection box. It was doing weird things if(undoGroupStarted || theLayer == self.selectionBox) { return [NSNull null]; } else { return nil; } } Am I doing something wrong? Is returning [NSNull null] bad behavior? If so, what is another way to do what I am trying to do here? If not, how do I make the compiler happy?

    Read the article

  • How to invoke a delegate with a null parameter?

    - by Rodney Burton
    I get a null exception if I try to pass a null parameter to a delegate during an invoke. Here's what the code looks like: public void RequestPhoto() { WCF.Service.BeginGetUserPhoto(Contact.UserID, new AsyncCallback(RequestPhotoCB), null); } public void RequestPhotoCB(IAsyncResult result) { var photo = WCF.Service.EndGetUserPhoto(result); UpdatePhoto(photo); } public delegate void UpdatePhotoDelegate(Binary photo); public void UpdatePhoto(Binary photo) { if (InvokeRequired) { var d = new UpdatePhotoDelegate(UpdatePhoto); Invoke(d, new object[] { photo }); } else { var ms = new MemoryStream(photo.ToArray()); var bmp = new Bitmap(ms); pbPhoto.BackgroundImage = bmp; } } The problem is with the line: Invoke(d, new object[] { photo }); If the variable "photo" is null. What is the correct way to pass a null parameter during an invoke? Thanks!

    Read the article

  • Issue with Callback method and maintaining CultureInfo and ASP.Net HttpRuntime

    - by Little Larry Sellers
    Hi All, Here is my issue. I am working on an E-commerce solution that is deployed to multiple European countries. We persist all exceptions within the application to SQL Server and I have found that there are records in the DB that have a DateTime in the future! We define the culture in the web.config, for example pt-PT, and the format expected is DD-MM-YYYY. After debugging I found the issue with these 'future' records in the DB is because of Callback methods we use. For example, in our Caching architecture we use Callbacks, as such - CacheItemRemovedCallback ReloadCallBack = new CacheItemRemovedCallback(OnRefreshRequest); When I check the current threads CultureInfo, on these Callbacks it is en-US instead of pt-PT and also the HttpContext is null. If an exception occurs on the Callback our exception manager reports it as MM-DD-YYYY and thus it is persisted to SQL Server incorrectly. Unfortunately, in the exception manager code, we use DateTime.Now, which is fine if it is not a callback. I can't change this code to be culture specific due to it being shared across other verticals. So, why don't callbacks into ASP.Net maintain context? Is there any way to maintain it on this callback thread? What are the best practices here? Thanks.

    Read the article

  • Help me clean up this crazy lambda with the out keyword

    - by Sarah Vessels
    My code looks ugly, and I know there's got to be a better way of doing what I'm doing: private delegate string doStuff( PasswordEncrypter encrypter, RSAPublicKey publicKey, string privateKey, out string salt ); private bool tryEncryptPassword( doStuff encryptPassword, out string errorMessage ) { ...get some variables... string encryptedPassword = encryptPassword(encrypter, publicKey, privateKey, out salt); ... } This stuff so far doesn't bother me. It's how I'm calling tryEncryptPassword that looks so ugly, and has duplication because I call it from two methods: public bool method1(out string errorMessage) { string rawPassword = "foo"; return tryEncryptPassword( (PasswordEncrypter encrypter, RSAPublicKey publicKey, string privateKey, out string salt) => encrypter.EncryptPasswordAndDoStuff( // Overload 1 rawPassword, publicKey, privateKey, out salt ), out errorMessage ); } public bool method2(SecureString unencryptedPassword, out string errorMessage) { return tryEncryptPassword( (PasswordEncrypter encrypter, RSAPublicKey publicKey, string privateKey, out string salt) => encrypter.EncryptPasswordAndDoStuff( // Overload 2 unencryptedPassword, publicKey, privateKey, out salt ), out errorMessage ); } Two parts to the ugliness: I have to explicitly list all the parameter types in the lambda expression because of the single out parameter. The two overloads of EncryptPasswordAndDoStuff take all the same parameters except for the first parameter, which can either be a string or a SecureString. So method1 and method2 are pretty much identical, they just call different overloads of EncryptPasswordAndDoStuff. Any suggestions? Edit: if I apply Jeff's suggestions, I do the following call in method1: return tryEncryptPassword( (encrypter, publicKey, privateKey) => { var result = new EncryptionResult(); string salt; result.EncryptedValue = encrypter.EncryptPasswordAndDoStuff( rawPassword, publicKey, privateKey, out salt ); result.Salt = salt; return result; }, out errorMessage ); Much the same call is made in method2, just with a different first value to EncryptPasswordAndDoStuff. This is an improvement, but it still seems like a lot of duplicated code.

    Read the article

  • c# delegete creation and activation

    - by aharont
    I have two functions: double fullFingerPrinting(string location1, string location2, int nGrams) double AllSubstrings(string location1, string location2, int nGrams) I want to go in a loop and activate each function in its turn, and after each function I also want to print the name of the function, how can I do that?

    Read the article

  • Typesafe fire-and-forget asynchronous delegate invocation in C#

    - by LBushkin
    I recently found myself needing a typesafe "fire-and-forget" mechanism for running code asynchronously. Ideally, what I would want to do is something like: var myAction = (Action)(() => Console.WriteLine("yada yada")); myAction.FireAndForget(); // async invocation Unfortunately, the obvious choice of calling BeginInvoke() without a corresponding EndInvoke() does not work - it results in a slow resource leak (since the asyn state is held by the runtime and never released ... it's expecting an eventual call to EndInvoke(). I also can't run the code on the .NET thread pool because it may take a very long time to complete (it's advised to only run relatively short-lived code on the thread pool) - this makes it impossible to use the ThreadPool.QueueUserWorkItem(). Initially, I only needed this behavior for methods whose signature matches Action, Action<...>, or Func<...>. So I put together a set of extension methods (see listing below) that let me do this without running into the resource leak. There are overloads for each version of Action/Func. Unfortunately, I now want to port this code to .NET 4 where the number of generic parameters on Action and Func have been increased substantially. Before I write a T4 script to generate these, I was also hoping to find a simpler more elegant way to do this. Any ideas are welcome. public static class AsyncExt { public static void FireAndForget( this Action action ) { action.BeginInvoke(OnActionCompleted, action); } public static void FireAndForget<T1>( this Action<T1> action, T1 arg1 ) { action.BeginInvoke(arg1, OnActionCompleted<T1>, action); } public static void FireAndForget<T1,T2>( this Action<T1,T2> action, T1 arg1, T2 arg2 ) { action.BeginInvoke(arg1, arg2, OnActionCompleted<T1, T2>, action); } public static void FireAndForget<TResult>(this Func<TResult> func, TResult arg1) { func.BeginInvoke(OnFuncCompleted<TResult>, func); } public static void FireAndForget<T1,TResult>(this Func<T1, TResult> action, T1 arg1) { action.BeginInvoke(arg1, OnFuncCompleted<T1,TResult>, action); } // more overloads of FireAndForget<..>() for Action<..> and Func<..> private static void OnActionCompleted( IAsyncResult result ) { var action = (Action)result.AsyncState; action.EndInvoke(result); } private static void OnActionCompleted<T1>( IAsyncResult result ) { var action = (Action<T1>)result.AsyncState; action.EndInvoke( result ); } private static void OnActionCompleted<T1,T2>(IAsyncResult result) { var action = (Action<T1,T2>)result.AsyncState; action.EndInvoke(result); } private static void OnFuncCompleted<TResult>( IAsyncResult result ) { var func = (Func<TResult>)result.AsyncState; func.EndInvoke( result ); } private static void OnFuncCompleted<T1,TResult>(IAsyncResult result) { var func = (Func<T1, TResult>)result.AsyncState; func.EndInvoke(result); } // more overloads of OnActionCompleted<> and OnFuncCompleted<> }

    Read the article

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