Search Results

Search found 2441 results on 98 pages for 'delegate'.

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

  • What happens if an asynchronous delegate call never returns?

    - by RichardHowells
    I found a decent looking example of how to call a delegate asynchronously with a timeout... http://www.eggheadcafe.com/tutorials/aspnet/847c94bf-4b8d-4a66-9ae5-5b61f049019f/basics-make-any-method-c.aspx. In summary it uses WaitOne with a timeout to determine if the call does not return before the timeout expires. I also know that you should have an EndInvoke to match each BeginInvoke. So what happens if the wait timeout expires? We (presumably) DON'T want to call EndInvoke as that will block. The code can go on to do 'other things', but have we leaked anything? Is there some poor thread someplace blocked waiting for a return that's never going to happen? Have we leaked some memory where the result-that-will-never-return was going to be placed?

    Read the article

  • Why does this MSDN example for Func<> delegate have a superfluous Select() call?

    - by Dan
    The MSDN gives this code example in the article on the Func Generic Delegate: Func<String, int, bool> predicate = ( str, index) => str.Length == index; String[] words = { "orange", "apple", "Article", "elephant", "star", "and" }; IEnumerable<String> aWords = words.Where(predicate).Select(str => str); foreach (String word in aWords) Console.WriteLine(word); I understand what all this is doing. What I don't understand is the Select(str => str) bit. Surely that's not needed? If you leave it out and just have IEnumerable<String> aWords = words.Where(predicate); then you still get an IEnumerable back that contains the same results, and the code prints the same thing. Am I missing something, or is the example misleading?

    Read the article

  • Why delegate types are derived from MulticastDelegate class why not it directly derive from Delegate class?

    - by Vijay
    I have a very basic question regarding delegate types. I compared the memebers of Delegate and MulticastDelegate classes in object browser and I couldn't find any new additional member present in MulticastDelegate. I also noticed that the Delegate class has GetInvocationList virtual method. So I assume that the Delegate class should have the capability to hold references to multiple methods. If my assumption is correct I wonder why not custom delegate types directly derive from the Delegate class instead of MulticastDelegate class. Not sure what I am missing here. Please help me understand the difference.

    Read the article

  • Func Delegate in C#

    - by Jalpesh P. Vadgama
    We already know about delegates in C# and I have previously posted about basics of delegates in C#. Following are posts about basic of delegates I have written. Delegates in C# Multicast Delegates in C# In this post we are going to learn about Func Delegates in C#. As per MSDN following is a definition. “Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.” Func can handle multiple arguments. The Func delegates is parameterized type. It takes any valid C# type as parameter and you have can multiple parameters and also you have specify the return type as last parameters. Followings are some examples of parameters. Func<int T,out TResult> Func<int T,int T, out Tresult> Now let’s take a string concatenation example for that. I am going to create two func delegate which will going to concate two strings and three string. Following is a code for that. using System; using System.Collections.Generic; namespace FuncExample { class Program { static void Main(string[] args) { Func<string, string, string> concatTwo = (x, y) => string.Format("{0} {1}",x,y); Func<string, string, string, string> concatThree = (x, y, z) => string.Format("{0} {1} {2}", x, y,z); Console.WriteLine(concatTwo("Hello", "Jalpesh")); Console.WriteLine(concatThree("Hello","Jalpesh","Vadgama")); Console.ReadLine(); } } } As you can see in above example, I have create two delegates ‘concatTwo’ and ‘concatThree. The first concat two strings and another concat three strings. If you see the func statements the last parameter is for the out as here its output string so I have written string as last parameter in both statements. Now it’s time to run the example and as expected following is output. That’s it. Hope you like it. Stay tuned for more updates.

    Read the article

  • C#/.NET Little Wonders: The Generic Func 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. Back in one of my three original “Little Wonders” Trilogy of posts, I had listed generic delegates as one of the Little Wonders of .NET.  Later, someone posted a comment saying said that they would love more detail on the generic delegates and their uses, since my original entry just scratched the surface of them. Last week, I began our look at some of the handy generic delegates built into .NET with a description of delegates in general, and the Action family of delegates.  For this week, I’ll launch into a look at the Func family of generic delegates and how they can be used to support generic, reusable algorithms and classes. Quick Delegate Recap Delegates are similar to function pointers in C++ in that they allow you to store a reference to a method.  They can store references to either static or instance methods, and can actually be used to chain several methods together in one delegate. Delegates are very type-safe and can be satisfied with any standard method, anonymous method, or a lambda expression.  They can also be null as well (refers to no method), so care should be taken to make sure that the delegate is not null before you invoke it. Delegates are defined using the keyword delegate, where the delegate’s type name is placed where you would typically place the method name: 1: // This delegate matches any method that takes string, returns nothing 2: public delegate void Log(string message); This delegate defines a delegate type named Log that can be used to store references to any method(s) that satisfies its signature (whether instance, static, lambda expression, etc.). Delegate instances then can be assigned zero (null) or more methods using the operator = which replaces the existing delegate chain, or by using the operator += which adds a method to the end of a delegate chain: 1: // creates a delegate instance named currentLogger defaulted to Console.WriteLine (static method) 2: Log currentLogger = Console.Out.WriteLine; 3:  4: // invokes the delegate, which writes to the console out 5: currentLogger("Hi Standard Out!"); 6:  7: // append a delegate to Console.Error.WriteLine to go to std error 8: currentLogger += Console.Error.WriteLine; 9:  10: // invokes the delegate chain and writes message to std out and std err 11: currentLogger("Hi Standard Out and Error!"); While delegates give us a lot of power, it can be cumbersome to re-create fairly standard delegate definitions repeatedly, for this purpose the generic delegates were introduced in various stages in .NET.  These support various method types with particular signatures. Note: a caveat with generic delegates is that while they can support multiple parameters, they do not match methods that contains ref or out parameters. If you want to a delegate to represent methods that takes ref or out parameters, you will need to create a custom delegate. We’ve got the Func… delegates Just like it’s cousin, the Action delegate family, the Func delegate family gives us a lot of power to use generic delegates to make classes and algorithms more generic.  Using them keeps us from having to define a new delegate type when need to make a class or algorithm generic. Remember that the point of the Action delegate family was to be able to perform an “action” on an item, with no return results.  Thus Action delegates can be used to represent most methods that take 0 to 16 arguments but return void.  You can assign a method The Func delegate family was introduced in .NET 3.5 with the advent of LINQ, and gives us the power to define a function that can be called on 0 to 16 arguments and returns a result.  Thus, the main difference between Action and Func, from a delegate perspective, is that Actions return nothing, but Funcs return a result. The Func family of delegates have signatures as follows: Func<TResult> – matches a method that takes no arguments, and returns value of type TResult. Func<T, TResult> – matches a method that takes an argument of type T, and returns value of type TResult. Func<T1, T2, TResult> – matches a method that takes arguments of type T1 and T2, and returns value of type TResult. Func<T1, T2, …, TResult> – and so on up to 16 arguments, and returns value of type TResult. These are handy because they quickly allow you to be able to specify that a method or class you design will perform a function to produce a result as long as the method you specify meets the signature. For example, let’s say you were designing a generic aggregator, and you wanted to allow the user to define how the values will be aggregated into the result (i.e. Sum, Min, Max, etc…).  To do this, we would ask the user of our class to pass in a method that would take the current total, the next value, and produce a new total.  A class like this could look like: 1: public sealed class Aggregator<TValue, TResult> 2: { 3: // holds method that takes previous result, combines with next value, creates new result 4: private Func<TResult, TValue, TResult> _aggregationMethod; 5:  6: // gets or sets the current result of aggregation 7: public TResult Result { get; private set; } 8:  9: // construct the aggregator given the method to use to aggregate values 10: public Aggregator(Func<TResult, TValue, TResult> aggregationMethod = null) 11: { 12: if (aggregationMethod == null) throw new ArgumentNullException("aggregationMethod"); 13:  14: _aggregationMethod = aggregationMethod; 15: } 16:  17: // method to add next value 18: public void Aggregate(TValue nextValue) 19: { 20: // performs the aggregation method function on the current result and next and sets to current result 21: Result = _aggregationMethod(Result, nextValue); 22: } 23: } Of course, LINQ already has an Aggregate extension method, but that works on a sequence of IEnumerable<T>, whereas this is designed to work more with aggregating single results over time (such as keeping track of a max response time for a service). We could then use this generic aggregator to find the sum of a series of values over time, or the max of a series of values over time (among other things): 1: // creates an aggregator that adds the next to the total to sum the values 2: var sumAggregator = new Aggregator<int, int>((total, next) => total + next); 3:  4: // creates an aggregator (using static method) that returns the max of previous result and next 5: var maxAggregator = new Aggregator<int, int>(Math.Max); So, if we were timing the response time of a web method every time it was called, we could pass that response time to both of these aggregators to get an idea of the total time spent in that web method, and the max time spent in any one call to the web method: 1: // total will be 13 and max 13 2: int responseTime = 13; 3: sumAggregator.Aggregate(responseTime); 4: maxAggregator.Aggregate(responseTime); 5:  6: // total will be 20 and max still 13 7: responseTime = 7; 8: sumAggregator.Aggregate(responseTime); 9: maxAggregator.Aggregate(responseTime); 10:  11: // total will be 40 and max now 20 12: responseTime = 20; 13: sumAggregator.Aggregate(responseTime); 14: maxAggregator.Aggregate(responseTime); The Func delegate family is useful for making generic algorithms and classes, and in particular allows the caller of the method or user of the class to specify a function to be performed in order to generate a result. What is the result of a Func delegate chain? If you remember, we said earlier that you can assign multiple methods to a delegate by using the += operator to chain them.  So how does this affect delegates such as Func that return a value, when applied to something like the code below? 1: Func<int, int, int> combo = null; 2:  3: // What if we wanted to aggregate the sum and max together? 4: combo += (total, next) => total + next; 5: combo += Math.Max; 6:  7: // what is the result? 8: var comboAggregator = new Aggregator<int, int>(combo); Well, in .NET if you chain multiple methods in a delegate, they will all get invoked, but the result of the delegate is the result of the last method invoked in the chain.  Thus, this aggregator would always result in the Math.Max() result.  The other chained method (the sum) gets executed first, but it’s result is thrown away: 1: // result is 13 2: int responseTime = 13; 3: comboAggregator.Aggregate(responseTime); 4:  5: // result is still 13 6: responseTime = 7; 7: comboAggregator.Aggregate(responseTime); 8:  9: // result is now 20 10: responseTime = 20; 11: comboAggregator.Aggregate(responseTime); So remember, you can chain multiple Func (or other delegates that return values) together, but if you do so you will only get the last executed result. Func delegates and co-variance/contra-variance in .NET 4.0 Just like the Action delegate, as of .NET 4.0, the Func delegate family is contra-variant on its arguments.  In addition, it is co-variant on its return type.  To support this, in .NET 4.0 the signatures of the Func delegates changed to: Func<out TResult> – matches a method that takes no arguments, and returns value of type TResult (or a more derived type). Func<in T, out TResult> – matches a method that takes an argument of type T (or a less derived type), and returns value of type TResult(or a more derived type). Func<in T1, in T2, out TResult> – matches a method that takes arguments of type T1 and T2 (or less derived types), and returns value of type TResult (or a more derived type). Func<in T1, in T2, …, out TResult> – and so on up to 16 arguments, and returns value of type TResult (or a more derived type). Notice the addition of the in and out keywords before each of the generic type placeholders.  As we saw last week, the in keyword is used to specify that a generic type can be contra-variant -- it can match the given type or a type that is less derived.  However, the out keyword, is used to specify that a generic type can be co-variant -- it can match the given type or a type that is more derived. On contra-variance, if you are saying you need an function that will accept a string, you can just as easily give it an function that accepts an object.  In other words, if you say “give me an function that will process dogs”, I could pass you a method that will process any animal, because all dogs are animals.  On the co-variance side, if you are saying you need a function that returns an object, you can just as easily pass it a function that returns a string because any string returned from the given method can be accepted by a delegate expecting an object result, since string is more derived.  Once again, in other words, if you say “give me a method that creates an animal”, I can pass you a method that will create a dog, because all dogs are animals. It really all makes sense, you can pass a more specific thing to a less specific parameter, and you can return a more specific thing as a less specific result.  In other words, pay attention to the direction the item travels (parameters go in, results come out).  Keeping that in mind, you can always pass more specific things in and return more specific things out. For example, in the code below, we have a method that takes a Func<object> to generate an object, but we can pass it a Func<string> because the return type of object can obviously accept a return value of string as well: 1: // since Func<object> is co-variant, this will access Func<string>, etc... 2: public static string Sequence(int count, Func<object> generator) 3: { 4: var builder = new StringBuilder(); 5:  6: for (int i=0; i<count; i++) 7: { 8: object value = generator(); 9: builder.Append(value); 10: } 11:  12: return builder.ToString(); 13: } Even though the method above takes a Func<object>, we can pass a Func<string> because the TResult type placeholder is co-variant and accepts types that are more derived as well: 1: // delegate that's typed to return string. 2: Func<string> stringGenerator = () => DateTime.Now.ToString(); 3:  4: // This will work in .NET 4.0, but not in previous versions 5: Sequence(100, stringGenerator); Previous versions of .NET implemented some forms of co-variance and contra-variance before, but .NET 4.0 goes one step further and allows you to pass or assign an Func<A, BResult> to a Func<Y, ZResult> as long as A is less derived (or same) as Y, and BResult is more derived (or same) as ZResult. Sidebar: The Func and the Predicate A method that takes one argument and returns a bool is generally thought of as a predicate.  Predicates are used to examine an item and determine whether that item satisfies a particular condition.  Predicates are typically unary, but you may also have binary and other predicates as well. Predicates are often used to filter results, such as in the LINQ Where() extension method: 1: var numbers = new[] { 1, 2, 4, 13, 8, 10, 27 }; 2:  3: // call Where() using a predicate which determines if the number is even 4: var evens = numbers.Where(num => num % 2 == 0); As of .NET 3.5, predicates are typically represented as Func<T, bool> where T is the type of the item to examine.  Previous to .NET 3.5, there was a Predicate<T> type that tended to be used (which we’ll discuss next week) and is still supported, but most developers recommend using Func<T, bool> now, as it prevents confusion with overloads that accept unary predicates and binary predicates, etc.: 1: // this seems more confusing as an overload set, because of Predicate vs Func 2: public static SomeMethod(Predicate<int> unaryPredicate) { } 3: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } 4:  5: // this seems more consistent as an overload set, since just uses Func 6: public static SomeMethod(Func<int, bool> unaryPredicate) { } 7: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } Also, even though Predicate<T> and Func<T, bool> match the same signatures, they are separate types!  Thus you cannot assign a Predicate<T> instance to a Func<T, bool> instance and vice versa: 1: // the same method, lambda expression, etc can be assigned to both 2: Predicate<int> isEven = i => (i % 2) == 0; 3: Func<int, bool> alsoIsEven = i => (i % 2) == 0; 4:  5: // but the delegate instances cannot be directly assigned, strongly typed! 6: // ERROR: cannot convert type... 7: isEven = alsoIsEven; 8:  9: // however, you can assign by wrapping in a new instance: 10: isEven = new Predicate<int>(alsoIsEven); 11: alsoIsEven = new Func<int, bool>(isEven); So, the general advice that seems to come from most developers is that Predicate<T> is still supported, but we should use Func<T, bool> for consistency in .NET 3.5 and above. Sidebar: Func as a Generator for Unit Testing One area of difficulty in unit testing can be unit testing code that is based on time of day.  We’d still want to unit test our code to make sure the logic is accurate, but we don’t want the results of our unit tests to be dependent on the time they are run. One way (of many) around this is to create an internal generator that will produce the “current” time of day.  This would default to returning result from DateTime.Now (or some other method), but we could inject specific times for our unit testing.  Generators are typically methods that return (generate) a value for use in a class/method. For example, say we are creating a CacheItem<T> class that represents an item in the cache, and we want to make sure the item shows as expired if the age is more than 30 seconds.  Such a class could look like: 1: // responsible for maintaining an item of type T in the cache 2: public sealed class CacheItem<T> 3: { 4: // helper method that returns the current time 5: private static Func<DateTime> _timeGenerator = () => DateTime.Now; 6:  7: // allows internal access to the time generator 8: internal static Func<DateTime> TimeGenerator 9: { 10: get { return _timeGenerator; } 11: set { _timeGenerator = value; } 12: } 13:  14: // time the item was cached 15: public DateTime CachedTime { get; private set; } 16:  17: // the item cached 18: public T Value { get; private set; } 19:  20: // item is expired if older than 30 seconds 21: public bool IsExpired 22: { 23: get { return _timeGenerator() - CachedTime > TimeSpan.FromSeconds(30.0); } 24: } 25:  26: // creates the new cached item, setting cached time to "current" time 27: public CacheItem(T value) 28: { 29: Value = value; 30: CachedTime = _timeGenerator(); 31: } 32: } Then, we can use this construct to unit test our CacheItem<T> without any time dependencies: 1: var baseTime = DateTime.Now; 2:  3: // start with current time stored above (so doesn't drift) 4: CacheItem<int>.TimeGenerator = () => baseTime; 5:  6: var target = new CacheItem<int>(13); 7:  8: // now add 15 seconds, should still be non-expired 9: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(15); 10:  11: Assert.IsFalse(target.IsExpired); 12:  13: // now add 31 seconds, should now be expired 14: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(31); 15:  16: Assert.IsTrue(target.IsExpired); Now we can unit test for 1 second before, 1 second after, 1 millisecond before, 1 day after, etc.  Func delegates can be a handy tool for this type of value generation to support more testable code.  Summary Generic delegates give us a lot of power to make truly generic algorithms and classes.  The Func family of delegates is a great way to be able to specify functions to calculate a result based on 0-16 arguments.  Stay tuned in the weeks that follow for other generic delegates in the .NET Framework!   Tweet Technorati Tags: .NET, C#, CSharp, Little Wonders, Generics, Func, Delegates

    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

  • JQuery: how to use "delegate" instead of "live"?

    - by JacobD
    I've read countless articles how using the JQuery delegate is much more efficient than using the "live" event. As such, I'm having trouble converting my existing Live code to using Delegate. $("#tabs li:eq(0)").live('click',function(){ //...code }); $('#A > div.listing, #B > div.listing, #C > div.listing').live('mouseover',function(){ // ...code }); When I replace the previous code with what I assume is more efficient delegate code, my page doesn't load. $("#tabs li:eq(0)").delegate('click',function(){ //...code }); $('#A > div.listing, #B > div.listing, #C > div.listing').delegate('mouseover',function(){ // ...code }); Any idea why my delegate code doesn't work? Also, any suggestions on how to make this more efficient? UPDATE: The think part of the problem is that, both "#tabs" and "#A, #B, #C" are't present on the web page at page load. Those attributes are dynamically inserted onto the page with an AJAX call. As such, does that mean I have to use live over delegate?

    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

  • C#&ndash;Using a delegate to raise an event from one class to another

    - by Bill Osuch
    Even though this may be a relatively common task for many people, I’ve had to show it to enough new developers that I figured I’d immortalize it… MSDN says “Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.” Any time you add a button to a Windows Form or Web app, you can subscribe to the OnClick event, and you can also create your own event handlers to pass events between classes. Here I’ll show you how to raise an event from a separate class to a console application (or Windows Form). First, create a console app project (you could create a Windows Form, but this is easier for this demo). Add a class file called MyEvent.cs (it doesn’t really need to be a separate file, this is just for clarity) with the following code: public delegate void MyHandler1(object sender, MyEvent e); public class MyEvent : EventArgs {     public string message; } Your event can have whatever public properties you like; here we’re just got a single string. Next, add a class file called WorkerDLL.cs; this will simulate the class that would be doing all the work in the project. Add the following code: class WorkerDLL {     public event MyHandler1 Event1;     public WorkerDLL()     {     }     public void DoWork()     {         FireEvent("From Worker: Step 1");         FireEvent("From Worker: Step 5");         FireEvent("From Worker: Step 10");     }     private void FireEvent(string message)     {         MyEvent e1 = new MyEvent();         e1.message = message;         if (Event1 != null)         {             Event1(this, e1);         }         e1 = null;     } } Notice that the FireEvent method creates an instance of the MyEvent class and passes it to the Event1 handler (which we’ll create in just a second). Finally, add the following code to Program.cs: static void Main(string[] args) {     Program p = new Program(args); } public Program(string[] args) {     Console.WriteLine("From Console: Creating DLL");     WorkerDLL wd = new WorkerDLL();     Console.WriteLine("From Console: Wiring up event handler");     WireEventHandlers(wd);     Console.WriteLine("From Console: Doing the work");     wd.DoWork();     Console.WriteLine("From Console: Done - press any key to finish.");     Console.ReadLine(); } private void WireEventHandlers(WorkerDLL wd) {     MyHandler1 handler = new MyHandler1(OnHandler1);     wd.Event1 += handler; } public void OnHandler1(object sender, MyEvent e) {     Console.WriteLine(e.message); } The OnHandler1 method is called any time the event handler “hears” an event matching the specified signature – you could have it log to a file, write to a database, etc. Run the app in debug mode and you should see output like this: You can distinctly see which lines were written by the console application itself (Program.cs) and which were written by the worker class (WorkerDLL.cs). Technorati Tags: Csharp

    Read the article

  • Delegates does not work properly

    - by Warrior
    I am new to iPhone development. I am converting the date to the desired format and set it to the delegate and get its value in the another view. The session restarts when I tried to get the value from delegate. If I set the original date and not the formatted date in the set delegate, then i able to get the value in the another view. If I also give any static string value, then also I am able to the static string value back. Only the formatted date which is string is set then the session restarts. If i print and check the value of the formatted date it prints the correct formatted date only.Please help me out.Here is my code for date conversion NSString *dateval=[[stories objectAtIndex: storyIndex] objectForKey:@"date"]; NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; [inputFormatter setDateFormat:@"EEE, MMM dd, yyyy"]; NSDate *inputDate = [inputFormatter dateFromString:dateval]; NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; [outputFormatter setDateFormat:@"MMMM dd"]; NSString *outputDate = [outputFormatter stringFromDate:inputDate]; AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate]; [delegate setCurrentDates:outputDate]; EDIT: This is displayed in console inside view did load [Session started at 2010-04-21 19:12:53 +0530.] GNU gdb 6.3.50-20050815 (Apple version gdb-967) (Tue Jul 14 02:11:58 UTC 2009) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 4216. (gdb) In another view - (void)viewDidLoad { NSLog(@"inside view did load"); AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate]; NSString *titleValue=[delegate getCurrentDates]; self.navigationItem.title =titleValue ; } The get does not work properly.It works fine if i give any static string or the "dateval". Thanks.

    Read the article

  • Using Delegates in C# (Part 1)

    - by rajbk
    This post provides a very basic introduction of delegates in C#. Part 2 of this post can be read here. A delegate is a class that is derived from System.Delegate.  It contains a list of one or more methods called an invocation list. When a delegate instance is “invoked” with the arguments as defined in the signature of the delegate, each of the methods in the invocation list gets invoked with the arguments. The code below shows example with static and instance methods respectively: Static Methods 1: using System; 2: using System.Linq; 3: using System.Collections.Generic; 4: 5: public delegate void SayName(string name); 6: 7: public class Program 8: { 9: [STAThread] 10: static void Main(string[] args) 11: { 12: SayName englishDelegate = new SayName(SayNameInEnglish); 13: SayName frenchDelegate = new SayName(SayNameInFrench); 14: SayName combinedDelegate =(SayName)Delegate.Combine(englishDelegate, frenchDelegate); 15: 16: combinedDelegate.Invoke("Tom"); 17: Console.ReadLine(); 18: } 19: 20: static void SayNameInFrench(string name) { 21: Console.WriteLine("J'ai m'appelle " + name); 22: } 23: 24: static void SayNameInEnglish(string name) { 25: Console.WriteLine("My name is " + name); 26: } 27: } We have declared a delegate of type SayName with return type of void and taking an input parameter of name of type string. On line 12, we create a new instance of this delegate which refers to a static method - SayNameInEnglish.  SayNameInEnglish has the same return type and parameter list as the delegate declaration.  Once a delegate is instantiated, the instance will always refer to the same target. Delegates are immutable. On line 13, we create a new instance of the delegate but point to a different static method. As you may recall, a delegate instance encapsulates an invocation list. You create an invocation list by combining delegates using the Delegate.Combine method (there is an easier syntax as you will see later). When two non null delegate instances are combined, their invocation lists get combined to form a new invocation list. This is done in line 14.  On line 16, we invoke the delegate with the Invoke method and pass in the required string parameter. Since the delegate has an invocation list with two entries, each of the method in the invocation list is invoked. If an unhandled exception occurs during the invocation of one of these methods, the exception gets bubbled up to the line where the invocation was made (line 16). If a delegate is null and you try to invoke it, you will get a System.NullReferenceException. We see the following output when the method is run: My name is TomJ'ai m'apelle Tom Instance Methods The code below outputs the same results as before. The only difference here is we are creating delegates that point to a target object (an instance of Translator) and instance methods which have the same signature as the delegate type. The target object can never be null. We also use the short cut syntax += to combine the delegates instead of Delegate.Combine. 1: public delegate void SayName(string name); 2: 3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Translator translator = new Translator(); 9: SayName combinedDelegate = new SayName(translator.SayNameInEnglish); 10: combinedDelegate += new SayName(translator.SayNameInFrench); 11:  12: combinedDelegate.Invoke("Tom"); 13: Console.ReadLine(); 14: } 15: } 16: 17: public class Translator { 18: public void SayNameInFrench(string name) { 19: Console.WriteLine("J'ai m'appelle " + name); 20: } 21: 22: public void SayNameInEnglish(string name) { 23: Console.WriteLine("My name is " + name); 24: } 25: } A delegate can be removed from a combination of delegates by using the –= operator. Removing a delegate from an empty list or removing a delegate that does not exist in a non empty list will not result in an exception. Delegates are invoked synchronously using the Invoke method. We can also invoke them asynchronously using the BeginInvoke and EndInvoke methods which are compiler generated.

    Read the article

  • Get compiler generated delegate for an event

    - by Sandor Davidhazi
    I need to know what handlers are subsribed to the CollectionChanged event of the ObservableCollection class. The only solution I found would be to use Delegate.GetInvocationList() on the delegate of the event. The problem is, I can't get Reflection to find the compiler generated delegate. AFAIK the delegate has the same name as the event. I used the following piece of code: PropertyInfo notifyCollectionChangedDelegate = collection.GetType().GetProperty("CollectionChanged", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

    Read the article

  • Jquery live() vs delegate()

    - by PeeHaa
    I've read some posts here and on the web about the differences of live() and delegate(). However I haven't found the answer I'm looking for (if this is a dupe please tell me). I know the difference between live and delegate is that live can not be used in a chain. As I also read somewhere delegate is in some case faster (better performance). So I am wondering is there a situation where you would use live instead of delegate?

    Read the article

  • Delegate, BeginInvoke. EndInvoke - How to clean up multiple Async threat calls to the same delegate?

    - by Dan
    I've created a Delegate that I intend to call Async. Module Level Delegate Sub GetPartListDataFromServer(ByVal dvOriginal As DataView, ByVal ProgramID As Integer) Dim dlgGetPartList As GetPartListDataFromServer The following code I use in a method Dim dlgGetPartList As New GetPartListDataFromServer(AddressOf AsyncThreadMethod_GetPartListDataFromServer) dlgGetPartList.BeginInvoke(ucboPart.DataSource, ucboProgram.Value, AddressOf AsyncCallback_GetPartListDataFromServer, Nothing) The method runs and does what it needs to The Asyn callback is fired upon completion where I do an EndInvoke Sub AsyncCallback_GetPartListDataFromServer(ByVal ar As IAsyncResult) dlgGetPartList.EndInvoke(Nothing) End Sub It works as long as the method that starts the BeginInvoke on the delegate only ever runs while there is not a BeginInvoke/Thread operation already running. Problem is that the a new thread could be invoked while another thread on the delegate is still running and hasnt yet been EndInvoke'd. The program needs to be able to have the delegate run in more than one instance at a time if necessary and they all need to complete and have EndInvoke called. Once I start another BeginInvoke I lose the reference to the first BeginInvoke so I am unable to clean up the new thread with an EndInvoke. What is a clean solution and best practice to overcome this problem?

    Read the article

  • UITableView programatically create delegate object?

    - by fuzzygoat
    I have a question regarding setting up a custom delegate class for use with UITableView. What I have done is as follows: Setup a new class (in sperate *.h and *.m files for the class) Conformed that new class to the <UITableViewDelegate, UITableViewDataSource> protocols Added the required methods. Created a pointer to the new object using @property and IBOutlet. In InterfaceBuilder created and assigned an object template to my new class Assigned the dataSource and delegate connections. This all works fine. My question is if I don't want to use interfaceBuilder to setup and instantiate my new delegate class directly in Xcode how do I go about doing that? More specifically how would I: Instantiate the delegate class, would that be created / owned by the controller? Set the dataSource and delegate connections? What is the best way of doing this? any help / information is much appreciated. Gary

    Read the article

  • Delegate Instantiation -Clarification

    - by nettguy
    When i have delegate like public delegate void PrintMe(); (1) PrintMe a = delegate() { MessageBox.Show("Hello"); }; a(); (2) PrintMe b = () => { MessageBox.Show("Hello"); }; b(); (3) PrintMe c = new PrintMe(HelpMe); c(); static void HelpMe() { MessageBox.Show("Help Me"); } for (1) and (2) I did not instatntiate the delegate it is directly pointing to anonymous methods.But as in the case of (3) I need to instatntiate the delegate and pass the static method.for case (3) can't i declare like PrintMe c= HelpMe(); ?.How does (1) and (2) work?

    Read the article

  • setting up delegate or smtp forwarding

    - by cotiso
    for work we have a remote dedicated server to run our webservice that also runs our email services, at home(comcast residential internet) i cannot send mail using the dedicated server's SMTP, comcast spits back a error saying i can only use their SMTP server for sending mail at work(comcast business internet) we can use our dedicated server for sending mail with no problem so i set up a box at work to forward smtp traffic, i'm new to all this networking stuff by the way i used delegate to forward smtp traffic, can someone point me in the right direction on how to use this program(delegate) to fix our issue the delegate command i used to test is : delegated -P25 SERVER="smtp://dedicated.server.com:25" PERMIT=":::" -v i also opened up port 25 on the router so it points to my boxes ip are there any other ways to fool comcast into thinking im using my works ip to send mail, my coworkers and i are unable to send mail from home for some time now thanks

    Read the article

  • JQuery delegate what may cause it to not function

    - by Jafin
    I have a webpage using jquery 1.42 The following 2 segments of code live in my page. $('body').delegate('h2', 'click', function() { $(this).after("<p>delegate paragraph!<\/p>"); }); $('body h2').live('click', function() { $(this).after("<p>live paragraph!<\/p>"); }); The live method always works, yet the delegate doesn't fire at all. If I create a trivial page with simple html <body><h2>blah</h2></body> both approaches work. So I'm assuming there is something else going on in my page. With firebug I am seeing no javascript errors, no html errors. and breakpoints on the delegate method definately do not get hit. What else might be the cause of delegate not triggering?

    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

  • two view controllers and reusability with delegate

    - by netcharmer
    Newbie question about design patterns in objC. I'm writing a functionality for my iphone app which I plan to use in other apps too. The functionality is written over two classes - Viewcontroller1 and Viewcontroller2. Viewcontroller1 is the root view of a navigation controller and it can push Viewcontroller2. Rest of the app will use only ViewController1 and will never access Viewcontroller2 directly. However, triggered by user events, Viewcontroller2 has to send a message to the rest of the app. My question is what is the best way of achieving it? Currently, I use two level of delegation to send the message out from Viewcontroller2. First send it to Viewcontroller1 and then let Viewcontroller1 send it to rest of the app or the application delegate. So my code looks like - //Viewcontroller1.h @protocol bellDelegate -(int)bellRang:(int)size; @end @interface Viewcontroller1 : UITableViewController <dummydelegate> { id <bellDelegate> delegate; @end //Viewcontroller1.m @implementation Viewcontroller1 -(void)viewDidLoad { //some stuff here Viewcontroller2 *vc2 = [[Viewcontroller2 alloc] init]; vc2.delegate = self; [self.navigationController pushViewController:vc2 animated:YES]; } -(int)dummyBell:(int)size { return([self.delegate bellRang:size]); } //Viewcontroller2.h @protocol dummyDelegate -(int)dummyBell:(int)size; @end @interface Viewcontroller2 : UITableViewController { id <dummyDelegate> delegate; @end //Viewcontroller2.m @implementation Viewcontroller2 -(int)eventFoo:(int)size { rval = [self.delegate dummyBell:size]; } @end

    Read the article

  • ReplaceBetweenTags function with delegate to describe transformation

    - by Michael Freidgeim
    I've created a function that allow to replace content between XML tags with data, that depend on original content within tag, in particular to MAsk credit card number.The function uses MidBetween extension from My StringHelper class /// <summary> /// /// </summary> /// <param name="thisString"></param> /// <param name="openTag"></param> /// <param name="closeTag"></param> /// <param name="transform"></param> /// <returns></returns> /// <example> /// // mask <AccountNumber>XXXXX4488</AccountNumber> ///requestAsString  = requestAsString.ReplaceBetweenTags("<AccountNumber>", "</AccountNumber>", CreditCard.MaskedCardNumber); ///mask cvv ///requestAsString = requestAsString.ReplaceBetweenTags("<FieldName>CC::VerificationCode</FieldName><FieldValue>", "</FieldValue>", cvv=>"XXX"); /// </example> public static string ReplaceBetweenTags(this string thisString, string openTag, string closeTag, Func<string, string> transform) { //See also http://stackoverflow.com/questions/1359412/c-sharp-remove-text-in-between-delimiters-in-a-string-regex string sRet = thisString; string between = thisString.MidBetween(openTag, closeTag, true); if (!String.IsNullOrEmpty(between)) sRet=thisString.Replace(openTag + between + closeTag, openTag + transform(between) + closeTag); return sRet; } public static string ReplaceBetweenTags(this string thisString, string openTag, string closeTag, string newValue) { //See also http://stackoverflow.com/questions/1359412/c-sharp-remove-text-in-between-delimiters-in-a-string-regex string sRet = thisString; string between = thisString.MidBetween(openTag, closeTag, true); if (!String.IsNullOrEmpty(between)) sRet = thisString.Replace(openTag + between + closeTag, openTag + newValue + closeTag); return sRet; }

    Read the article

  • Interacting with scene from controller/app delegate cocos2d

    - by cjroebuck
    I'm attempting to make my first cocos2d (for iphone) multiplayer game and having difficulty understanding how to interact with a scene once it is running. The game is a simple turn-based one and so I have a GameController class which co-ordinates the rounds. I also have a GameScene class which is the actual scene that is displayed during a round of the game. The basic interaction I need is for the GameController to be able to pass messages to the GameScene class.. such as StartRound/StopRound etc. The thing that complicates this is that I am loading the GameScene with a LoadingScene class which simply initialises the scene and replaces the current scene with this one, so there is no reference from GameController to GameScene, so passing messages is quite tricky. Does anyone have any ways to get around this, ideally I would still like to use a Loading class as it smooths out the memory hit when replacing scenes.

    Read the article

  • Delegate.CreateDelegate() and generics: Error binding to target method

    - by SDReyes
    I'm having problems creating a collection of delegate using reflection and generics. I'm trying to create a delegate collection from Ally methods, whose share a common method signature. public class Classy { public string FirstMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); public string SecondMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); public string ThirdMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); // And so on... } And the generics cooking: // This is the Classy's shared method signature public delegate string classyDelegate<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> filter ); // And the linq-way to get the collection of delegates from Classy ( from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic ) let delegateType = typeof( classyDelegate<,> ) select Delegate.CreateDelegate( delegateType, method ) ).ToList( ); But the Delegate.CreateDelegate( delegateType, method ) throws an ArgumentException saying Error binding to target method. : / What am I doing wrong?

    Read the article

  • Need to Release UIWebView Delegate?

    - by Chris
    I have a UIWebView named wView. I want to use webViewDidFinishLoad: in my class, so I am setting the class as the delegate for wView by using this line: wView.delegate = self; Everything loads properly, but when I close the UIWebView, the App crashes. If I comment out the wView.delegate = self, it works and does not crash, but then I can't use webViewDidFinishLoad: - any ideas? Do I need to release something?

    Read the article

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