Search Results

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

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

  • Are delegates copied during assignment to an event?

    - by Sir Psycho
    Hi, The following code seems to execute the FileRetrieved event more than once. I thought delegates were a reference type. I was expecting this to execute once. I'm going to take a guess and say that the reference is being passed by value, therefore copied but I don't like guesswork :-) public delegate void DirListEvent<T>(T dirItem); void Main() { DirListEvent<string> printFilename = s => { Console.WriteLine (s); }; var obj = new DirectoryLister(); obj.FileRetrieved += printFilename; obj.FileRetrieved += printFilename; obj.GetDirListing(); } public class DirectoryLister { public event DirListEvent<string> FileRetrieved; public DirectoryLister() { FileRetrieved += delegate {}; } public void GetDirListing() { foreach (var file in Directory.GetFiles(@"C:\")) { FileRetrieved(file); } } }

    Read the article

  • Are static delegates thread-safe?

    - by leypascua
    Consider this code snippet: public static class ApplicationContext { private static Func<TService> Uninitialized<TService>() { throw new InvalidOperationException(); } public static Func<IAuthenticationProvider> AuthenticationProvider = Uninitialized<IAuthenticationProvider>(); public static Func<IUnitOfWorkFactory> UnitOfWorkFactory = Uninitialized<IUnitOfWorkFactory>(); } //can also be in global.asax if used in a web app. public static void Main(string[] args) { ApplicationContext.AuthenticationProvider = () => new LdapAuthenticationProvider(); ApplicationContext.UnitOfWorkFactory = () => new EFUnitOfWorkFactory(); } //somewhere in the code.. say an ASP.NET MVC controller ApplicationContext.AuthenticationProvider().SignIn(username, true); Are delegates in the static class ApplicationContext thread-safe in the sense that multiple-threads can invoke them? What potential problems will I face if I pursue this approach?

    Read the article

  • c# Delegates, Events and Lambda Expr for new students

    - by MarkP
    I've been asked by my pointy haired boss to educate our new co-ops (interns) in the ways of C#. I have roughly ~30mins to cover the topics of Delegates, Events and Lambda Expressions. The time restriction is rather tight and the topics are broad. Since I'm not a C# guru, I would like some hints and pointers. Since my time is short, what points should I cover with respect to the three topics listed above? What are some good Do's and Dont's when using those three things? I might have time for a short Lambda Expr demo. What is the most common use of LExpr (probably a Select().Where() statement on an enumerable??) that I could demo? Thanks. EDIT: The students have working knowledge of C++ and Java.

    Read the article

  • Delegates in .NET: how are they constructed ?

    - by Saulius
    While inspecting delegates in C# and .NET in general, I noticed some interesting facts: Creating a delegate in C# creates a class derived from MulticastDelegate with a constructor: .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } Meaning that it expects the instance and a pointer to the method. Yet the syntax of constructing a delegate in C# suggests that it has a constructor new MyDelegate(int () target) where I can recognise int () as a function instance (int *target() would be a function pointer in C++). So obviously the C# compiler picks out the correct method from the method group defined by the function name and constructs the delegate. So the first question would be, where does the C# compiler (or Visual Studio, to be precise) pick this constructor signature from ? I did not notice any special attributes or something that would make a distinction. Is this some sort of compiler/visualstudio magic ? If not, is the T (args) target construction valid in C# ? I did not manage to get anything with it to compile, e.g.: int () target = MyMethod; is invalid, so is doing anything with MyMetod, e.g. calling .ToString() on it (well this does make some sense, since that is technically a method group, but I imagine it should be possible to explicitly pick out a method by casting, e.g. (int())MyFunction. So is all of this purely compiler magic ? Looking at the construction through reflector reveals yet another syntax: Func CS$1$0000 = new Func(null, (IntPtr) Foo); This is consistent with the disassembled constructor signature, yet this does not compile! One final interesting note is that the classes Delegate and MulticastDelegate have yet another sets of constructors: .method family hidebysig specialname rtspecialname instance void .ctor(class System.Type target, string 'method') cil managed Where does the transition from an instance and method pointer to a type and a string method name occur ? Can this be explained by the runtime managed keywords in the custom delegate constructor signature, i.e. does the runtime do it's job here ?

    Read the article

  • Different behavior of reflected generic delegates with and without debugger

    - by Andrew_B
    Hello. We have encountered some strange things while calling reflected generic delegates. In some cases with attatched debuger we can make impossible call, while without debugger we cannot catch any exception and application fastfails. Here is the code: using System; using System.Windows.Forms; using System.Reflection; namespace GenericDelegate { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate Class2 Delegate1(); private void button1_Click(object sender, EventArgs e) { MethodInfo mi = typeof (Class1<>).GetMethod("GetClass", BindingFlags.NonPublic | BindingFlags.Static); if (mi != null) { Delegate1 del = (Delegate1) Delegate.CreateDelegate(typeof (Delegate1), mi); MessageBox.Show("1"); try { del(); } catch (Exception) { MessageBox.Show("No, I can`t catch it"); } MessageBox.Show("2"); mi.Invoke(null, new object[] {});//It's Ok, we'll get exception here MessageBox.Show("3"); } } class Class2 { } class Class1<T> : Class2 { internal static Class2 GetClass() { Type type = typeof(T); MessageBox.Show("Type name " + type.FullName +" Type: " + type + " Assembly " + type.Assembly); return new Class1<T>(); } } } } There are two problems: Behavior differs with debugger and without You cannot catch this error without debugger by clr tricks. It's just not the clr exception. There are memory acces vialation, reading zero pointer inside of internal code. Use case: You develop something like plugins system for your app. You read external assembly, find suitable method in some type, and execute it. And we just forgot about that we need to check up is the type generic or not. Under VS (and .net from 2.0 to 4.0) everything works fine. Called function does not uses static context of generic type and type parameters. But without VS application fails with no sound. We even cannot identify call stack attaching debuger. Tested with .net 4.0 The question is why VS catches but runtime do not?

    Read the article

  • Lambda expressions as CLR (.NET) delegates / event handlers in Visual C++ 2010

    - by absence
    Is it possible to use the new lambda expressions in Visual C++ 2010 as CLR event handlers? I've tried the following code: SomeEvent += gcnew EventHandler( [] (Object^ sender, EventArgs^ e) { // code here } ); It results in the following error message: error C3364: 'System::EventHandler' : invalid argument for delegate constructor; delegate target needs to be a pointer to a member function Am I attempting the impossible, or is simply my syntax wrong?

    Read the article

  • Problem using delegates, static, and dependencyproperties

    - by red-X
    I'm trying to animate a private variable named radius, which works. However while its changing I'm trying to execute a function which is getting to be quite of a problem. the code i have is below, it wont run because it has the following error An object reference is required for the non-static field, method, or property 'AppPart.SetChildrenPosition()' specifically new SetChildrenPositionDelegate(SetChildrenPosition) this part in this sentance part.Dispatcher.BeginInvoke(new SetChildrenPositionDelegate(SetChildrenPosition), new Object()); thnx to anyone able to help me. class AppPart : Shape { public string name { get; set; } public List<AppPart> parts { get; set; } private double radius { get { return (double)GetValue(radiusProperty); } set { SetValue(radiusProperty, value); } } public static readonly DependencyProperty radiusProperty = DependencyProperty.Register( "radius", typeof(double), typeof(AppPart), new PropertyMetadata( new PropertyChangedCallback(radiusChangedCallback))); private delegate void SetChildrenPositionDelegate(); private void SetChildrenPosition() { //do something with radius } private static void radiusChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { AppPart part = d as AppPart; part.Dispatcher.BeginInvoke(new SetChildrenPositionDelegate(SetChildrenPosition), new Object()); } private void AnimateRadius(double start, double end) { DoubleAnimation ani = new DoubleAnimation(); ani.From = start; ani.To = end; ani.FillBehavior = FillBehavior.HoldEnd; ani.Duration = new Duration(new TimeSpan(0, 0, 0, 3, 0)); ani.Completed += delegate { Console.WriteLine("ani ended"); }; this.BeginAnimation(AppPart.radiusProperty, ani); } }

    Read the article

  • Question about Multicast Delegates?

    - by IbrarMumtaz
    I am going through some exam questions for the 70-536 exam and an actual question one developer posted on his blog has popped up in my exam questions. I cannot remember what his answer was .... but below is the question: You need to write a multicast delegate that accepts a DateTime argument and returns a bool value. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) The answer is A. Can someone please explain why? As I already did some research into this question a while ago and so I was sure that it was C, obviously now looking back at the question its clear that I did not read properly. As i was sure I had seen the same one before so I jumped to the most obvious one. A variation on this question: You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) Now this is another variation on this question, it still has the same bogus sample answers, as they still kind work in throwing the exam taker off. Notice how by simply keeping the sample answers the same and by removing a small portion of the question text, the answer is C and not A. The variation has no official answer as I just conjured it up using the exam question as a baseplate. The answer is definitely C. This time round its easy to see why C is correct but the very first question I have an inkling but as you know an inkling is not good enough in passing exams. Thanks For Reading.

    Read the article

  • Understanding AddHandler and pass delegates and events.

    - by Achilles
    I am using AddHandler to wire a function to a control's event that I dynamically create: Public Sub BuildControl(EventHandler as System.Delegate) dim objMyButton as new button AddHandler objMyButton.Click, EventHandler end Sub This code is generating a run-time exception stating: Unable to cast object of type 'MyEventHandlerDelegate' to type 'System.EventHandler' What am I not understanding about System.Delegate even though AddHandler takes as an argument of type "System.Delegate"? What Type does "EventHandler need to be to cast to a type that AddHandler can accept? Thanks for your help!

    Read the article

  • A question on delegates and method parameters

    - by Srinivas Reddy Thatiparthy
    public class Program { delegate void Srini(string param); static void Main(string[] args) { Srini sr = new Srini(PrintHello1); sr += new Srini(PrintHello2); //case 2: sr += new Srini(delegate(string o) { Console.WriteLine(o); }); sr += new Srini(delegate(object o) { Console.WriteLine(o.ToString()); }); //case 4: sr += new Srini(delegate { Console.WriteLine(“This line is accepted,though the method signature is not Comp”); });//case 5 sr("Hello World"); Console.Read(); } static void PrintHello1(string param) { Console.WriteLine(param); } static void PrintHello2(object param) { Console.WriteLine(param); } } Compiler doesn't complain about the case 2(see the comment),well,the reason is straight forward since string inherits from object. ,along the same lines ,Why is it complaining for anonymous method types(see the comment //case 4:) that “Cannot convert anonymous method to delegate type 'DelegateTest.Program.Srini' because the parameter types do not match the delegate parameter types” where as in case of normal method it doesn't ?or am i comparing apples with oranges? Another case is why is it accepting anonymous method without parameters?

    Read the article

  • Logging class using delegates (NullReferenceException)

    - by Leroy Jenkins
    I have created a small application but I would now like to incorporate some type of logging that can be viewed via listbox. The source of the data can be sent from any number of places. I have created a new logging class that will pass in a delegate. I think Im close to a solution but Im receiving a NullReferenceException and I don’t know the proper solution. Here is an example of what Im trying to do: Class1 where the inbound streaming data is received. class myClass { OtherClass otherClass = new OtherClass(); otherClass.SendSomeText(myString); } Logging Class class OtherClass { public delegate void TextToBox(string s); TextToBox textToBox; Public OtherClass() { } public OtherClass(TextToBox ttb) { textToBox = ttb; } public void SendSomeText(string foo) { textToBox(foo); } } The Form public partial class MainForm : Form { OtherClass otherClass; public MainForm() { InitializeComponent(); otherClass = new OtherClass(this.TextToBox); } public void TextToBox(string pString) { listBox1.Items.Add(pString); } } Whenever I receive data in myClass, its throwing an error. Any help you could give would be appreciated.

    Read the article

  • When using delegates, need better way to do sequential processing

    - by Padawan
    I have a class WebServiceCaller that uses NSURLConnection to make asynchronous calls to a web service. The class provides a delegate property and when the web service call is done, it calls a method webServiceDoneWithXXX on the delegate. There are several web service methods that can be called, two of which are say GetSummary and GetList. The classes that use WebServiceCaller initially need both the summary and list so they are written like this: -(void)getAllData { [webServiceCaller getSummary]; } -(void)webServiceDoneWithGetSummary { [webServiceCaller getList]; } -(void)webServiceDoneWithGetList { ... } This works but there are at least two problems: The calls are split across delegate methods so it's hard to see the sequence at a glance but more important it's hard to control or modify the sequence. Sometimes I want to call just GetSummary and not also GetList so I would then have to use an ugly class-level state variable that tells webServiceDoneWithGetSummary whether to call GetList or not. Assume that GetList cannot be done until GetSummary completes and returns some data which is used as input to GetList. Is there a better way to handle this and still get asynchronous calls? Update based on Matt Long's answer: Using notifications instead of a delegate, it looks like I can solve problem #2 by setting a different selector depending on whether I want the full sequence (GetSummary+GetList) or just GetSummary. Both observers would still use the same notification name when calling GetSummary. I would have to write two separate methods to handle GetSummaryDone instead of using a single delegate method (where I would have needed some class-level variable to tell whether to then call GetList). -(void)getAllData { [[NSNotificationCenter defaultCenter] addObserver:self              selector:@selector(getSummaryDoneAndCallGetList:)                  name:kGetSummaryDidFinish object:nil];     [webServiceCaller getSummary]; } -(void)getSummaryDoneAndCallGetList { [NSNotificationCenter removeObserver] //process summary data [[NSNotificationCenter defaultCenter] addObserver:self              selector:@selector(getListDone:)                  name:kGetListDidFinish object:nil];     [webServiceCaller getList]; } -(void)getListDone { [NSNotificationCenter removeObserver] //process list data } -(void)getJustSummaryData { [[NSNotificationCenter defaultCenter] addObserver:self              selector:@selector(getJustSummaryDone:) //different selector but                  name:kGetSummaryDidFinish object:nil]; //same notification name     [webServiceCaller getSummary]; } -(void)getJustSummaryDone { [NSNotificationCenter removeObserver] //process summary data } I haven't actually tried this yet. It seems better than having state variables and if-then statements but you have to write more methods. I still don't see a solution for problem 1.

    Read the article

  • Implement delegates for Core Data's fetched results controller or not

    - by Spanky
    What advantage is there to implementing the four delegate methods: (void)controllerWillChangeContent:(NSFetchedResultsController *)controller (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath (void)controllerDidChangeContent:(NSFetchedResultsController *)controller rather than implement: (void)controllerDidChangeContent:(NSFetchedResultsController *)controller Any help appreciated // :)

    Read the article

  • Delegates And Cross Thread Exception

    - by Neo
    Whenever i am updating UI in windows form using delegate it gives me cross thread exception why it is happening like this? is there new thread started for each delegate call ? void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { //this call delegate to display data clsConnect(statusMsg); } protected void displayResponse(string resp) { //here cross thread exception occur if directly set to lblMsgResp.Text="Test"; if (lblMsgResp.InvokeRequired) { lblMsgResp.Invoke(new MethodInvoker(delegate { lblMsgResp.Text = resp; })); } }

    Read the article

  • Question about Multicaste Delegates?

    - by IbrarMumtaz
    I am going through some exam questions for the 70-536 exam and an actual question one developer postedon his blog has popped up in my exam questions. I cannot remember what his answer was .... but below is the question: You need to write a multicast delegate that accepts a DateTime arguement and returns a bool value. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) The answer is A. Can someone please explain why? As I already did some research into this question a while ago and so I was sure that it was C, obviously now looking back at the question its clear that I did not read properly. As i was sure I had seen the same one before so I jumped to the most obvious one. A varitation on this question: You need to write a multicast delegate that accepts a DateTime arguement. Which code segment should you use? A: public delegate int PowerDeviceOn(bool, DateTime) B: public delegate bool PowerDeviceOn(Object, EventArgs) C: public delegate void PowerDeviceOn(DateTime) D: public delegate bool PowerDeviceOn(DateTime) Now this is another variation on this quesiton, it still has the same bogus sample answers, as they still kind work in throwing the exam taker off. Notice how by simply keeping the sample asnwers the same and by removing a small portion of the question text, the answer is C and not A. The variation has no official answer as I just conjured it up using the exam question as a baseplate. The answer is definately C. This time round its easy to see why C is correctr but the very first question I have an inkiling but as you know an inkling is not good enough in passing exams. Thanks For Reading.

    Read the article

  • C# delegates problem

    - by Mick Taylor
    Hello I am getting the following error from my C# Windows Application: Error 1 No overload for 'CreateLabelInPanel' matches delegate 'WorksOrderStore.ProcessDbConnDetailsDelegate' H:\c\WorksOrderFactory\WorksOrderFactory\WorksOrderClient.cs 43 39 WorksOrderFactory I have 3 .cs files that essentially: Opens a windows Has an option for the users to connect to a db When that is selected, the system will go off and connect to the db, and load some data in (just test data for now) Then using a delegate, the system should do soemthing, which for testing will be to create a label. However I haven't coded this part yet. But I can't build until I get this error sorted. The 3 fiels are called: WorksOrderClient.cs (which is the MAIN) WorksOrderStore.cs LoginBox.cs Here's the code for each file: WorksOrderClient.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using WorksOrderStore; namespace WorksOrderFactory { using WorksOrderStore; public partial class WorksOrderClient : Form { LoginBox lb = new LoginBox(); private static WorksOrderDB wodb = new WorksOrderDB(); private static int num_conns = 0; public WorksOrderClient() { InitializeComponent(); } private void connectToADBToolStripMenuItem_Click(object sender, EventArgs e) { lb.ShowDialog(); lb.Visible = true; } public static bool createDBConnDetObj(string username, string password, string database) { // increase the number of connections num_conns = num_conns + 1; // create the connection object wodb.AddDbConnDetails(username, password, database, num_conns); // create a new delegate object associated with the static // method WorksOrderClient.createLabelInPanel wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(CreateLabelInPanel)); return true; } static void CreateLabelInPanel(DbConnDetails dbcd) { Console.Write("hellO"); string tmp = (string)dbcd.username; //Console.Write(tmp); } private void WorksOrderClient_Load(object sender, EventArgs e) { } } } WorksOrderStore.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using WorksOrderFactory; namespace WorksOrderStore { using System.Collections; // Describes a book in the book list: public struct WorksOrder { public string contractor_code { get; set; } // contractor ID public string email_address { get; set; } // contractors email address public string date_issued { get; set; } // date the works order was issued public string wo_ref { get; set; } // works order ref public string status { get; set; } // status ... not used public job_status js { get; set; } // status of this worksorder within this system public WorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref) : this() { this.contractor_code = contractor_code; this.email_address = email_address; this.date_issued = date_issued; this.wo_ref = wo_ref; this.js = job_status.Pending; } } // Declare a delegate type for processing a WorksOrder: //public delegate void ProcessWorksOrderDelegate(WorksOrder worksorder); // Maintains a worksorder database. public class WorksOrderDB { // List of all worksorders in the database: ArrayList list = new ArrayList(); // Add a worksorder to the database: public void AddWorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref) { list.Add(new WorksOrder(contractor_code, email_address, date_issued, wo_ref)); } // Call a passed-in delegate on each pending works order to process it: /*public void ProcessPendingWorksOrders(ProcessWorksOrderDelegate processWorksOrder) { foreach (WorksOrder wo in list) { if (wo.js.Equals(job_status.Pending)) // Calling the delegate: processWorksOrder(wo); } }*/ // Add a DbConnDetails to the database: public void AddDbConnDetails(string username, string password, string database, int conn_num) { list.Add(new DbConnDetails(username, password, database, conn_num)); } // Call a passed-in delegate on each dbconndet to process it: public void ProcessDbConnDetails(ProcessDbConnDetailsDelegate processDBConnDetails) { foreach (DbConnDetails wo in list) { processDBConnDetails(wo); } } } // statuses for worksorders in this system public enum job_status { Pending, InProgress, Completed } public struct DbConnDetails { public string username { get; set; } // username public string password { get; set; } // password public string database { get; set; } // database public int conn_num { get; set; } // this objects connection number. public ArrayList woList { get; set; } // list of works orders for this connection // this constructor just sets the db connection details // the woList array will get created later .. not a lot later but a bit. public DbConnDetails(string username, string password, string database, int conn_num) : this() { this.username = username; this.password = password; this.database = database; this.conn_num = conn_num; woList = new ArrayList(); } } // Declare a delegate type for processing a DbConnDetails: public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails); } and LoginBox.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace WorksOrderFactory { public partial class LoginBox : Form { public LoginBox() { InitializeComponent(); } private void LoginBox_Load(object sender, EventArgs e) { this.Visible = true; this.Show(); //usernameText.Text = "Username"; //new Font(usernameText.Font, FontStyle.Italic); } private void cancelBtn_Click(object sender, EventArgs e) { this.Close(); } private void loginBtn_Click(object sender, EventArgs e) { // set up a connection details object. bool success = WorksOrderClient.createDBConnDetObj(usernameText.Text, passwordText.Text, databaseText.Text); } private void LoginBox_Load_1(object sender, EventArgs e) { } } } Any ideas?? Cheers, m

    Read the article

  • Creating Delegates With Lambda Expressions in F#

    - by Matt H
    Why does... type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list) (d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate [1..10] (fun x -> printfn "%d" x) not compile, when: type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list, d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate ([1..10], (fun x -> printfn "%d" x)) does? The only difference that is that in the second one, ApplyDelegate takes its parameters as a tuple. Error 1 This function takes too many arguments, or is used in a context where a function is not expected

    Read the article

  • Implement delegates for Core Data or not

    - by Spanky
    What advantage is there to implementing the four delegate methods: (void)controllerWillChangeContent:(NSFetchedResultsController *)controller (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath (void)controllerDidChangeContent:(NSFetchedResultsController *)controller rather than implement: (void)controllerDidChangeContent:(NSFetchedResultsController *)controller Any help appreciated // :)

    Read the article

  • Searching a Better Solution with Delegates

    - by spagetticode
    Hey All, I am a newbie in C# and curious about the better solution of my case. I have a method which gets the DataTable as a parameter and creates a List with MyClass's variables and returns it. public static List<Campaigns> GetCampaignsList(DataTable DataTable) { List<Campaigns> ListCampaigns = new List<Campaigns>(); foreach (DataRow row in DataTable.Rows) { Campaigns Campaign = new Campaigns(); Campaign.CampaignID = Convert.ToInt32(row["CampaignID"]); Campaign.CustomerID = Convert.ToInt32(row["CustomerID"]); Campaign.ClientID = Convert.ToInt32(row["ClientID"]); Campaign.Title = row["Title"].ToString(); Campaign.Subject = row["Subject"].ToString(); Campaign.FromName = row["FromName"].ToString(); Campaign.FromEmail = row["FromEmail"].ToString(); Campaign.ReplyEmail = row["ReplyEmail"].ToString(); Campaign.AddDate = Convert.ToDateTime(row["AddDate"]); Campaign.UniqueRecipients = Convert.ToInt32(row["UniqueRecipients"]); Campaign.ClientReportVisible = Convert.ToBoolean(row["ClientReportVisible"]); Campaign.Status = Convert.ToInt16(row["Status"]); ListCampaigns.Add(Campaign); } return ListCampaigns; } And one of my another DataTable method gets the DataTable from the database with given parameters. Here is the method. public static DataTable GetNewCampaigns() { DataTable dtCampaigns = new DataTable(); Campaigns Campaigns = new Campaigns(); dtCampaigns = Campaigns.SelectStatus(0); return dtCampaigns; } But the problem is that, this GetNewCampaigns method doesnt take parameters but other methods can take parameters. For example when I try to select a campaign with a CampaignID, I have to send CampaignID as parameter. These all Database methods do take return type as DataTable but different number of parameters. public static DataTable GetCampaignDetails(int CampaignID) { DataTable dtCampaigns = new DataTable(); Campaigns Campaigns = new Campaigns(); dtCampaigns = Campaigns.Select(CampaignID); return dtCampaigns; } At the end, I want to pass a Delegate to my first GetCampaignList Method as parameter which will decide which Database method to invoke. I dont want to pass DataTable as parameter as it is newbie programming. Could you pls help me learn some more advance features. I searched over it and got to Func< delegate but could not come up with a solution.

    Read the article

  • Delegates with explicit "this" pointer?

    - by Qwertie
    Is it possible to adapt a method like this function "F" class C { public void F(int i); } to a delegate like Action<C,int>? I have this vague recollection that Microsoft was working on supporting this kind of adaptation. But maybe I misremembered!

    Read the article

  • Different methods using Functors/Delegates in c#

    - by mo alaz
    I have a method that I call multiple times, but each time a different method with a different signature is called from inside. public void MethodOne() { //some stuff *MethodCall(); //some stuff } So MethodOne is called multiple times, each time with a different *MethodCall(). What I'm trying to do is something like this : public void MethodOne(Func<> MethodCall) { //some stuff *MethodCall; //some stuff } but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this? Thank you!

    Read the article

  • C#: Handling Notifications: inheritance, events, or delegates?

    - by James Michael Hare
    Often times as developers we have to design a class where we get notification when certain things happen. In older object-oriented code this would often be implemented by overriding methods -- with events, delegates, and interfaces, however, we have far more elegant options. So, when should you use each of these methods and what are their strengths and weaknesses? Now, for the purposes of this article when I say notification, I'm just talking about ways for a class to let a user know that something has occurred. This can be through any programmatic means such as inheritance, events, delegates, etc. So let's build some context. I'm sitting here thinking about a provider neutral messaging layer for the place I work, and I got to the point where I needed to design the message subscriber which will receive messages from the message bus. Basically, what we want is to be able to create a message listener and have it be called whenever a new message arrives. Now, back before the flood we would have done this via inheritance and an abstract class: 1:  2: // using inheritance - omitting argument null checks and halt logic 3: public abstract class MessageListener 4: { 5: private ISubscriber _subscriber; 6: private bool _isHalted = false; 7: private Thread _messageThread; 8:  9: // assign the subscriber and start the messaging loop 10: public MessageListener(ISubscriber subscriber) 11: { 12: _subscriber = subscriber; 13: _messageThread = new Thread(MessageLoop); 14: _messageThread.Start(); 15: } 16:  17: // user will override this to process their messages 18: protected abstract void OnMessageReceived(Message msg); 19:  20: // handle the looping in the thread 21: private void MessageLoop() 22: { 23: while(!_isHalted) 24: { 25: // as long as processing, wait 1 second for message 26: Message msg = _subscriber.Receive(TimeSpan.FromSeconds(1)); 27: if(msg != null) 28: { 29: OnMessageReceived(msg); 30: } 31: } 32: } 33: ... 34: } It seems so odd to write this kind of code now. Does it feel odd to you? Maybe it's just because I've gotten so used to delegation that I really don't like the feel of this. To me it is akin to saying that if I want to drive my car I need to derive a new instance of it just to put myself in the driver's seat. And yet, unquestionably, five years ago I would have probably written the code as you see above. To me, inheritance is a flawed approach for notifications due to several reasons: Inheritance is one of the HIGHEST forms of coupling. You can't seal the listener class because it depends on sub-classing to work. Because C# does not allow multiple-inheritance, I've spent my one inheritance implementing this class. Every time you need to listen to a bus, you have to derive a class which leads to lots of trivial sub-classes. The act of consuming a message should be a separate responsibility than the act of listening for a message (SRP). Inheritance is such a strong statement (this IS-A that) that it should only be used in building type hierarchies and not for overriding use-specific behaviors and notifications. Chances are, if a class needs to be inherited to be used, it most likely is not designed as well as it could be in today's modern programming languages. So lets look at the other tools available to us for getting notified instead. Here's a few other choices to consider. Have the listener expose a MessageReceived event. Have the listener accept a new IMessageHandler interface instance. Have the listener accept an Action<Message> delegate. Really, all of these are different forms of delegation. Now, .NET events are a bit heavier than the other types of delegates in terms of run-time execution, but they are a great way to allow others using your class to subscribe to your events: 1: // using event - ommiting argument null checks and halt logic 2: public sealed class MessageListener 3: { 4: private ISubscriber _subscriber; 5: private bool _isHalted = false; 6: private Thread _messageThread; 7:  8: // assign the subscriber and start the messaging loop 9: public MessageListener(ISubscriber subscriber) 10: { 11: _subscriber = subscriber; 12: _messageThread = new Thread(MessageLoop); 13: _messageThread.Start(); 14: } 15:  16: // user will override this to process their messages 17: public event Action<Message> MessageReceived; 18:  19: // handle the looping in the thread 20: private void MessageLoop() 21: { 22: while(!_isHalted) 23: { 24: // as long as processing, wait 1 second for message 25: Message msg = _subscriber.Receive(TimeSpan.FromSeconds(1)); 26: if(msg != null && MessageReceived != null) 27: { 28: MessageReceived(msg); 29: } 30: } 31: } 32: } Note, now we can seal the class to avoid changes and the user just needs to provide a message handling method: 1: theListener.MessageReceived += CustomReceiveMethod; However, personally I don't think events hold up as well in this case because events are largely optional. To me, what is the point of a listener if you create one with no event listeners? So in my mind, use events when handling the notification is optional. So how about the delegation via interface? I personally like this method quite a bit. Basically what it does is similar to inheritance method mentioned first, but better because it makes it easy to split the part of the class that doesn't change (the base listener behavior) from the part that does change (the user-specified action after receiving a message). So assuming we had an interface like: 1: public interface IMessageHandler 2: { 3: void OnMessageReceived(Message receivedMessage); 4: } Our listener would look like this: 1: // using delegation via interface - omitting argument null checks and halt logic 2: public sealed class MessageListener 3: { 4: private ISubscriber _subscriber; 5: private IMessageHandler _handler; 6: private bool _isHalted = false; 7: private Thread _messageThread; 8:  9: // assign the subscriber and start the messaging loop 10: public MessageListener(ISubscriber subscriber, IMessageHandler handler) 11: { 12: _subscriber = subscriber; 13: _handler = handler; 14: _messageThread = new Thread(MessageLoop); 15: _messageThread.Start(); 16: } 17:  18: // handle the looping in the thread 19: private void MessageLoop() 20: { 21: while(!_isHalted) 22: { 23: // as long as processing, wait 1 second for message 24: Message msg = _subscriber.Receive(TimeSpan.FromSeconds(1)); 25: if(msg != null) 26: { 27: _handler.OnMessageReceived(msg); 28: } 29: } 30: } 31: } And they would call it by creating a class that implements IMessageHandler and pass that instance into the constructor of the listener. I like that this alleviates the issues of inheritance and essentially forces you to provide a handler (as opposed to events) on construction. Well, this is good, but personally I think we could go one step further. While I like this better than events or inheritance, it still forces you to implement a specific method name. What if that name collides? Furthermore if you have lots of these you end up either with large classes inheriting multiple interfaces to implement one method, or lots of small classes. Also, if you had one class that wanted to manage messages from two different subscribers differently, it wouldn't be able to because the interface can't be overloaded. This brings me to using delegates directly. In general, every time I think about creating an interface for something, and if that interface contains only one method, I start thinking a delegate is a better approach. Now, that said delegates don't accomplish everything an interface can. Obviously having the interface allows you to refer to the classes that implement the interface which can be very handy. In this case, though, really all you want is a method to handle the messages. So let's look at a method delegate: 1: // using delegation via delegate - omitting argument null checks and halt logic 2: public sealed class MessageListener 3: { 4: private ISubscriber _subscriber; 5: private Action<Message> _handler; 6: private bool _isHalted = false; 7: private Thread _messageThread; 8:  9: // assign the subscriber and start the messaging loop 10: public MessageListener(ISubscriber subscriber, Action<Message> handler) 11: { 12: _subscriber = subscriber; 13: _handler = handler; 14: _messageThread = new Thread(MessageLoop); 15: _messageThread.Start(); 16: } 17:  18: // handle the looping in the thread 19: private void MessageLoop() 20: { 21: while(!_isHalted) 22: { 23: // as long as processing, wait 1 second for message 24: Message msg = _subscriber.Receive(TimeSpan.FromSeconds(1)); 25: if(msg != null) 26: { 27: _handler(msg); 28: } 29: } 30: } 31: } Here the MessageListener now takes an Action<Message>.  For those of you unfamiliar with the pre-defined delegate types in .NET, that is a method with the signature: void SomeMethodName(Message). The great thing about delegates is it gives you a lot of power. You could create an anonymous delegate, a lambda, or specify any other method as long as it satisfies the Action<Message> signature. This way, you don't need to define an arbitrary helper class or name the method a specific thing. Incidentally, we could combine both the interface and delegate approach to allow maximum flexibility. Doing this, the user could either pass in a delegate, or specify a delegate interface: 1: // using delegation - give users choice of interface or delegate 2: public sealed class MessageListener 3: { 4: private ISubscriber _subscriber; 5: private Action<Message> _handler; 6: private bool _isHalted = false; 7: private Thread _messageThread; 8:  9: // assign the subscriber and start the messaging loop 10: public MessageListener(ISubscriber subscriber, Action<Message> handler) 11: { 12: _subscriber = subscriber; 13: _handler = handler; 14: _messageThread = new Thread(MessageLoop); 15: _messageThread.Start(); 16: } 17:  18: // passes the interface method as a delegate using method group 19: public MessageListener(ISubscriber subscriber, IMessageHandler handler) 20: : this(subscriber, handler.OnMessageReceived) 21: { 22: } 23:  24: // handle the looping in the thread 25: private void MessageLoop() 26: { 27: while(!_isHalted) 28: { 29: // as long as processing, wait 1 second for message 30: Message msg = _subscriber.Receive(TimeSpan.FromSeconds(1)); 31: if(msg != null) 32: { 33: _handler(msg); 34: } 35: } 36: } 37: } } This is the method I tend to prefer because it allows the user of the class to choose which method works best for them. You may be curious about the actual performance of these different methods. 1: Enter iterations: 2: 1000000 3:  4: Inheritance took 4 ms. 5: Events took 7 ms. 6: Interface delegation took 4 ms. 7: Lambda delegate took 5 ms. Before you get too caught up in the numbers, however, keep in mind that this is performance over over 1,000,000 iterations. Since they are all < 10 ms which boils down to fractions of a micro-second per iteration so really any of them are a fine choice performance wise. As such, I think the choice of what to do really boils down to what you're trying to do. Here's my guidelines: Inheritance should be used only when defining a collection of related types with implementation specific behaviors, it should not be used as a hook for users to add their own functionality. Events should be used when subscription is optional or multi-cast is desired. Interface delegation should be used when you wish to refer to implementing classes by the interface type or if the type requires several methods to be implemented. Delegate method delegation should be used when you only need to provide one method and do not need to refer to implementers by the interface name.

    Read the article

  • C#, Delegates and LINQ

    - by JustinGreenwood
    One of the topics many junior programmers struggle with is delegates. And today, anonymous delegates and lambda expressions are profuse in .net APIs.  To help some VB programmers adapt to C# and the many equivalent flavors of delegates, I walked through some simple samples to show them the different flavors of delegates. using System; using System.Collections.Generic; using System.Linq; namespace DelegateExample { class Program { public delegate string ProcessStringDelegate(string data); public static string ReverseStringStaticMethod(string data) { return new String(data.Reverse().ToArray()); } static void Main(string[] args) { var stringDelegates = new List<ProcessStringDelegate> { //========================================================== // Declare a new delegate instance and pass the name of the method in new ProcessStringDelegate(ReverseStringStaticMethod), //========================================================== // A shortcut is to just and pass the name of the method in ReverseStringStaticMethod, //========================================================== // You can create an anonymous delegate also delegate (string inputString) //Scramble { var outString = inputString; if (!string.IsNullOrWhiteSpace(inputString)) { var rand = new Random(); var chs = inputString.ToCharArray(); for (int i = 0; i < inputString.Length * 3; i++) { int x = rand.Next(chs.Length), y = rand.Next(chs.Length); char c = chs[x]; chs[x] = chs[y]; chs[y] = c; } outString = new string(chs); } return outString; }, //========================================================== // yet another syntax would be the lambda expression syntax inputString => { // ROT13 var array = inputString.ToCharArray(); for (int i = 0; i < array.Length; i++) { int n = (int)array[i]; n += (n >= 'a' && n <= 'z') ? ((n > 'm') ? 13 : -13) : ((n >= 'A' && n <= 'Z') ? ((n > 'M') ? 13 : -13) : 0); array[i] = (char)n; } return new string(array); } //========================================================== }; // Display the results of the delegate calls var stringToTransform = "Welcome to the jungle!"; System.Console.ForegroundColor = ConsoleColor.Cyan; System.Console.Write("String to Process: "); System.Console.ForegroundColor = ConsoleColor.Yellow; System.Console.WriteLine(stringToTransform); stringDelegates.ForEach(delegatePointer => { System.Console.WriteLine(); System.Console.ForegroundColor = ConsoleColor.Cyan; System.Console.Write("Delegate Method Name: "); System.Console.ForegroundColor = ConsoleColor.Magenta; System.Console.WriteLine(delegatePointer.Method.Name); System.Console.ForegroundColor = ConsoleColor.Cyan; System.Console.Write("Delegate Result: "); System.Console.ForegroundColor = ConsoleColor.White; System.Console.WriteLine(delegatePointer(stringToTransform)); }); System.Console.ReadKey(); } } } The output of the program is below: String to Process: Welcome to the jungle! Delegate Method Name: ReverseStringStaticMethod Delegate Result: !elgnuj eht ot emocleW Delegate Method Name: ReverseStringStaticMethod Delegate Result: !elgnuj eht ot emocleW Delegate Method Name: b__1 Delegate Result: cg ljotWotem!le une eh Delegate Method Name: b__2 Delegate Result: dX_V|`X ?| ?[X ]?{Z_X!

    Read the article

  • Dynamically load and call delegates based on source data

    - by makerofthings7
    Assume I have a stream of records that need to have some computation. Records will have a combination of these functions run Sum, Aggregate, Sum over the last 90 seconds, or ignore. A data record looks like this: Date;Data;ID Question Assuming that ID is an int of some kind, and that int corresponds to a matrix of some delegates to run, how should I use C# to dynamically build that launch map? I'm sure this idea exists... it is used in Windows Forms which has many delegates/events, most of which will never actually be invoked in a real application. The sample below includes a few delegates I want to run (sum, count, and print) but I don't know how to make the quantity of delegates fire based on the source data. (say print the evens, and sum the odds in this sample) using System; using System.Threading; using System.Collections.Generic; internal static class TestThreadpool { delegate int TestDelegate(int parameter); private static void Main() { try { // this approach works is void is returned. //ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello"); int c = 0; int w = 0; ThreadPool.GetMaxThreads(out w, out c); bool rrr =ThreadPool.SetMinThreads(w, c); Console.WriteLine(rrr); // perhaps the above needs time to set up6 Thread.Sleep(1000); DateTime ttt = DateTime.UtcNow; TestDelegate d = new TestDelegate(PrintOut); List<IAsyncResult> arDict = new List<IAsyncResult>(); int count = 1000000; for (int i = 0; i < count; i++) { IAsyncResult ar = d.BeginInvoke(i, new AsyncCallback(Callback), d); arDict.Add(ar); } for (int i = 0; i < count; i++) { int result = d.EndInvoke(arDict[i]); } // Give the callback time to execute - otherwise the app // may terminate before it is called //Thread.Sleep(1000); var res = DateTime.UtcNow - ttt; Console.WriteLine("Main program done----- Total time --> " + res.TotalMilliseconds); } catch (Exception e) { Console.WriteLine(e); } Console.ReadKey(true); } static int PrintOut(int parameter) { // Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Delegate PRINTOUT waited and printed this:"+parameter); var tmp = parameter * parameter; return tmp; } static int Sum(int parameter) { Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread return parameter; } static int Count(int parameter) { Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread return parameter; } static void Callback(IAsyncResult ar) { TestDelegate d = (TestDelegate)ar.AsyncState; //Console.WriteLine("Callback is delayed and returned") ;//d.EndInvoke(ar)); } }

    Read the article

  • Predicate delegate in C#

    - by Jalpesh P. Vadgama
    I am writing few post on different type of delegates and and this post also will be part of it. In this post I am going to write about Predicate delegate which is available from C# 2.0. Following is list of post that I have written about delegates. Delegates in C#. Multicast delegates in C#. Func delegate in C#. Action delegate in C#. Predicate delegate in C#: As per MSDN predicate delegate is a pointer to a function that returns true or false and takes generics types as argument. It contains following signature. Predicate<T> – where T is any generic type and this delegate will always return Boolean value. The most common use of a predicate delegate is to searching items in array or list. So let’s take a simple example. Following is code for that. Read More

    Read the article

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