Search Results

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

Page 3/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Delegates: A Practical Understanding

    - by samerpaul
    It's been a while since I have written on this blog, and I'm planning on reviving it this summer, since I have more time to do so again.I've also recently started working on the iPhone platform, so I haven't been as busy in .NET as before.In either case, today's blog post applies to both C# and Objective-C, because it's more about a practical understanding of delegates than it is about code. When I was learning coding, I felt like delegates was one of the hardest things to conceptually understand, and a lot of books don't really do a good job (in my opinion) of explaining it. So here's my stab at it.A Real Life Example of DelegatesLet's say there are three of you. You, your friend, and your brother. You're each in a different room in your house so you can't hear each other, even if you shout. 1)You are playing a computer game2) Friend is building a puzzle3) Brother is nappingNow, you three are going to stay in your room but you want to be informed if anything interesting is happening to the one of you. Let's say you (playing the computer game) want to know when your brother wakes up.You could keep walking to the room, checking to see if he's napping, and then walking back to your room. But that would waste a lot of time / resources, and what if you miss when he's awake before he goes back to sleep? That would be bad.Instead, you hand him a 2-way radio that works between your room and his room. And you inform him that when he wakes up, he should press a button on the radio and say "I'm awake". You are going to be listening to that radio, waiting for him to say he's awake. This, in essence, is how a delegate works.You're creating an "object" (the radio) that allows you to listen in on an event you specify. You don't want him to send any other messages to you right now, except when he wakes up. And you want to know immediately when he does, so you can go over to his room and say hi. (the methods that are called when a delegate event fires). You're also currently specifying that only you are listening on his radio.Let's say you want your friend to come into the room at the same time as you, and do something else entirely, like fluff your brother's pillow. You will then give him an identical radio, that also hooks into your brother's radio, and inform him to wait and listen for the "i'm awake" signal.Then, when your brother wakes up, he says "I'm awake!" and both you and your friend walk into the room. You say hi, and your friend fluffs the pillow, then you both exit.Later, if you decide you don't care to say hi anymore, you turn off your radio. Now, you have no idea when your brother is awake or not, because you aren't listening anymore.So again, you are each classes in this example, and each of you have your own methods. You're playing a computer game (PlayComputerGame()), your friend is building a puzzle (BuildPuzzle()) and your brother is napping (Napping()). You create a delegate (ImAwake) that you set your brother to do, when he wakes up. You listen in on that delegate (giving yourself a radio and turning it on), and when you receive the message, you fire a new method called SayHi()). Your friend is also wired up to the same delegate (using an identical radio) and fires the method FluffPillow().Hopefully this makes sense, and helps shed some light on how delegates operate. Let me know! Feel free to drop me a line at Twitter (preferred method of contact) here: samerabousalbi

    Read the article

  • C#/.NET Little Wonders: The EventHandler and EventHandler&lt;TEventArgs&gt; delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. In the last two weeks, we examined the Action family of delegates (and delegates in general), and the Func family of delegates and how they can be used to support generic, reusable algorithms and classes. So this week, we are going to look at a handy pair of delegates that can be used to eliminate the need for defining custom delegates when creating events: the EventHandler and EventHandler<TEventArgs> delegates. Events and delegates Before we begin, let’s quickly consider events in .NET.  According to the MSDN: An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. So, basically, you can create an event in a type so that users of that type can subscribe to notifications of things of interest.  How is this different than some of the delegate programming that we talked about in the last two weeks?  Well, you can think of an event as a special access modifier on a delegate.  Some differences between the two are: Events are a special access case of delegates They behave much like delegates instances inside the type they are declared in, but outside of that type they can only be (un)subscribed to. Events can specify add/remove behavior explicitly If you want to do additional work when someone subscribes or unsubscribes to an event, you can specify the add and remove actions explicitly. Events have access modifiers, but these only specify the access level of those who can (un)subscribe A public event, for example, means anyone can (un)subscribe, but it does not mean that anyone can raise (invoke) the event directly.  Events can only be raised by the type that contains them In contrast, if a delegate is visible, it can be invoked outside of the object (not even in a sub-class!). Events tend to be for notifications only, and should be treated as optional Semantically speaking, events typically don’t perform work on the the class directly, but tend to just notify subscribers when something of note occurs. My basic rule-of-thumb is that if you are just wanting to notify any listeners (who may or may not care) that something has happened, use an event.  However, if you want the caller to provide some function to perform to direct the class about how it should perform work, make it a delegate. Declaring events using custom delegates To declare an event in a type, we simply use the event keyword and specify its delegate type.  For example, let’s say you wanted to create a new TimeOfDayTimer that triggers at a given time of the day (as opposed to on an interval).  We could write something like this: 1: public delegate void TimeOfDayHandler(object source, ElapsedEventArgs e); 2:  3: // A timer that will fire at time of day each day. 4: public class TimeOfDayTimer : IDisposable 5: { 6: // Event that is triggered at time of day. 7: public event TimeOfDayHandler Elapsed; 8:  9: // ... 10: } The first thing to note is that the event is a delegate type, which tells us what types of methods may subscribe to it.  The second thing to note is the signature of the event handler delegate, according to the MSDN: The standard signature of an event handler delegate defines a method that does not return a value, whose first parameter is of type Object and refers to the instance that raises the event, and whose second parameter is derived from type EventArgs and holds the event data. If the event does not generate event data, the second parameter is simply an instance of EventArgs. Otherwise, the second parameter is a custom type derived from EventArgs and supplies any fields or properties needed to hold the event data. So, in a nutshell, the event handler delegates should return void and take two parameters: An object reference to the object that raised the event. An EventArgs (or a subclass of EventArgs) reference to event specific information. Even if your event has no additional information to provide, you are still expected to provide an EventArgs instance.  In this case, feel free to pass the EventArgs.Empty singleton instead of creating new instances of EventArgs (to avoid generating unneeded memory garbage). The EventHandler delegate Because many events have no additional information to pass, and thus do not require custom EventArgs, the signature of the delegates for subscribing to these events is typically: 1: // always takes an object and an EventArgs reference 2: public delegate void EventHandler(object sender, EventArgs e) It would be insane to recreate this delegate for every class that had a basic event with no additional event data, so there already exists a delegate for you called EventHandler that has this very definition!  Feel free to use it to define any events which supply no additional event information: 1: public class Cache 2: { 3: // event that is raised whenever the cache performs a cleanup 4: public event EventHandler OnCleanup; 5:  6: // ... 7: } This will handle any event with the standard EventArgs (no additional information).  But what of events that do need to supply additional information?  Does that mean we’re out of luck for subclasses of EventArgs?  That’s where the generic for of EventHandler comes into play… The generic EventHandler<TEventArgs> delegate Starting with the introduction of generics in .NET 2.0, we have a generic delegate called EventHandler<TEventArgs>.  Its signature is as follows: 1: public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) 2: where TEventArgs : EventArgs This is similar to EventHandler except it has been made generic to support the more general case.  Thus, it will work for any delegate where the first argument is an object (the sender) and the second argument is a class derived from EventArgs (the event data). For example, let’s say we wanted to create a message receiver, and we wanted it to have a few events such as OnConnected that will tell us when a connection is established (probably with no additional information) and OnMessageReceived that will tell us when a new message arrives (probably with a string for the new message text). So for OnMessageReceived, our MessageReceivedEventArgs might look like this: 1: public sealed class MessageReceivedEventArgs : EventArgs 2: { 3: public string Message { get; set; } 4: } And since OnConnected needs no event argument type defined, our class might look something like this: 1: public class MessageReceiver 2: { 3: // event that is called when the receiver connects with sender 4: public event EventHandler OnConnected; 5:  6: // event that is called when a new message is received. 7: public event EventHandler<MessageReceivedEventArgs> OnMessageReceived; 8:  9: // ... 10: } Notice, nowhere did we have to define a delegate to fit our event definition, the EventHandler and generic EventHandler<TEventArgs> delegates fit almost anything we’d need to do with events. Sidebar: Thread-safety and raising an event When the time comes to raise an event, we should always check to make sure there are subscribers, and then only raise the event if anyone is subscribed.  This is important because if no one is subscribed to the event, then the instance will be null and we will get a NullReferenceException if we attempt to raise the event. 1: // This protects against NullReferenceException... or does it? 2: if (OnMessageReceived != null) 3: { 4: OnMessageReceived(this, new MessageReceivedEventArgs(aMessage)); 5: } The above code seems to handle the null reference if no one is subscribed, but there’s a problem if this is being used in multi-threaded environments.  For example, assume we have thread A which is about to raise the event, and it checks and clears the null check and is about to raise the event.  However, before it can do that thread B unsubscribes to the event, which sets the delegate to null.  Now, when thread A attempts to raise the event, this causes the NullReferenceException that we were hoping to avoid! To counter this, the simplest best-practice method is to copy the event (just a multicast delegate) to a temporary local variable just before we raise it.  Since we are inside the class where this event is being raised, we can copy it to a local variable like this, and it will protect us from multi-threading since multicast delegates are immutable and assignments are atomic: 1: // always make copy of the event multi-cast delegate before checking 2: // for null to avoid race-condition between the null-check and raising it. 3: var handler = OnMessageReceived; 4: 5: if (handler != null) 6: { 7: handler(this, new MessageReceivedEventArgs(aMessage)); 8: } The very slight trade-off is that it’s possible a class may get an event after it unsubscribes in a multi-threaded environment, but this is a small risk and classes should be prepared for this possibility anyway.  For a more detailed discussion on this, check out this excellent Eric Lippert blog post on Events and Races. Summary Generic delegates give us a lot of power to make generic algorithms and classes, and the EventHandler delegate family gives us the flexibility to create events easily, without needing to redefine delegates over and over.  Use them whenever you need to define events with or without specialized EventArgs.   Tweet Technorati Tags: .NET, C#, CSharp, Little Wonders, Generics, Delegates, EventHandler

    Read the article

  • Take care to unhook Anonymous Delegates

    - by David Vallens
    Anonymous delegates are great, they elimiante the need for lots of small classes that just pass values around, however care needs to be taken when using them, as they are not automatically unhooked when the function you created them in returns. In fact after it returns there is no way to unhook them. Consider the following code.   using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { SimpleEventSource t = new SimpleEventSource(); t.FireEvent(); FunctionWithAnonymousDelegate(t); t.FireEvent(); } private static void FunctionWithAnonymousDelegate(SimpleEventSource t) { t.MyEvent += delegate(object sender, EventArgs args) { Debug.WriteLine("Anonymous delegate called"); }; t.FireEvent(); } } public class SimpleEventSource { public event EventHandler MyEvent; public void FireEvent() { if (MyEvent == null) { Debug.WriteLine("Attempting to fire event - but no ones listening"); } else { Debug.WriteLine("Firing event"); MyEvent(this, EventArgs.Empty); } } } } If you expected the anonymous delegates do die with the function that created it then you would expect the output Attempting to fire event - but no ones listeningFiring eventAnonymous delegate calledAttempting to fire event - but no ones listening However what you actually get is Attempting to fire event - but no ones listeningFiring eventAnonymous delegate calledFiring eventAnonymous delegate called In my example the issue is just slowing things down, but if your delegate modifies objects, then you could end up with dificult to diagnose bugs. A solution to this problem is to unhook the delegate within the function var myDelegate = delegate(){Console.WriteLine("I did it!");}; MyEvent += myDelegate; // .... later MyEvent -= myDelegate;

    Read the article

  • When is it useful to define your own delegates instead of using the generics?

    - by Carlos
    I've been going through some old code, where I came across some custom defined delegates, which are used thus: private delegate void ListenDelegate(UdpClient listener, bool multicast); private void ListenOn(UdpClient listener, bool multicast) { new ListenDelegate(_ListenLoop).BeginInvoke(listener, multicast, null, null); } With some of the new .NET framework versions, you can do the following: private void ListenOn(UdpClient listener, bool multicast) { new Action<UdpClient, bool>(_ListenLoop).BeginInvoke(listener, multicast, null, null); } This ought to be exactly the same. Is there any point in defining your own delegates, when the generic delegates seem to do the same job with less space? Or have I missed something about the generics that makes them not equivalent?

    Read the article

  • Using delegates in C# (Part 2)

    - by rajbk
    Part 1 of this post can be read here. We are now about to see the different syntaxes for invoking a delegate and some c# syntactic sugar which allows you to code faster. We have the following console application. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Operation op1 = new Operation(Division); 9: double result = op1.Invoke(10, 5); 10: 11: Console.WriteLine(result); 12: Console.ReadLine(); 13: } 14: 15: static double Division(double x, double y) { 16: return x / y; 17: } 18: } Line 1 defines a delegate type called Operation with input parameters (double x, double y) and a return type of double. On Line 8, we create an instance of this delegate and set the target to be a static method called Division (Line 15) On Line 9, we invoke the delegate (one entry in the invocation list). The program outputs 5 when run. The language provides shortcuts for creating a delegate and invoking it (see line 9 and 11). Line 9 is a syntactical shortcut for creating an instance of the Delegate. The C# compiler will infer on its own what the delegate type is and produces intermediate language that creates a new instance of that delegate. Line 11 uses a a syntactical shortcut for invoking the delegate by removing the Invoke method. The compiler sees the line and generates intermediate language which invokes the delegate. When this code is compiled, the generated IL will look exactly like the IL of the compiled code above. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //shortcut constructor syntax 9: Operation op1 = Division; 10: //shortcut invoke syntax 11: double result = op1(10, 2); 12: 13: Console.WriteLine(result); 14: Console.ReadLine(); 15: } 16: 17: static double Division(double x, double y) { 18: return x / y; 19: } 20: } C# 2.0 introduced Anonymous Methods. Anonymous methods avoid the need to create a separate method that contains the same signature as the delegate type. Instead you write the method body in-line. There is an interesting fact about Anonymous methods and closures which won’t be covered here. Use your favorite search engine ;-)We rewrite our code to use anonymous methods (see line 9): 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //Anonymous method 9: Operation op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } We could rewrite our delegate to be of a generic type like so (see line 2 and line 9). You will see why soon. 1: //Generic delegate 2: public delegate T Operation<T>(T x, T y); 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: Operation<double> op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } The .NET 3.5 framework introduced a whole set of predefined delegates for us including public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); Our code can be modified to use this delegate instead of the one we declared. Our delegate declaration has been removed and line 7 has been changed to use the Func delegate type. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //Func is a delegate defined in the .NET 3.5 framework 7: Func<double, double, double> op1 = delegate (double x, double y) { 8: return x / y; 9: }; 10: double result = op1(10, 2); 11: 12: Console.WriteLine(result); 13: Console.ReadLine(); 14: } 15: 16: static double Division(double x, double y) { 17: return x / y; 18: } 19: } .NET 3.5 also introduced lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. We change our code to use lambda expressions. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //lambda expression 7: Func<double, double, double> op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } C# 3.0 introduced the keyword var (implicitly typed local variable) where the type of the variable is inferred based on the type of the associated initializer expression. We can rewrite our code to use var as shown below (line 7).  The implicitly typed local variable op1 is inferred to be a delegate of type Func<double, double, double> at compile time. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //implicitly typed local variable 7: var op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } You have seen how we can write code in fewer lines by using a combination of the Func delegate type, implicitly typed local variables and lambda expressions.

    Read the article

  • Templated Razor Delegates – Phil Haack

    - by nmarun
    This post is largely based off of Phil Haack’s article titled Templated Razor Delegates. I strongly recommend reading this article first. Here’s a sample code for the same, so you can have a look at. I also have a custom type being rendered as a table. 1: // my custom type 2: public class Device 3: { 4: public int Id { get; set; } 5: public string Name { get; set; } 6: public DateTime MfgDate { get; set; } 7: } Now I can write an extension method just for this type. 1: public static class RazorExtensions 2: { 3: public static HelperResult List(this IList<Models.Device> devices, Func<Models.Device, HelperResult> template) 4: { 5: return new HelperResult(writer => 6: { 7: foreach (var device in devices) 8: { 9: template(device).WriteTo(writer); 10: } 11: }); 12: } 13: // ... 14: } Modified my view to make it a strongly typed one and included html to render my custom type collection in a table. 1: @using TemplatedRazorDelegates 2: @model System.Collections.Generic.IList<TemplatedRazorDelegates.Models.Device> 3:  4: @{ 5: ViewBag.Title = "Home Page"; 6: } 7:  8: <h2>@ViewBag.Message</h2> 9:  10: @{ 11: var items = new[] { "one", "two", "three" }; 12: IList<int> ints = new List<int> { 1, 2, 3 }; 13: } 14:  15: <ul> 16: @items.List(@<li>@item</li>) 17: </ul> 18: <ul> 19: @ints.List(@<li>@item</li>) 20: </ul> 21:  22: <table> 23: <tr><th>Id</th><th>Name</th><th>Mfg Date</th></tr> 24: @Model.List(@<tr><td>@item.Id</td><td>@item.Name</td><td>@item.MfgDate.ToShortDateString()</td></tr>) 25: </table> We get intellisense as well! Just added some items in the action method of the controller: 1: public ActionResult Index() 2: { 3: ViewBag.Message = "Welcome to ASP.NET MVC!"; 4: IList<Device> devices = new List<Device> 5: { 6: new Device {Id = 1, Name = "abc", MfgDate = new DateTime(2001, 10, 19)}, 7: new Device {Id = 2, Name = "def", MfgDate = new DateTime(2011, 1, 1)}, 8: new Device {Id = 3, Name = "ghi", MfgDate = new DateTime(2003, 3, 15)}, 9: new Device {Id = 4, Name = "jkl", MfgDate = new DateTime(2007, 6, 6)} 10: }; 11: return View(devices); 12: } Running this I get the output as: Absolutely brilliant! Thanks to both Phil Haack and to David Fowler for bringing this out to us. Download the code for this from here. Verdict: RazorViewEngine.Points += 1;

    Read the article

  • Adding More Than 2 Delegates in iPhone App

    - by golfromeo
    This is a simple question that can be answered fast by someone who's more familiar with Objective-C than I am- how can one add more than 2 delegates to a Class? To clarify, I'm used to putting delegates in classes like this: @interface ViewController : UIViewController <UIWebViewDelegate> { ... When I try to put two delegates: @interface ViewController : UIViewController <UIWebViewDelegate> <UITextFieldDelegate> { ... ...the app gives many errors, none of which help with the situation. Is there a separator that I need to put between the delegates, or is it possible at all to have more than two? Thanks for any help in advance.

    Read the article

  • How to extract delegates from ViewController class?

    - by adranle
    Hi I have the problem that my view controller class has too many delegates and starts to get big. I want to write the delegates in separate classes to keep the view controller class small. For delegates that are programmatically created (like UIAlertViewDelegate) I could do it easily. The problem is in the delegates assigned in Interface Builder. How can I tell the IB to assign, for example, another class as the UITableViewDelegate or UITableViewDataSource? Or how to choose another IBAction method for a Touch UP inside Event on a button? One solution would be to delete the connections from IB and write them programmatically at ViewDidLoad, but since I have a lot of ViewControllers, this would take a long time. any other ideas?

    Read the article

  • "Sent on behalf" not appearing when delegates sending mails

    - by New Steve
    Ringo is a delegate of Paul's mailbox in Exchange, but when Ringo sends mail from Paul's mailbox, the recipient sees "Paul" in the sender field, rather than "Paul Sent On Behalf Of Ringo" Paul has set "Editor" permissions for Ringo to his mailbox, and Ringo has been granted "Send on behalf of" permissions in Exchange. Ringo did at one time have "Send As" permissions for Paul's mailbox in Exchange, but this has since been removed. This is also the case for all other delegates to Paul's mailbox. How do I make it so that emails sent by Paul's delegates show the "Sent On Behalf Of" information in the Sender field? Using Exchange Server 2007 and Microsoft Office Outlook 2007

    Read the article

  • "Sent on behalf" not appearing when delegates sending mails

    - by New Steve
    Ringo is a delegate of Paul's mailbox in Exchange, but when Ringo sends mail from Paul's mailbox, the recipient sees "Paul" in the sender field, rather than "Paul Sent On Behalf Of Ringo" Paul has set "Editor" permissions for Ringo to his mailbox, and Ringo has been granted "Send on behalf of" permissions in Exchange. Ringo did at one time have "Send As" permissions for Paul's mailbox in Exchange, but this has since been removed. This is also the case for all other delegates to Paul's mailbox. How do I make it so that emails sent by Paul's delegates show the "Sent On Behalf Of" information in the Sender field? Using Exchange Server 2007 and Microsoft Office Outlook 2007

    Read the article

  • Is it possible to pass a structure of delegates from managed to native?

    - by Veiva
    I am writing a wrapper for the game programming library "Allegro" and its less stable 4.9 branch. Now, I have done good insofar, except for when it comes to wrapping a structure of function pointers. Basically, I can't change the original code, despite having access to it, because that would require me to fork it in some manner. I need to know how I can somehow pass a structure of delegates from managed to native without causing an AccessViolationException that has occurred so far. Now, for the code. Here is the Allegro definition of the structure: typedef struct ALLEGRO_FILE_INTERFACE { AL_METHOD(ALLEGRO_FILE*, fi_fopen, (const char *path, const char *mode)); AL_METHOD(void, fi_fclose, (ALLEGRO_FILE *handle)); AL_METHOD(size_t, fi_fread, (ALLEGRO_FILE *f, void *ptr, size_t size)); AL_METHOD(size_t, fi_fwrite, (ALLEGRO_FILE *f, const void *ptr, size_t size)); AL_METHOD(bool, fi_fflush, (ALLEGRO_FILE *f)); AL_METHOD(int64_t, fi_ftell, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_fseek, (ALLEGRO_FILE *f, int64_t offset, int whence)); AL_METHOD(bool, fi_feof, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_ferror, (ALLEGRO_FILE *f)); AL_METHOD(int, fi_fungetc, (ALLEGRO_FILE *f, int c)); AL_METHOD(off_t, fi_fsize, (ALLEGRO_FILE *f)); } ALLEGRO_FILE_INTERFACE; My simple attempt at wrapping it: public delegate IntPtr AllegroInternalOpenFileDelegate(string path, string mode); public delegate void AllegroInternalCloseFileDelegate(IntPtr file); public delegate int AllegroInternalReadFileDelegate(IntPtr file, IntPtr data, int size); public delegate int AllegroInternalWriteFileDelegate(IntPtr file, IntPtr data, int size); public delegate bool AllegroInternalFlushFileDelegate(IntPtr file); public delegate long AllegroInternalTellFileDelegate(IntPtr file); public delegate bool AllegroInternalSeekFileDelegate(IntPtr file, long offset, int where); public delegate bool AllegroInternalIsEndOfFileDelegate(IntPtr file); public delegate bool AllegroInternalIsErrorFileDelegate(IntPtr file); public delegate int AllegroInternalUngetCharFileDelegate(IntPtr file, int c); public delegate long AllegroInternalFileSizeDelegate(IntPtr file); [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct AllegroInternalFileInterface { [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalOpenFileDelegate fi_fopen; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalCloseFileDelegate fi_fclose; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalReadFileDelegate fi_fread; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalWriteFileDelegate fi_fwrite; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFlushFileDelegate fi_fflush; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalTellFileDelegate fi_ftell; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalSeekFileDelegate fi_fseek; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsEndOfFileDelegate fi_feof; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsErrorFileDelegate fi_ferror; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalUngetCharFileDelegate fi_fungetc; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFileSizeDelegate fi_fsize; } I have a simple auxiliary wrapper that turns an ALLEGRO_FILE_INTERFACE into an ALLEGRO_FILE, like so: #define ALLEGRO_NO_MAGIC_MAIN #include <allegro5/allegro5.h> #include <stdlib.h> #include <string.h> #include <assert.h> __declspec(dllexport) ALLEGRO_FILE * al_aux_create_file(ALLEGRO_FILE_INTERFACE * fi) { ALLEGRO_FILE * file; assert(fi && "`fi' null"); file = (ALLEGRO_FILE *)malloc(sizeof(ALLEGRO_FILE)); if (!file) return NULL; file->vtable = (ALLEGRO_FILE_INTERFACE *)malloc(sizeof(ALLEGRO_FILE_INTERFACE)); if (!(file->vtable)) { free(file); return NULL; } memcpy(file->vtable, fi, sizeof(ALLEGRO_FILE_INTERFACE)); return file; } __declspec(dllexport) void al_aux_destroy_file(ALLEGRO_FILE * f) { assert(f && "`f' null"); assert(f->vtable && "`f->vtable' null"); free(f->vtable); free(f); } Lastly, I have a class that accepts a Stream and provides the proper methods to interact with the stream. Just to make sure, here it is: /// <summary> /// A semi-opaque data type that allows one to load fonts, etc from a stream. /// </summary> public class AllegroFile : AllegroResource, IDisposable { AllegroInternalFileInterface fileInterface; Stream fileStream; /// <summary> /// Gets the file interface. /// </summary> internal AllegroInternalFileInterface FileInterface { get { return fileInterface; } } /// <summary> /// Constructs an Allegro file from the stream provided. /// </summary> /// <param name="stream">The stream to use.</param> public AllegroFile(Stream stream) { fileStream = stream; fileInterface = new AllegroInternalFileInterface(); fileInterface.fi_fopen = Open; fileInterface.fi_fclose = Close; fileInterface.fi_fread = Read; fileInterface.fi_fwrite = Write; fileInterface.fi_fflush = Flush; fileInterface.fi_ftell = GetPosition; fileInterface.fi_fseek = Seek; fileInterface.fi_feof = GetIsEndOfFile; fileInterface.fi_ferror = GetIsError; fileInterface.fi_fungetc = UngetCharacter; fileInterface.fi_fsize = GetLength; Resource = AllegroFunctions.al_aux_create_file(ref fileInterface); if (!IsValid) throw new AllegroException("Unable to create file"); } /// <summary> /// Disposes of all resources. /// </summary> ~AllegroFile() { Dispose(); } /// <summary> /// Disposes of all resources used. /// </summary> public void Dispose() { if (IsValid) { Resource = IntPtr.Zero; // Should call AllegroFunctions.al_aux_destroy_file fileStream.Dispose(); } } IntPtr Open(string path, string mode) { return IntPtr.Zero; } void Close(IntPtr file) { fileStream.Close(); } int Read(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; int read = fileStream.Read(d, 0, size); Marshal.Copy(d, 0, data, size); return read; } int Write(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; Marshal.Copy(data, d, 0, size); fileStream.Write(d, 0, size); return size; } bool Flush(IntPtr file) { fileStream.Flush(); return true; } long GetPosition(IntPtr file) { return fileStream.Position; } bool Seek(IntPtr file, long offset, int whence) { SeekOrigin origin = SeekOrigin.Begin; if (whence == 1) origin = SeekOrigin.Current; else if (whence == 2) origin = SeekOrigin.End; fileStream.Seek(offset, origin); return true; } bool GetIsEndOfFile(IntPtr file) { return fileStream.Position == fileStream.Length; } bool GetIsError(IntPtr file) { return false; } int UngetCharacter(IntPtr file, int character) { return -1; } long GetLength(IntPtr file) { return fileStream.Length; } } Now, when I do something like this: AllegroFile file = new AllegroFile(new FileStream("Test.bmp", FileMode.Create, FileAccess.ReadWrite)); bitmap.SaveToFile(file, ".bmp"); ...I get an AccessViolationException. I think I understand why (the garbage collector can relocate structs and classes whenever), but I'd think that the method stub that is created by the framework would take this into consideration and route the calls to the valid classes. However, it seems obviously so that I'm wrong. So basically, is there any way I can successfully wrap that structure? (And I'm sorry for all the code! Hope it's not too much...)

    Read the article

  • What's the proper way to setup different objects as delegates using Interface Builder?

    - by eagle
    Let's say I create a new project. I now add two text fields to the view controller in Interface Builder. I want to respond to delegate events that the text fields create, however, I don't want to have the main view controller to act as the delegate for both text fields. Ideally I want a separate file for each text field that acts as the delegate. Each of these objects also needs to be able to interact with the main view controller. My question is how I would set this up and link everything correctly? I tried creating a new class that inherits from NSObject and implements UITextFieldDelegate. I then added an instance variable called "viewController" of the same type of my view controller and marked it with IBOutlet (this required me to add #import "myViewcontroller.h"). I then went to Interface Builder and opened up my view controller which contains the two edit boxes. I added an NSObject to the form and changed it's type to be of the new class I created. I set its viewController property to the File's Owner, and set one of the textbox's delegate properties to point to this new object I created. Now when I run the program, it crashes when I touch the text box. It gives the error EXC_BAD_ACCESS. I'm guessing I didn't link stuff correctly in IB. Some things I'm not sure about which might be the problem: Does IB automatically know to create an instance of the class just by placing the NSObject in the ViewController? Can it properly assign the viewController property to an instance of itself even though it is creating itself at the same time?

    Read the article

  • how do i add two delegates to a ui element at run time?

    - by Michael Xu
    Hi everyone, im trying to implement some behaviors when a mapview element scrolls... by coding a delegate for the scrollview inside of a mapview. so, right now, i got a pointer to the scroll view used by the map view in my code. however, i wish to set the delegate of this scroll view inside the map view, but the issue is that the mapview already sets up a default delegate for this scroll view inside the map view. can i make my delegate implement all of the messages of the protocol, explicitly sending them to the mapview's default delegate while also implementing my own behaviors? how else can i go about adding my own delegate behavior, to an already existing default delegate....? thanks everyone, michael

    Read the article

  • C++ and C#, "Casting" Functions to Delegates, What's the scoop?

    - by Jacob G
    In C# 2.0, I can do the following: public class MyClass { delegate void MyDelegate(int myParam); public MyClass(OtherObject obj) { //THIS IS THE IMPORTANT PART obj.SomeCollection.Add((MyDelegate)MyFunction); } private void MyFunction(int myParam); { //... } } Trying to implement the same thing in C++, it appears I have to do: MyDelegate del = gcnew MyDelegate(this, MyFunction); obj-SomeCollection-Add(del); Obviously I can create a new instance of the delegate in C# as well instead of what's going on up there. Is there some kind of magic going on in the C# world that doesn't exist in C++ that allows that cast to work? Some kind of magic anonymous delegate? Thanks.

    Read the article

  • C++/CLI and C#, "Casting" Functions to Delegates, What's the scoop?

    - by Jacob G
    In C# 2.0, I can do the following: public class MyClass { delegate void MyDelegate(int myParam); public MyClass(OtherObject obj) { //THIS IS THE IMPORTANT PART obj.SomeCollection.Add((MyDelegate)MyFunction); } private void MyFunction(int myParam); { //... } } Trying to implement the same thing in C++/CLI, it appears I have to do: MyDelegate del = gcnew MyDelegate(this, MyFunction); obj-SomeCollection-Add(del); Obviously I can create a new instance of the delegate in C# as well instead of what's going on up there. Is there some kind of magic going on in the C# world that doesn't exist in C++/CLI that allows that cast to work? Some kind of magic anonymous delegate? Thanks.

    Read the article

  • How to work with delegates and event handler for user control.

    - by Shantanu Gupta
    I have created a user control that contains a button. I am using this control on my winform which will be loaded at run time after fetching data from database. Now I need to remove a row from a datatable on the Click event of that button. The problem is that how do I capture that event in my form. Currently it goes in that user control's btn click event defination.

    Read the article

  • Outlook, Delegates and IgnoreSOBError registry work-around

    - by Yougotiger
    We just moved to exchange/Outlook, and our users are trying to create delegations to their admin assistants. We're getting the following message: The Delegates settings were not saved correctly. Unable to activate send-on-behalf-of list. You do not have sufficient permission to perform this operation on this object. It seems the issue can be resolved with a registry entry as per the KB article: http://support.microsoft.com/kb/950794/en-us But I'm wondering if this is just a band-aid or if it gets to the root of the problem?

    Read the article

  • EJB3 Business Delegates

    - by mykola
    Is there any reason for making delegate when using EJB3? Because the only real benefit i see from delegate is that it allows to hide lookup and access details of EJB architecture. Well it also provides some decoupling but it's mostly unused, imho. With EJB3 we have injection so now i can just create a variable with @EJB annotation and use it as is. Do i still need delegates? Is this injection resource consuming? I mean if i use it in JSF's request managed beans may be it's still better to use delegates just to lessen these injection calls? Thank you!

    Read the article

  • Delegates in Action -Help

    - by Amutha
    I am learning delegates.I am very curious to apply delegates to the following chain-of-responsibility pattern. Kindly help me the way to apply delegates to the following piece. Thanks in advance.Thanks for your effort. #region Chain of Responsibility Pattern namespace Chain { public class Player { public string Name { get; set; } public int Score { get; set; } } public abstract class PlayerHandler { protected PlayerHandler _Successor = null; public abstract void HandlePlayer(Player _player); public void SetupHandler(PlayerHandler _handler) { _Successor = _handler; } } public class Employee : PlayerHandler { public override void HandlePlayer(Player _player) { if (_player.Score <= 100) { MessageBox.Show(string.Format("{0} is greeted by Employee", _player.Name)); } else { _Successor.HandlePlayer(_player); } } } public class Supervisor : PlayerHandler { public override void HandlePlayer(Player _player) { if (_player.Score >100 && _player.Score<=200) { MessageBox.Show(string.Format("{0} is greeted by Supervisor", _player.Name)); } else { _Successor.HandlePlayer(_player); } } } public class Manager : PlayerHandler { public override void HandlePlayer(Player _player) { if (_player.Score > 200) { MessageBox.Show(string.Format("{0} is greeted by Manager", _player.Name)); } else { MessageBox.Show(string.Format("{0} got low score", _player.Name)); } } } } #endregion #region Main() void Main() { Chain.Player p1 = new Chain.Player(); p1.Name = "Jon"; p1.Score = 100; Chain.Player p2 = new Chain.Player(); p2.Name = "William"; p2.Score = 170; Chain.Player p3 = new Chain.Player(); p3.Name = "Robert"; p3.Score = 300; Chain.Employee emp = new Chain.Employee(); Chain.Manager mgr = new Chain.Manager(); Chain.Supervisor sup = new Chain.Supervisor(); emp.SetupHandler(sup); sup.SetupHandler(mgr); emp.HandlePlayer(p1); emp.HandlePlayer(p2); emp.HandlePlayer(p3); } #endregion

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >