Search Results

Search found 4334 results on 174 pages for 'sender'.

Page 12/174 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • How can I bind events to strongly typed datasets of different types?

    My application contains several forms which consist of a strongly typed datagridview, a strongly typed bindingsource, and a strongly typed table adapter. I am using some code in each form to update the database whenever the user leaves the current row, shifts focus away from the datagrid or the form, or closes the form. This code is the same in each case, so I want to make a subclass of form, from which all of these forms can inherit. But the strongly typed data objects all inherit from component, which doesn't expose the events I want to bind to or the methods I want to invoke. The only way I can see of gaining access to the events is to use: Type(string Name).GetEvent(string EventName).AddEventHandler(object Target,Delegate Handler) Similarly, I want to call the Update method of the strongly typed table adapter, and am using Type(string Name).GetMethod(String name, Type[] params).Invoke(object target, object[] params). It works ok, but it seems very heavy handed. Is there a better way? Here is my code for the main class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; using System.ComponentModel; namespace MyApplication { public class AutoSaveDataGridForm: Form { private DataRow PreviousRow; public Component Adapter { private get; set; } private Component dataGridView; public Component DataGridView { private get { return dataGridView; } set { dataGridView = value; Type t = dataGridView.GetType(); t.GetEvent("Leave").AddEventHandler(dataGridView, new EventHandler(DataGridView_Leave)); } } private Component bindingSource; public Component BindingSource { private get { return bindingSource; } set { bindingSource = value; Type t = bindingSource.GetType(); t.GetEvent("PositionChanged").AddEventHandler(bindingSource, new EventHandler(BindingSource_PositionChanged)); } } protected void Save() { if (PreviousRow != null && PreviousRow.RowState != DataRowState.Unchanged) { Type t = Adapter.GetType(); t.GetMethod("Update", new Type[] { typeof(DataRow[]) }).Invoke(Adapter, new object[] { new DataRow[] { PreviousRow } }); } } private void BindingSource_PositionChanged(object sender, EventArgs e) { BindingSource bindingSource = sender as BindingSource; DataRowView CurrentRowView = bindingSource.Current as DataRowView; DataRow CurrentRow = CurrentRowView.Row; if (PreviousRow != null && PreviousRow != CurrentRow) { Save(); } PreviousRow = CurrentRow; } private void InitializeComponent() { this.SuspendLayout(); // // AutoSaveDataGridForm // this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.AutoSaveDataGridForm_FormClosed); this.Leave += new System.EventHandler(this.AutoSaveDataGridForm_Leave); this.ResumeLayout(false); } private void DataGridView_Leave(object sender, EventArgs e) { Save(); } private void AutoSaveDataGridForm_FormClosed(object sender, FormClosedEventArgs e) { Save(); } private void AutoSaveDataGridForm_Leave(object sender, EventArgs e) { Save(); } } } And here is a (partial) form which implements it: public partial class FileTypesInherited :AutoSaveDataGridForm { public FileTypesInherited() { InitializeComponent(); } private void FileTypesInherited_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'sharedFoldersInformationV2DataSet.tblFileTypes' table. You can move, or remove it, as needed. this.tblFileTypesTableAdapter.Fill(this.sharedFoldersInformationV2DataSet.tblFileTypes); this.BindingSource = tblFileTypesBindingSource; this.Adapter = tblFileTypesTableAdapter; this.DataGridView = tblFileTypesDataGridView; } }

    Read the article

  • About global.asax and the events there

    - by eski
    So what i'm trying to understand is the whole global.asax events. I doing a simple counter that records website visits. I am using MSSQL. Basicly i have two ints. totalNumberOfUsers - The total visist from begining. currentNumberOfUsers - Total of users viewing the site at the moment. So the way i understand global.asax events is that every time someone comes to the site "Session_Start" is fired once. So once per user. "Application_Start" is fired only once the first time someone comes to the site. Going with this i have my global.asax file here. <script runat="server"> string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString; void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application.Lock(); Application["currentNumberOfUsers"] = 0; Application.UnLock(); string sql = "Select c_hit from v_counter where (id=1)"; SqlConnection connect = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand(sql, connect); cmd.Connection.Open(); cmd.ExecuteNonQuery(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Application.Lock(); Application["totalNumberOfUsers"] = reader.GetInt32(0); Application.UnLock(); } reader.Close(); cmd.Connection.Close(); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["totalNumberOfUsers"] = (int)Application["totalNumberOfUsers"] + 1; Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] + 1; Application.UnLock(); string sql = "UPDATE v_counter SET c_hit = @hit WHERE c_type = 'totalNumberOfUsers'"; SqlConnection connect = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand(sql, connect); SqlParameter hit = new SqlParameter("@hit", SqlDbType.Int); hit.Value = Application["totalNumberOfUsers"]; cmd.Parameters.Add(hit); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Application.Lock(); Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] - 1; Application.UnLock(); } </script> In the page_load i have this protected void Page_Load(object sender, EventArgs e) { l_current.Text = Application["currentNumberOfUsers"].ToString(); l_total.Text = Application["totalNumberOfUsers"].ToString(); } So if i understand this right, every time someone comes to the site both the currentNumberOfUsers and totalNumberOfUsers are incremented with 1. But when the session is over the currentNumberOfUsers is decremented with 1. If i go to the site with 3 types of browsers with the same computer i should have 3 in hits on both counters. Doing this again after hours i should have 3 in current and 6 in total, right ? The way its working right now is the current goes up to 2 and the total is incremented on every postback on IE and Chrome but not on firefox. And one last thing, is this the same thing ? Application["value"] = 0; value = Application["value"] //OR Application.Set("Value", 0); Value = Application.Get("Value");

    Read the article

  • When Clearing an ObservableCollection, There are No Items in e.OldItems

    - by cplotts
    I have something here that is really catching me off guard. I have an ObservableCollection of T that is filled with items. I also have an event handler attached to the CollectionChanged event. When you Clear the collection it causes an CollectionChanged event with e.Action set to NotifyCollectionChangedAction.Reset. Ok, that's normal. But what is weird is that neither e.OldItems or e.NewItems has anything in it. I would expect e.OldItems to be filled with all items that were removed from the collection. Has anyone else seen this? And if so, how have they gotten around it? Some background: I am using the CollectionChanged event to attach and detach from another event and thus if I don't get any items in e.OldItems ... I won't be able to detach from that event. CLARIFICATION: I do know that the documentation doesn't outright state that it has to behave this way. But for every other action, it is notifying me of what it has done. So, my assumption is that it would tell me ... in the case of Clear/Reset as well. Below is the sample code if you wish to reproduce it yourself. First off the xaml: <Window x:Class="ObservableCollection.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" > <StackPanel> <Button x:Name="addButton" Content="Add" Width="100" Height="25" Margin="10" Click="addButton_Click"/> <Button x:Name="moveButton" Content="Move" Width="100" Height="25" Margin="10" Click="moveButton_Click"/> <Button x:Name="removeButton" Content="Remove" Width="100" Height="25" Margin="10" Click="removeButton_Click"/> <Button x:Name="replaceButton" Content="Replace" Width="100" Height="25" Margin="10" Click="replaceButton_Click"/> <Button x:Name="resetButton" Content="Reset" Width="100" Height="25" Margin="10" Click="resetButton_Click"/> </StackPanel> </Window> Next, the code behind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace ObservableCollection { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); _integerObservableCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_integerObservableCollection_CollectionChanged); } private void _integerObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Move: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Replace: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: break; default: break; } } private void addButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Add(25); } private void moveButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Move(0, 19); } private void removeButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.RemoveAt(0); } private void replaceButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection[0] = 50; } private void resetButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Clear(); } private ObservableCollection<int> _integerObservableCollection = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; } }

    Read the article

  • I'm trying to pass a string from my first ViewController to my second ViewController but it returns NULL

    - by Dashony
    In my first view controller I have 3 input fields each of them take the user input into and saves it into a string such as: address, username and password as NSUserDefaults. This part works fine. In my second view controller I'm trying to take the 3 strings from first controller (address, username and password) create a html link based on the 3 strings. I've tried many ways to access the 3 strings with no luck, the result I get is NULL. Here is my code: //.h file - first view controller with the 3 input fields CamSetup.h #import <UIKit/UIKit.h> @interface CamSetup : UIViewController <UITextFieldDelegate> { NSString * address; NSString * username; NSString * password; IBOutlet UITextField * addressField; IBOutlet UITextField * usernameField; IBOutlet UITextField * passwordField; } -(IBAction) saveAddress: (id) sender; -(IBAction) saveUsername: (id) sender; -(IBAction) savePassword: (id) sender; @property(nonatomic, retain) UITextField *addressField; @property(nonatomic, retain) UITextField *usernameField; @property(nonatomic, retain) UITextField *passwordField; @property(nonatomic, retain) NSString *address; @property(nonatomic, retain) NSString *username; @property(nonatomic, retain) NSString *password; @end //.m file - first view controller CamSetup.m #import "CamSetup.h" @interface CamSetup () @end @implementation CamSetup @synthesize addressField, usernameField, passwordField, address, username, password; -(IBAction) saveAddress: (id) sender { address = [[NSString alloc] initWithFormat:addressField.text]; [addressField setText:address]; NSUserDefaults *stringDefaultAddress = [NSUserDefaults standardUserDefaults]; [stringDefaultAddress setObject:address forKey:@"stringKey1"]; NSLog(@"String [%@]", address); } -(IBAction) saveUsername: (id) sender { username = [[NSString alloc] initWithFormat:usernameField.text]; [usernameField setText:username]; NSUserDefaults *stringDefaultUsername = [NSUserDefaults standardUserDefaults]; [stringDefaultUsername setObject:username forKey:@"stringKey2"]; NSLog(@"String [%@]", username); } -(IBAction) savePassword: (id) sender { password = [[NSString alloc] initWithFormat:passwordField.text]; [passwordField setText:password]; NSUserDefaults *stringDefaultPassword = [NSUserDefaults standardUserDefaults]; [stringDefaultPassword setObject:password forKey:@"stringKey3"]; NSLog(@"String [%@]", password); } - (void)viewDidLoad { [addressField setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"stringKey1"]]; [usernameField setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"stringKey2"]]; [passwordField setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"stringKey3"]]; [super viewDidLoad]; } @end //.h second view controller LiveView.h #import <UIKit/UIKit.h> #import "CamSetup.h" @interface LiveView : UIViewController { NSString *theAddress; NSString *theUsername; NSString *thePassword; CamSetup *camsetup; //here is an instance of the first class } @property (nonatomic, retain) NSString *theAddress; @property (nonatomic, retain) NSString *theUsername; @property (nonatomic, retain) NSString *thePassword; @end //.m second view LiveView.m file #import "LiveView.h" @interface LiveView () @end @implementation LiveView @synthesize theAddress, theUsername, thePassword; - (void)viewDidLoad { [super viewDidLoad]; theUsername = camsetup.username; //this is probably not right? NSLog(@"String [%@]", theUsername); //resut here is NULL NSLog(@"String [%@]", camsetup.username); //and here NULL as well } @end

    Read the article

  • Winforms controls and "generic" events handlers. How can I do this?

    - by Yanko Hernández Alvarez
    In the demo of the ObjectListView control there is this code (in the "Complex Example" tab page) to allow for a custom editor (a ComboBox) (Adapted to my case and edited for clarity): EventHandler CurrentEH; private void ObjectListView_CellEditStarting(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) { ISomeInterface M = (e.RowObject as ObjectListView1Row).SomeObject; //(1) ComboBox cb = new ComboBox(); cb.Bounds = e.CellBounds; cb.DropDownStyle = ComboBoxStyle.DropDownList; cb.DataSource = ISomeOtherObjectCollection; cb.DisplayMember = "propertyName"; cb.DataBindings.Add("SelectedItem", M, "ISomeOtherObject", false, DataSourceUpdateMode.Never); e.Control = cb; cb.SelectedIndexChanged += CurrentEH = (object sender2, EventArgs e2) => M.ISomeOtherObject = (ISomeOtherObject)((ComboBox)sender2).SelectedValue; //(2) } } private void ObjectListView_CellEditFinishing(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) { // Stop listening for change events ((ComboBox)e.Control).SelectedIndexChanged -= CurrentEH; // Any updating will have been down in the SelectedIndexChanged // event handler. // Here we simply make the list redraw the involved ListViewItem ((ObjectListView)sender).RefreshItem(e.ListViewItem); // We have updated the model object, so we cancel the auto update e.Cancel = true; } } I have too many other columns with combo editors inside objectlistviews to use a copy& paste strategy (besides, copy&paste is a serious source of bugs), so I tried to parameterize the code to keep the code duplication to a minimum. ObjectListView_CellEditFinishing is a piece of cake: HashSet<OLVColumn> cbColumns = new HashSet<OLVColumn> (new OLVColumn[] { SomeCol, SomeCol2, ...}; private void ObjectListView_CellEditFinishing(object sender, CellEditEventArgs e) { if (cbColumns.Contains(e.Column)) ... but ObjectListView_CellEditStarting is the problematic. I guess in CellEditStarting I will have to discriminate each case separately: private void ObjectListView_CellEditStarting(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) // code to create the combo, put the correct list as the datasource, etc. else if (e.Column == SomeOtherCol) // code to create the combo, put the correct list as the datasource, etc. And so on. But how can I parameterize the "code to create the combo, put the correct list as the datasource, etc."? Problem lines are (1) Get SomeObject. the property NAME varies. (2) Set ISomeOtherObject, the property name varies too. The types vary too, but I can cover those cases with a generic method combined with a not so "typesafe" API (for instance, the cb.DataBindings.Add and cb.DataSource both use an object) Reflection? more lambdas? Any ideas? Any other way to do the same? PS: I want to be able to do something like this: private void ObjectListView_CellEditStarting(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) SetUpCombo<ISomeInterface>(ISomeOtherObjectCollection, "propertyName", SomeObject, ISomeOtherObject); else if (e.Column == SomeOtherCol) SetUpCombo<ISomeInterface2>(ISomeOtherObject2Collection, "propertyName2", SomeObject2 ISomeOtherObject2); and so on. Or something like that. I know, parameters SomeObject and ISomeOtherObject are not real parameters per see, but you get the idea of what I want. I want not to repeat the same code skeleton again and again and again. One solution would be "preprocessor generics" like C's DEFINE, but I don't thing c# has something like that. So, does anyone have some alternate ideas to solve this?

    Read the article

  • how to pass a string value from one controller to another

    - by shreedevi
    I have a login controller ,and after the successful login i want to pass some string value to the menu page.however it does not work.the application crashes. I have tried possible suggesstion of Ihuk and SAM from the link below http://stackoverflow.com/questions/1685964/how-to-pass-a-string-value-from-one-view-controller-to-another-view-controller loginController.h: #import <UIKit/UIKit.h> @class RootViewController; @class Menu; @interface LoginController : UIViewController { UIButton *login_Button; UITextField *username_TextField; UITextField *password_TextField; RootViewController *mc1; UINavigationController *navigationController; Menu *mv1; } @property(nonatomic,retain) IBOutlet UIButton *login_Button; @property(nonatomic,retain) IBOutlet UITextField *username_TextField; @property(nonatomic,retain) IBOutlet UITextField *password_TextField; @property(nonatomic,retain) RootViewController *mc1; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController; @property(nonatomic,retain)Menu *mv1; - (IBAction)Login_Method:(id)sender; -(id)initWithUserName:(NSString *)name ; @end loginController.m #import "LoginController.h" #import "Menu.h" #import "ViewController.h" #import "RootViewController.h" @implementation LoginController @synthesize mc1,mv1; @synthesize login_Button,username_TextField,password_TextField; @synthesize navigationController; // Implement viewDidLoad to do additional setup after // loading the view, typically from a nib. - (void)viewDidLoad { if (![self.navigationController isNavigationBarHidden]) [self.navigationController setNavigationBarHidden:YES animated:NO]; //[self presentModalViewController:navigationController animated:YES]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (IBAction)Login_Method:(id)sender { Menu *mv2 = [[Menu alloc] initWithUserName:@"Menu" bundle:nil]; //mv2.l1.text=@"aa"; //i tried this, but not work,so created initWithUserName self.mv1=mv2; [self presentModalViewController:mv1 animated:YES]; // [RootViewController release]; } -(id)initWithUserName:(NSString *)name { self = [super init]; if (nil == self) { return nil; } // display or store login info somewhere [mv1.l1 setText:name]; return self; } -(BOOL)textFieldShouldReturn:(UITextField *)theTextField { [theTextField resignFirstResponder]; return YES; } - (void)dealloc { [username_TextField release]; [password_TextField release]; [super dealloc]; } @end Menu.h #import <UIKit/UIKit.h> @class Menu; @interface Menu : UIViewController { UILabel *l1; UIButton *AccountSummary_Button; UIButton *PayOffQuote_Button; UIButton *PayBill_Button; UIButton *Logout_Button; UINavigationController *nv1; } @property(nonatomic,retain) IBOutlet UILabel *l1; @property(nonatomic,retain) IBOutlet UIButton *AccountSummary_Button; @property(nonatomic,retain) IBOutlet UIButton *PayOffQuote_Button; @property(nonatomic,retain) IBOutlet UIButton *PayBill_Button; @property(nonatomic,retain) IBOutlet UIButton *Logout_Button; @property (nonatomic, retain) IBOutlet UINavigationController *nv1; -(IBAction)ViewAccountSummary_method:(id)sender; -(IBAction)ViewPayOffQuote_method:(id)sender; -(IBAction)ViewPayBill_method:(id)sender; -(IBAction)Logout_method:(id)sender; @end Menu.m

    Read the article

  • RSync over SSH hangs and fails with timeout

    - by tx2
    Client: Gentoo, GCC 4.3.4, RSync 3.0.9 Server: Ubuntu 10.04.4 LTS, RSync 3.0.7 Client and server connectet through is Internet, about 2Mbps. Ping is ok. RSync called on any files in any direction hangs on random file, then, after timeout, fails with: [sender] io timeout after 30 seconds -- exiting rsync error: timeout in data send/receive (code 30) at io.c(140) [sender=3.0.9] [sender] _exit_cleanup(code=30, file=io.c, line=140): about to call exit(30) In 1/10 trys is pass correctly. I've tryed to add SSH options TcpRcvBufPoll=yes, KeepAlive=yes; disable and enable rsync compression -- no changes. How can i make rsync works properly?

    Read the article

  • Observable Collections

    - by SGWellens
    I didn't think it was possible, but .NET surprised me yet again with a cool feature I never knew existed: The ObservableCollection. This became available in .NET 3.0. In essence, an ObservableCollection is a collection with an event you can connect to. The event fires when the collection changes. As usual, working with the .NET classes is so ridiculously easy, it feels like cheating. The following is small test program to illustrate how the ObservableCollection works. To start, create an ObservableCollection and then store it in the Session object so it will persist between page post backs. I also added the code to pull it out of Session state when there is a page post back:   public partial class _Default : System.Web.UI.Page{    public ObservableCollection<int> MyInts;     // ---- Page_Load ------------------------------     protected void Page_Load(object sender, EventArgs e)    {        if (IsPostBack == false)        {            MyInts = new ObservableCollection<int>();            MyInts.CollectionChanged += CollectionChangedHandler;             Session["MyInts"] = MyInts;  // store for use between postbacks        }        else        {            MyInts = Session["MyInts"] as ObservableCollection<int>;        }    } Here's the event handler I hooked up to the ObservableCollection, it writes status strings to a ListBox. Note: The event handler fires in a different thread than the IIS process thread.     // ---- CollectionChangedHandler -----------------------------------    //    // Something changed in the Observable collection     public void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)    {        // need to dig around to get the current page and control to write to:        // (because this is in a separate thread)        Page CurrentPage = System.Web.HttpContext.Current.Handler as Page;        ListBox LB = CurrentPage.FindControl("ListBoxHistory") as ListBox;         switch (e.Action)        {            case NotifyCollectionChangedAction.Add:                LB.Items.Add("Add: " + e.NewItems[0]);                               break;             case NotifyCollectionChangedAction.Remove:                LB.Items.Add("Remove: " + e.OldItems[0]);                break;             case NotifyCollectionChangedAction.Reset:                LB.Items.Add("Reset: ");                break;             default:                LB.Items.Add(e.Action.ToString());                break;                     }    }  Next, add some buttons and code to exercise the ObservableCollection:     <br />    <asp:Button ID="ButtonAdd" runat="server" Text="Add" OnClick="ButtonAdd_Click" />    <asp:Button ID="ButtonRemove" runat="server" Text="Remove" OnClick="ButtonRemove_Click" />    <asp:Button ID="ButtonReset" runat="server" Text="Reset" OnClick="ButtonReset_Click" />    <asp:Button ID="ButtonList" runat="server" Text="List" OnClick="ButtonList_Click" />    <br />    <asp:TextBox ID="TextBoxInt" runat="server" Width="51px"></asp:TextBox>    <br />    <asp:ListBox ID="ListBoxHistory" runat="server" Height="255px" Width="195px">    </asp:ListBox>    // ---- Add Button --------------------------------------     protected void ButtonAdd_Click(object sender, EventArgs e)    {        int Temp;        if (int.TryParse(TextBoxInt.Text, out Temp) == true)            MyInts.Add(Temp);    }     // ---- Remove Button --------------------------------------     protected void ButtonRemove_Click(object sender, EventArgs e)    {        int Temp;        if (int.TryParse(TextBoxInt.Text, out Temp) == true)            MyInts.Remove(Temp);    }     // ---- Button Reset -----------------------------------     protected void ButtonReset_Click(object sender, EventArgs e)    {        MyInts.Clear();    }     // ---- Button List --------------------------------------     protected void ButtonList_Click(object sender, EventArgs e)    {        ListBoxHistory.Items.Add("MyInts:");        foreach (int i in MyInts)        {            // a bit of tweaking to get the text to be indented            ListItem LI = new ListItem("&nbsp;&nbsp;" + i.ToString());            LI.Text = Server.HtmlDecode(LI.Text);            ListBoxHistory.Items.Add(LI);        }    } Here's what it looks like after entering some numbers and clicking some buttons: An interesting note is that I had to use: System.Web.HttpContext.Current.Response to write to a control on the page. As mentioned earlier, this implies that the notification event is in a thread separate from the IIS thread. Another interesting note: From the online help: Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe What does that mean to Asp.Net developers? If you are going to share an ObservableCollection among different sessions, you'd better make it a static object. I hope someone finds this useful. Steve Wellens

    Read the article

  • C-panel mail goes into spam instead of inbox in gmail

    - by Robin Jain
    I have c-panel vps server. I have created a domain on the same server, but when I send mail through webmail to gmail email id it goes into the spam folder. Note--->Mail ip note blacklisted Spf records enable DKIM enable reverse dns are perfect ====================================================================== Email header Information: Delivered-To: [email protected] Received: by 10.143.93.13 with SMTP id v13csp119806wfl; Fri, 6 Jul 2012 08:01:36 -0700 (PDT) Received: by 10.182.52.42 with SMTP id q10mr26133912obo.46.1341586895571; Fri, 06 Jul 2012 08:01:35 -0700 (PDT) Return-Path: <[email protected]> Received: from lakshyacs-u.securehostdns.com ([50.97.147.134]) by mx.google.com with ESMTPS id fx3si18028369obc.144.2012.07.06.08.01.35 (version=TLSv1/SSLv3 cipher=OTHER); Fri, 06 Jul 2012 08:01:35 -0700 (PDT) Received-SPF: pass (google.com: domain of [email protected] designates 50.97.147.134 as permitted sender) client-ip=50.97.147.134; Authentication-Results: mx.google.com; spf=pass (google.com: domain of [email protected] designates 50.97.147.134 as permitted sender) [email protected] Received: from localhost.localdomain ([127.0.0.1]:39016 helo=harishjoshico.com) by lakshyacs-u.securehostdns.com with esmtpa (Exim 4.77) (envelope-from <[email protected]>) id 1SnA2J-0006Nq-05 for [email protected]; Fri, 06 Jul 2012 20:31:35 +0530 Received: from 223.189.14.213 ([223.189.14.213]) (SquirrelMail authenticated user [email protected]) by harishjoshico.com with HTTP; Fri, 6 Jul 2012 20:31:35 +0530 Message-ID: <[email protected]> Date: Fri, 6 Jul 2012 20:31:35 +0530 Subject: ggglkhl From: [email protected] To: [email protected] User-Agent: SquirrelMail/1.4.22 MIME-Version: 1.0 Content-Type: text/plain;charset=iso-8859-1 Content-Transfer-Encoding: 8bit X-Priority: 3 (Normal) Importance: Normal X-AntiAbuse: This header was added to track abuse, please include it with any abuse report X-AntiAbuse: Primary Hostname - lakshyacs-u.securehostdns.com X-AntiAbuse: Original Domain - gmail.com X-AntiAbuse: Originator/Caller UID/GID - [47 12] / [47 12] X-AntiAbuse: Sender Address Domain - harishjoshico.com jhkhl ================================================================

    Read the article

  • Autocomplete in Silverlight with Visual Studio 2010

    - by Sayre Collado
    Last week I keep searching on how to use the autocomplete in silverligth with visual studio 2010 but most of the examples that I find they are using a textbox or combobox for the autocomplete. I tried to study those examples and apply to the single autocomplete from tools on my silverlight project. And now this is the result. I will use a database again from my previous post (Silverlight Simple DataBinding in DataGrid) to show how the autocomplete works with database. This is the output: First, this is the setup for my autocomplete: //The tags for autocompletebox on XAML Second, my simple snippets: //Event for the autocomplete to send a text string to my function private void autoCompleteBox1_KeyUp(object sender, KeyEventArgs e) { autoCompleteBox1.Populating += (s, args) => { args.Cancel = true; var c = new Service1Client(); c.GetListByNameCompleted +=new EventHandler(c_GetListByNameCompleted); c.GetListByNameAsync(autoCompleteBox1.Text); }; } //Getting result from database void c_GetListByNameCompleted(object sender, GetListByNameCompletedEventArgs e) { autoCompleteBox1.ItemsSource = e.Result; autoCompleteBox1.PopulateComplete(); } The snippets above will show on how to use the autocompleteBox using the data from database that bind in DataGrid. But what if we want to show the result on DataGrid while the autocomplete changing the items source? Ok just add one line to c_GetListByNameCompleted void c_GetListByNameCompleted(object sender, GetListByNameCompletedEventArgs e) { autoCompleteBox1.ItemsSource = e.Result; autoCompleteBox1.PopulateComplete(); dataGrid1.ItemsSource = e.Result; }

    Read the article

  • NetworkManager broken after upgrade to Kubuntu Saucy

    - by queueoverflow
    I had Kubuntu 13.04 on my ThinkPad X220, and I upgraded to 13.10 and I am not able to connect to a wired or wireless connection. The new network tray icon does not show any entries at all. In the menu of the tray icon, there is an error saying: Require NetworkManager 0.9.8, found . I then tried the following: nmcli con ** (process:3695): WARNING **: Could not initialize NMClient /org/freedesktop/NetworkManager: Rejected send message, 3 matched rules; type="method_call", sender=":1.64" (uid=1000 pid=3695 comm="nmcli con ") interface="org.freedesktop.DBus.Properties" member="GetAll" error name="(unset)" requested_reply="0" destination="org.freedesktop.NetworkManager" (uid=0 pid=1116 comm="NetworkManager ") Error: nmcli (0.9.8.0) and NetworkManager (unknown) versions don't match. Force execution using --nocheck, but the results are unpredictable. nmcli dev ** (process:3700): WARNING **: Could not initialize NMClient /org/freedesktop/NetworkManager: Rejected send message, 3 matched rules; type="method_call", sender=":1.65" (uid=1000 pid=3700 comm="nmcli dev ") interface="org.freedesktop.DBus.Properties" member="GetAll" error name="(unset)" requested_reply="0" destination="org.freedesktop.NetworkManager" (uid=0 pid=1116 comm="NetworkManager ") Error: nmcli (0.9.8.0) and NetworkManager (unknown) versions don't match. Force execution using --nocheck, but the results are unpredictable. nm-tool ** (process:3705): WARNING **: Could not initialize NMClient /org/freedesktop/NetworkManager: Rejected send message, 3 matched rules; type="method_call", sender=":1.66" (uid=1000 pid=3705 comm="nm-tool ") interface="org.freedesktop.DBus.Properties" member="GetAll" error name="(unset)" requested_reply="0" destination="org.freedesktop.NetworkManager" (uid=0 pid=1116 comm="NetworkManager ") NetworkManager Tool State: unknown ** (process:3705): WARNING **: error: could not connect to NetworkManager Running those as root works, however. I was also able to run nmcli con up id DHCP which got my DHCP connection working and giving me internet access. That did not work using a Wifi connection though, and I do need those. How can I get networking back to work without a reinstall?

    Read the article

  • bluetooth headset can connect, but not visible in pulse audio

    - by Kim Marivoet
    I have a plantronics bluetooth headset, and until yesterday I could use it without any problem. However, today it suddenly stopped working (maybe related to the last software update I did). I can still connect/disconnect my headset, but it doesn't show up in pulse audio anymore. I read through various posts that describes kind of the same problem, but none of the suggested solutions worked. I get following error in the syslog: Oct 13 16:49:57 desktop bluetoothd[1040]: Endpoint registered: sender=:1.34 path=/MediaEndpoint/HFPAG Oct 13 16:49:57 desktop bluetoothd[1040]: Endpoint registered: sender=:1.34 path=/MediaEndpoint/A2DPSource Oct 13 16:49:57 desktop bluetoothd[1040]: Endpoint registered: sender=:1.34 path=/MediaEndpoint/A2DPSink Oct 13 16:50:09 desktop kernel: [ 17.340943] input: 48:C1:AC:08:FE:8F as /devices/virtual/input/input14 Oct 13 16:50:09 desktop bluetoothd[1040]: /org/bluez/1040/hci0/dev_48_C1_AC_08_FE_8F/fd0: fd(36) ready Oct 13 16:50:09 desktop rtkit-daemon[1894]: Successfully made thread 2213 of process 1892 (n/a) owned by '1000' RT at priority 5. Oct 13 16:50:09 desktop rtkit-daemon[1894]: Supervising 5 threads of 1 processes of 1 users. Oct 13 16:50:10 desktop bluetoothd[1040]: Badly formated or unrecognized command: AT+XEVENT=USER-AGENT,COM.PLANTRONICS,PLT_VOYAGERPRO,0109,27.90,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF Oct 13 16:50:10 desktop bluetoothd[1040]: Audio connection got disconnected Any help would be much appreciated. I'm using Ubuntu 12.04. Thanks, Kim

    Read the article

  • Message Driven Bean JMS integration

    - by Anthony Shorten
    In Oracle Utilities Application Framework V4.1 and above the product introduced the concept of real time JMS integration within the Framework for interfacing. Customer familiar with older versions of the Framework will recall that we used a component called the Multi-purpose Listener (MPL) which was a very light service bus for calling interface channels (including JMS). The MPL is not supplied with all products and customers prefer to use Oracle SOA Suite and native methods rather then MPL. In Oracle Utilities Application Framework V4.1 (and for Oracle Utilities Application Framework V2.2 via Patches 9454971, 9256359, 9672027 and 9838219) we introduced real time JMS integration natively for outbound JMS integration and using Message Driven Beans (MDB) for incoming integration. The outbound integration has not changed a lot between releases where you create an Outbound Message Type to indicate the record types to send out, create a JMS sender (though now you use the Real Time Sender) and then create an External System definition to complete the configuration. When an outbound message appears in the table of the type and external system configured (via a business event such as an algorithm or plug-in script) the Oracle Utilities Application Framework will place the message on the configured Queue linked to the JMS Sender. The inbound integration has changed. In the past you created XAI Receivers and specified configuration about what types of transactions to process. This is now all configuration file driven. The configuration files for the Business Application Server (ejb-jar.xml and weblogic-ejb-jar.xml) define Message Driven Beans and the queues to monitor. When a message appears on the queue, the MDB processes it through our web services interface. Configuration of the MDB can be native (via editing the configuration files) or through the new user exit capabilities (which is aimed at maintaining custom configuration across upgrades). The latter is better as you build fragments of configuration to make it easier to maintain. In the next few weeks a number of new whitepaper will be released to illustrate the features of the Oracle WebLogic JMS and Oracle SOA Suite integration capabilities.

    Read the article

  • In c-panel mail goes in spam instead of inbox in gmail

    - by Robin Jain
    I have c-panel vps server I have create a domain in the same server but when I sent a mail through webmail to gmail email id it goes into spam. Note--->Mail ip note blacklisted Spf records enable DKIM enable reverse dns are perfect ====================================================================== Email header Information: Delivered-To: [email protected] Received: by 10.143.93.13 with SMTP id v13csp119806wfl; Fri, 6 Jul 2012 08:01:36 -0700 (PDT) Received: by 10.182.52.42 with SMTP id q10mr26133912obo.46.1341586895571; Fri, 06 Jul 2012 08:01:35 -0700 (PDT) Return-Path: <[email protected]> Received: from lakshyacs-u.securehostdns.com ([50.97.147.134]) by mx.google.com with ESMTPS id fx3si18028369obc.144.2012.07.06.08.01.35 (version=TLSv1/SSLv3 cipher=OTHER); Fri, 06 Jul 2012 08:01:35 -0700 (PDT) Received-SPF: pass (google.com: domain of [email protected] designates 50.97.147.134 as permitted sender) client-ip=50.97.147.134; Authentication-Results: mx.google.com; spf=pass (google.com: domain of [email protected] designates 50.97.147.134 as permitted sender) [email protected] Received: from localhost.localdomain ([127.0.0.1]:39016 helo=harishjoshico.com) by lakshyacs-u.securehostdns.com with esmtpa (Exim 4.77) (envelope-from <[email protected]>) id 1SnA2J-0006Nq-05 for [email protected]; Fri, 06 Jul 2012 20:31:35 +0530 Received: from 223.189.14.213 ([223.189.14.213]) (SquirrelMail authenticated user [email protected]) by harishjoshico.com with HTTP; Fri, 6 Jul 2012 20:31:35 +0530 Message-ID: <[email protected]> Date: Fri, 6 Jul 2012 20:31:35 +0530 Subject: ggglkhl From: [email protected] To: [email protected] User-Agent: SquirrelMail/1.4.22 MIME-Version: 1.0 Content-Type: text/plain;charset=iso-8859-1 Content-Transfer-Encoding: 8bit X-Priority: 3 (Normal) Importance: Normal X-AntiAbuse: This header was added to track abuse, please include it with any abuse report X-AntiAbuse: Primary Hostname - lakshyacs-u.securehostdns.com X-AntiAbuse: Original Domain - gmail.com X-AntiAbuse: Originator/Caller UID/GID - [47 12] / [47 12] X-AntiAbuse: Sender Address Domain - harishjoshico.com jhkhl ================================================================

    Read the article

  • WPF Combobox: Autocomplete

    - by user279244
    Hi, I have implemented a Autocomplete enabled Combobox in WPF. It is like below... private void cbxSession_Loaded(object sender, RoutedEventArgs e) { cbxSession.ApplyTemplate(); TextBox textBox = cbxSession.Template.FindName("PART_EditableTextBox", cbxSession) as TextBox; textBox.IsReadOnly = false; if (textBox != null) { textBox.KeyUp += new KeyEventHandler(textBox_KeyUp); textBox.KeyUp += delegate { ///open the drop down and start filtering based on what the user types into the combobox cbxSession.IsDropDownOpen = true; cbxSession.Items.Filter += a => { if (a.ToString().ToUpper().Contains(textBox.Text.ToUpper())) return true; else return false; }; }; } } void textBox_KeyUp(object sender, KeyEventArgs e) { if ((e.Key == System.Windows.Input.Key.Up) || (e.Key == System.Windows.Input.Key.Down)) { e.Handled = true; } else if (e.Key == System.Windows.Input.Key.Enter) { e.Handled = true; cbxSession.IsDropDownOpen = false; } } void textBox_KeyDown(object sender, KeyEventArgs e) { cbxSession.SelectionChanged -= cbxSession_SelectionChanged; if (e.Key == System.Windows.Input.Key.Enter) { e.Handled = true; cbxSession.SelectionChanged += cbxSession_SelectionChanged; } if ((e.Key == System.Windows.Input.Key.Up) || (e.Key == System.Windows.Input.Key.Down)) { e.Handled = true; } } private void cbxSession_DropDownClosed(object sender, EventArgs e) { if (cbxSession.Text != "") { TextBox textBox = cbxSession.Template.FindName("PART_EditableTextBox", cbxSession) as TextBox; if (!cbxSession.Items.Contains(textBox.Text)) { textBox.Text = cbxSession.Text; } } } private void cbxSession_DropDownOpened(object sender, EventArgs e) { cbxSession.Items.Filter += a => { return true; }; } <ComboBox x:Name="cbxSession" Width="260" Canvas.Top="5" Canvas.Left="79" Height="25" Visibility="Visible" SelectionChanged="cbxSession_SelectionChanged" MaxDropDownHeight="200" IsTextSearchEnabled="False" IsEditable="True" IsReadOnly="True" Loaded="cbxSession_Loaded" DropDownClosed="cbxSession_DropDownClosed" StaysOpenOnEdit="True" DropDownOpened="cbxSession_DropDownOpened"> <ComboBox.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel IsVirtualizing="True" IsItemsHost="True"/> </ItemsPanelTemplate> </ComboBox.ItemsPanel> </ComboBox> But, the problem I am facing is... When I try searching, the first character goes missing. And this happens only once. Secondly, When I am using Arrow buttons to the filtered items, the ComboboxSelectionChanged event is fired. Is there any way to make it fire only on the click of 'Enter'

    Read the article

  • Spring mail support - no subject

    - by Trick
    I have updated my libraries, and now e-mails are sent without subject. I don't know where this happened... Mail API is 1.4.3., Spring 2.5.6. and Spring Integration Mail 1.0.3.RELEASE. <!-- Definitions for SMTP server --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${mail.host}" /> <property name="username" value="${mail.username}" /> <property name="password" value="${mail.password}" /> </bean> <bean id="adminMailTemplate" class="org.springframework.mail.SimpleMailMessage" > <property name="from" value="${mail.admin.from}" /> <property name="to" value="${mail.admin.to}" /> <property name="cc"> <list> <value>${mail.admin.cc1}</value> </list> </property> </bean> <!-- Mail service definition --> <bean id="mailService" class="net.bbb.core.service.impl.MailServiceImpl"> <property name="sender" ref="mailSender"/> <property name="mail" ref="adminMailTemplate"/> </bean> And properties mail.host,mail.username,mail.password,mail.admin.from,mail.admin.to, mail.admin.cc1. Java class: /** The sender. */ private MailSender sender; /** The mail. */ private SimpleMailMessage mail; public void sendMail() { this.mail.setSubject("Subject"); this.mail.setText("msg body"); try { getSender().send(this.mail); } catch (MailException e) { log.error("Error sending mail!",e); } } public SimpleMailMessage getMail() { return this.mail; } public void setMail(SimpleMailMessage mail) { this.mail = mail; } public MailSender getSender() { return this.sender; } public void setSender(MailSender mailSender1) { this.sender = mailSender1; } Everything worked before, I am wondering if there may be any conflicts with new libraries.

    Read the article

  • How to Resolve Jason issue

    - by Mohammad Nezhad
    I am working in a web scheduling application which uses DayPilot component I started by reading the documentation and use the calendar control. but whenever I do some thing which (fires an event on the Daypilot control) I face with following error An exception was thrown in the server-side event handler: System.InvalidCastException: Instance Of JasonData doesn't hold a double at DayPilot.Jason.JasonData.op_Explicit(JasonData data) at DayPilot.Web.Ui.Events.EventMoveEventArgs..ctor(JasonData parameters, string[] fields, JasonData data) at DayPilot.Web.Ui.DayPilotCalendar.ExecuteEventJASON(String ea) at DayPilot.Web.Ui.DayPilotCalendar.System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string ea) at System.Web.UI.Page.PrepareCallback(String callbackControlID) here is the completed code in the ASPX page <DayPilot:DayPilotCalendar ID="DayPilotCalendar1" runat="server" Direction="RTL" Days="7" DataStartField="eventstart" DataEndField="eventend" DataTextField="name" DataValueField="id" DataTagFields="State" EventMoveHandling="CallBack" OnEventMove="DayPilotCalendar1_EventMove" EventEditHandling="CallBack" OnEventEdit="DayPilotCalendar1_EventEdit" EventClickHandling="Edit" OnBeforeEventRender="DayPilotCalendar1_BeforeEventRender" EventResizeHandling="CallBack" OnEventResize="DayPilotCalendar1_EventResize" EventDoubleClickHandling="CallBack" OnEventDoubleClick="DayPilotCalendar1_EventDoubleClick" oncommand="DayPilotCalendar1_Command" and here is the complete codebehind protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) Initialization(); } private void dbUpdateEvent(string id, DateTime start, DateTime end) { // update for move using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString)) { con.Open(); SqlCommand cmd = new SqlCommand("UPDATE [event] SET [eventstart] = @start, [eventend] = @end WHERE [id] = @id", con); cmd.Parameters.AddWithValue("id", id); cmd.Parameters.AddWithValue("start", start); cmd.Parameters.AddWithValue("end", end); cmd.ExecuteNonQuery(); } } private DataTable dbGetEvents(DateTime start, int days) { // get Data SqlDataAdapter da = new SqlDataAdapter("SELECT [id], [name], [eventstart], [eventend], [state], [other] FROM [event] WHERE NOT (([eventend] <= @start) OR ([eventstart] >= @end))", ConfigurationManager.ConnectionStrings["DayPilotTest"].ConnectionString); ; da.SelectCommand.Parameters.AddWithValue("start", start); da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days)); DataTable dt = new DataTable(); da.Fill(dt); return dt; } protected void DayPilotCalendar1_EventMove(object sender, DayPilot.Web.Ui.Events.EventMoveEventArgs e) { // Drag and Drop dbUpdateEvent(e.Value, e.NewStart, e.NewEnd); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DayPilotCalendar1.DataBind(); DayPilotCalendar1.Update(); } private void Initialization() { // first bind DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek(new DateTime(2009, 1, 1)); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DataBind(); } protected void DayPilotCalendar1_BeforeEventRender(object sender, BeforeEventRenderEventArgs e) { // change the color based on state if (e.Tag["State"] == "Fixed") { e.DurationBarColor = "Brown"; } } protected void DayPilotCalendar1_EventResize(object sender, DayPilot.Web.Ui.Events.EventResizeEventArgs e) { dbUpdateEvent(e.Value, e.NewStart, e.NewEnd); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DayPilotCalendar1.DataBind(); DayPilotCalendar1.Update(); } protected void DayPilotCalendar1_EventDoubleClick(object sender, EventClickEventArgs e) { dbInsertEvent(e.Text , e.Start, e.End, "New", "New Meeting"); DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days); DayPilotCalendar1.DataBind(); DayPilotCalendar1.Update(); } note that I remove unnecessary code behinds

    Read the article

  • Working through exercises in "Cocoa Programming for Mac OS X" - I'm stumped

    - by Zigrivers
    I've been working through the exercises in a book recommended here on stackoverflow, however I've run into a problem and after three days of banging my head on the wall, I think I need some help. I'm working through the "Speakline" exercise where we add a TableView to the interface and the table will display the "voices" that you can choose for the text to speech aspect of the program. I am having two problems that I can't seem to get to the bottom of: I get the following error: * Illegal NSTableView data source (). Must implement numberOfRowsInTableView: and tableView:objectValueForTableColumn:row: The tableView that is supposed to display the voices comes up blank I have a feeling that both of these problems are related. I'm including my interface code here: #import <Cocoa/Cocoa.h> @interface AppController : NSObject <NSSpeechSynthesizerDelegate, NSTableViewDelegate> { IBOutlet NSTextField *textField; NSSpeechSynthesizer *speechSynth; IBOutlet NSButton *stopButton; IBOutlet NSButton *startButton; IBOutlet NSTableView *tableView; NSArray *voiceList; } - (IBAction)sayIt:(id)sender; - (IBAction)stopIt:(id)sender; @end And my implementation code here: #import "AppController.h" @implementation AppController - (id)init { [super init]; //Log to help me understand what is happening NSLog(@"init"); speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil]; [speechSynth setDelegate:self]; voiceList = [[NSSpeechSynthesizer availableVoices] retain]; return self; } - (IBAction)sayIt:(id)sender { NSString *string = [[textField stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; //Is the string zero-length? if([string length] == 0) { NSLog(@"String from %@ is a string with a length of %d.", textField, [string length]); [speechSynth startSpeakingString:@"Please enter a phrase first."]; } [speechSynth startSpeakingString:string]; NSLog(@"Started to say: %@", string); [stopButton setEnabled:YES]; [startButton setEnabled:NO]; } - (IBAction)stopIt:(id)sender { NSLog(@"Stopping..."); [speechSynth stopSpeaking]; } - (void) speechSynthesizer:(NSSpeechSynthesizer *)sender didFinishSpeaking:(BOOL)complete { NSLog(@"Complete = %d", complete); [stopButton setEnabled:NO]; [startButton setEnabled:YES]; } - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView { return [voiceList count]; } - (id)tableView: (NSTableView *)tv objecValueForTableColumn: (NSTableColumn *)tableColumn row:(NSInteger)row { NSString *v = [voiceList objectAtIndex:row]; NSLog(@"v = %@",v); NSDictionary *dict = [NSSpeechSynthesizer attributesForVoice:v]; return [dict objectForKey:NSVoiceName]; } /* - (BOOL)respondsToSelector:(SEL)aSelector { NSString *methodName = NSStringFromSelector(aSelector); NSLog(@"respondsToSelector: %@", methodName); return [super respondsToSelector:aSelector]; } */ @end Hopefully, you guys can see something obvious that I've missed. Thank you!

    Read the article

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

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

    Read the article

  • Invalid Cross-Thread Operations from BackgroundWorker2_RunWorkerCompleted in C#

    - by Jim Fell
    Hello. I'm getting an error that does not make sense. Cross-thread operation not valid: Control 'buttonOpenFile' accessed from a thread other than the thread it was created on. In my application, the UI thread fires off backgroundWorker1, which when almost complete fires off backgroundWorker2 and waits for it to complete. backgroundWorker1 waits for backgroundWorker2 to complete, before it completes. AutoResetEvent variables are used to flag when each of the workers complete. In backgroundWorker2_RunWorkerComplete a function is called that resets the form controls. It is in this ResetFormControls() function where the exception is thrown. I thought it was safe to modify form controls in the RunWorkerCompleted function. Both background workers are instantiated from the UI thread. Here is a greatly summarized version of what I am doing: AutoResetEvent evtProgrammingComplete_c = new AutoResetEvent(false); AutoResetEvent evtResetComplete_c = new AutoResetEvent(false); private void ResetFormControls() { toolStripProgressBar1.Enabled = false; toolStripProgressBar1.RightToLeftLayout = false; toolStripProgressBar1.Value = 0; buttonInit.Enabled = true; buttonOpenFile.Enabled = true; // Error occurs here. buttonProgram.Enabled = true; buttonAbort.Enabled = false; buttonReset.Enabled = true; checkBoxPeripheryModule.Enabled = true; checkBoxVerbose.Enabled = true; comboBoxComPort.Enabled = true; groupBoxToolSettings.Enabled = true; groupBoxNodeSettings.Enabled = true; } private void buttonProgram_Click(object sender, EventArgs e) { while (backgroundWorkerProgram.IsBusy) backgroundWorkerProgram.CancelAsync(); backgroundWorkerProgram.RunWorkerAsync(); } private void backgroundWorkerProgram_DoWork(object sender, DoWorkEventArgs e) { // Does a bunch of stuff... if (tProgramStat_c == eProgramStat_t.DONE) { tProgramStat_c = eProgramStat_t.RESETTING; while (backgroundWorkerReset.IsBusy) backgroundWorkerReset.CancelAsync(); backgroundWorkerReset.RunWorkerAsync(); evtResetComplete_c.WaitOne(LONG_ACK_WAIT * 2); if (tResetStat_c == eResetStat_t.COMPLETED) tProgramStat_c = eProgramStat_t.DONE; } } private void backgroundWorkerProgram_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Updates form to report complete. No problems here. evtProgrammingComplete_c.Set(); backgroundWorkerProgram.Dispose(); } private void backgroundWorkerReset_DoWork(object sender, DoWorkEventArgs e) { // Does a bunch of stuff... if (tResetStat_c == eResetStat_t.COMPLETED) if (tProgramStat_c == eProgramStat_t.RESETTING) evtProgrammingComplete_c.WaitOne(); } private void backgroundWorkerReset_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { CloseAllComms(); ResetFormControls(); evtResetComplete_c.Set(); backgroundWorkerReset.Dispose(); } Any thoughts or suggestions you may have would be appreciated. I am using Microsoft Visual C# 2008 Express Edition. Thanks.

    Read the article

  • Form graphics not set when form loads

    - by Jimmy
    My form has a group box which contains two overlapping rectangles. The form's other controls are two sets of four numeric up down controls to set the rectangles' colors. (nudF1,2,3 and 4 set the rectangle that's in front, and nudB1,2,3 and 4 set the rectangle that's behind.) Everything works fine, except that the rectangles do not display the colors set in the numeric up downs when the form first loads. The numeric up down controls' ChangeValue events all call the ShowColors() method. The form's Load event calls the csColorsForm_Load() method. Any suggestions? namespace csColors { public partial class csColorsForm : Form { public csColorsForm() { InitializeComponent(); } private void csColorsForm_Load(object sender, EventArgs e) { this.BackColor = System.Drawing.Color.DarkBlue; SetColors(sender, e); } private void SetColors(object sender, EventArgs e) { Control control = (Control)sender; String ctrlName = control.Name; Graphics objGraphics; Rectangle rect1, rect2; int colorBack, colorFore; objGraphics = this.grpColor.CreateGraphics(); // If calling control is not a forecolor control, paint backcolor rectangle if (ctrlName.Substring(0,4)!="nudF") { colorBack = int.Parse(SetColorsB("nudB"), NumberStyles.HexNumber); SolidBrush BrushB = new SolidBrush(Color.FromArgb(colorBack)); rect1 = new Rectangle(this.grpColor.Left, this.grpColor.Top, this.grpColor.Width, this.grpColor.Height); objGraphics.FillRectangle(BrushB, rect1); } // Always paint forecolor rectangle colorFore = int.Parse(SetColorsB("nudF"), NumberStyles.HexNumber); SolidBrush BrushF = new SolidBrush(Color.FromArgb(colorFore)); rect2 = new Rectangle(this.grpColor.Left, this.grpColor.Top, this.grpColor.Width, this.grpColor.Height); objGraphics.FillRectangle(BrushF, rect2); objGraphics.Dispose(); } private string SetColorsB(string nam) { string txt=""; for (int n = 1; n <= 4; ++n) { var ud = Controls[nam + n] as NumericUpDown; int hex = (int)ud.Value; txt += hex.ToString("X2"); } return txt; } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } } }

    Read the article

  • Gmail and Live are making all messages from my server as spam.

    - by Ryan Kearney
    I'm getting very weird results here. When my server sends an email to my @hotmail or @gmail account, it's marked as spam. When I send email through my server from Outlook to @hotmail, it doesn't get marked as spam, but it still gets marked as spam in gmail. They seem to get through fine on Yahoo though. My servers hostname A record points to an IP address whose PTR record points back to the same domain name. The TXT record has a SPF record in it to allow email to be sent from that servers IP. I moved from a VPS to a Dedicated server when this started to happen. From what I can see, the email headers are identical. Here's one of my email headers that gmail marks as spam. Some fields were repalced. MYGMAILACCOUNT is the email address of the account the email was addressed to. USER is the name of the account on the system it was sent from HOSTNAME is the servers FQDN IPADDR is the IP Address of the Hostname MYDOMAIN is my domain name Delivered-To: MYGMAILACCOUNT Received: by 10.220.77.82 with SMTP id f18cs263483vck; Sat, 27 Feb 2010 23:58:02 -0800 (PST) Received: by 10.150.16.4 with SMTP id 4mr3886702ybp.110.1267343881628; Sat, 27 Feb 2010 23:58:01 -0800 (PST) Return-Path: <USER@HOSTNAME> Received: from HOSTNAME (HOSTNAME [IPADDR]) by mx.google.com with ESMTP id 17si4604419yxe.134.2010.02.27.23.58.01; Sat, 27 Feb 2010 23:58:01 -0800 (PST) Received-SPF: pass (google.com: best guess record for domain of USER@HOSTNAME designates IPADDR as permitted sender) client-ip=IPADDR; Authentication-Results: mx.google.com; spf=pass (google.com: best guess record for domain of USER@HOSTNAME designates IPADDR as permitted sender) smtp.mail=USER@HOSTNAME Received: from USER by HOSTNAME with local (Exim 4.69) (envelope-from <USER@HOSTNAME>) id 1Nle2K-0000t8-Bd for MYGMAILACCOUNT; Sun, 28 Feb 2010 02:57:36 -0500 To: Ryan Kearney <MYGMAILACCOUNT> Subject: [Email Subject] MIME-Version: 1.0 Content-type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From: webmaster@MYDOMAIN Message-Id: <E1Nle2K-0000t8-Bd@HOSTNAME> Sender: <USER@HOSTNAME> Date: Sun, 28 Feb 2010 02:57:36 -0500 X-AntiAbuse: This header was added to track abuse, please include it with any abuse report X-AntiAbuse: Primary Hostname - HOSTNAME X-AntiAbuse: Original Domain - gmail.com X-AntiAbuse: Originator/Caller UID/GID - [503 500] / [47 12] X-AntiAbuse: Sender Address Domain - HOSTNAME Anyone have any ideas as to why all mail leaving my server gets marked as spam? EDIT: I already used http://www.mxtoolbox.com/SuperTool.aspx to check if my servers IP's are blacklisted and they are in fact not. That's what I thought at first, but it isn't the case. Update Mar 1, 2010 I received the following email from Microsoft Thank you for writing to Windows Live Hotmail Domain Support. My name is * and I will be assisting you today. We have identified that messages from your IP are being filtered based on the recommendations of the SmartScreen filter. This is the spam filtering technology developed and operated by Microsoft and is built around the technology of machine learning. It learns to recognize what is and isn't spam. In short, we filter incoming emails that look like spam. I am not able to go into any specific details about what these filters specifically entail, as this would render them useless. E-mails from IPs are filtered based upon a combination of IP reputation and the content of individual emails. The reputation of an IP is influenced by a number of factors. Among these factors, which you as a sender can control, are: The IP's Junk Mail Reporting complaint rate The frequency and volume in which email is sent The number of spam trap account hits The RCPT success rate So I'm guessing it has to do with the fact that I got an IP address with little or no history in sending email. I've confirmed that I'm not on any blacklists. I'm guessing it's one of those things that will work itself out in a month or so. I'll post when I hear more.

    Read the article

  • EnOcean -> USB Serial Communication (C++)

    - by regorianer
    I guess it is not the right place to ask here for enocean specific details, but maybe I am doing something wrong by using serial connections and you can help me no matter if there is knowledge about this technology or not. I have a problem to communicate with the RCM152 Module. I have written a C++ program to communicate with the RCM152 by emulating packets of the PTM 200. I teach the RCM152 to listen to the following packets: [06/19/12 04:21:44.546] INFO: SENDING BYTE : 55 <-- start byte [06/19/12 04:21:44.546] INFO: SENDING BYTE : 00 <-- head begin [06/19/12 04:21:44.546] INFO: SENDING BYTE : 07 [06/19/12 04:21:44.546] INFO: SENDING BYTE : 07 [06/19/12 04:21:44.546] INFO: SENDING BYTE : 01 <-- head end [06/19/12 04:21:44.546] INFO: SENDING BYTE : 7a <-- CRC Check [06/19/12 04:21:44.546] INFO: SENDING BYTE : f6 <-- packet type [06/19/12 04:21:44.546] INFO: SENDING BYTE : 20 <-- My action (00 and 10 -> OFF, 20 and 30 -> ON) [06/19/12 04:21:44.546] INFO: SENDING BYTE : 00 <-- serial.byte 3 [06/19/12 04:21:44.546] INFO: SENDING BYTE : 24 <-- serial.byte 2 [06/19/12 04:21:44.546] INFO: SENDING BYTE : 21 <-- serial.byte 1 [06/19/12 04:21:44.546] INFO: SENDING BYTE : 87 <-- serial.byte 0 [06/19/12 04:21:44.546] INFO: SENDING BYTE : 30 <-- status [06/19/12 04:21:44.546] INFO: SENDING BYTE : 03 <-- 03 for send, 01 for receiver [06/19/12 04:21:44.546] INFO: SENDING BYTE : ff <-- begin destination [06/19/12 04:21:44.546] INFO: SENDING BYTE : ff [06/19/12 04:21:44.546] INFO: SENDING BYTE : ff [06/19/12 04:21:44.546] INFO: SENDING BYTE : ff <-- end destination [06/19/12 04:21:44.546] INFO: SENDING BYTE : ff <-- Transmission quality (sender ff) [06/19/12 04:21:44.546] INFO: SENDING BYTE : 00 [06/19/12 04:21:44.547] INFO: SENDING BYTE : 10 <-- CRC Check A PTM200 Device or a SG-FUS-24-230 Device are sending equivalent packets like: [06/19/12 04:30:31.106] INFO: Received Byte: 55 [06/19/12 04:30:31.106] INFO: Received Byte: 00 [06/19/12 04:30:31.106] INFO: Received Byte: 07 [06/19/12 04:30:31.106] INFO: Received Byte: 07 [06/19/12 04:30:31.106] INFO: Received Byte: 01 [06/19/12 04:30:31.106] INFO: Received Byte: 7a [06/19/12 04:30:31.106] INFO: Received Byte: f6 [06/19/12 04:30:31.106] INFO: Received Byte: 40 [06/19/12 04:30:31.106] INFO: Received Byte: 00 [06/19/12 04:30:31.106] INFO: Received Byte: 24 [06/19/12 04:30:31.106] INFO: Received Byte: 6c [06/19/12 04:30:31.106] INFO: Received Byte: 2f [06/19/12 04:30:31.106] INFO: Received Byte: 30 [06/19/12 04:30:31.106] INFO: Received Byte: 01 [06/19/12 04:30:31.106] INFO: Received Byte: ff [06/19/12 04:30:31.106] INFO: Received Byte: ff [06/19/12 04:30:31.108] INFO: Received Byte: ff [06/19/12 04:30:31.108] INFO: Received Byte: ff [06/19/12 04:30:31.108] INFO: Received Byte: 37 [06/19/12 04:30:31.108] INFO: Received Byte: 00 [06/19/12 04:30:31.108] INFO: Received Byte: d1 I can control the device connected to the RCM152 like I want to with my sending packets (thats a good fact and means that the RCM152 has learned my packets and can use them. Also the actions (0x10 - ON, 0x30 - OFF) are working fine), but the problem is, that no matter which serial I choose, the RCM152 reacts to these packets. I only want to have actions if the teached-in serial is send and all other packets with different serials to be ignored. The RCM152 is not reacting to the packets sent by the PTM200 nor by the SG-FUS-24-230 because these are not teached-in. Thats exactly what I want to have with the packets created myself. What am I doing wrong? The libraries I am using are these for C++ http://pvbrowser.de/pvbrowser/sf/manual/rllib/html/ The enocean EEP says: For this purpose of a determined relationship between transmitter and receiver each transmitting device has a unique Sender-ID which is part of each radio telegram. The receiving device detects from the Sender-ID whether the device is known, i.e., was already learned, or unknown. A telegram with unknown Sender-ID is disregarded.

    Read the article

  • Why does my Messaging Menu code not work when split into functions?

    - by fluteflute
    Below are two python programs. They're exactly the same, except for one is split into two functions. However only the one that's split into two functions doesn't work - the second function doesn't work. Why would this be? Note the code is taken from this useful blog post. Without functions (works): import gtk def show_window_function(x, y): print x print y # get the indicate module, which does all the work import indicate # Create a server item mm = indicate.indicate_server_ref_default() # If someone clicks your server item in the MM, fire the server-display signal mm.connect("server-display", show_window_function) # Set the type of messages that your item uses. It's not at all clear which types # you're allowed to use, here. mm.set_type("message.im") # You must specify a .desktop file: this is where the MM gets the name of your # app from. mm.set_desktop_file("/usr/share/applications/nautilus.desktop") # Show the item in the MM. mm.show() # Create a source item mm_source = indicate.Indicator() # Again, it's not clear which subtypes you are allowed to use here. mm_source.set_property("subtype", "im") # "Sender" is the text that appears in the source item in the MM mm_source.set_property("sender", "Unread") # If someone clicks this source item in the MM, fire the user-display signal mm_source.connect("user-display", show_window_function) # Light up the messaging menu so that people know something has changed mm_source.set_property("draw-attention", "true") # Set the count of messages in this source. mm_source.set_property("count", "15") # If you prefer, you can set the time of the last message from this source, # rather than the count. (You can't set both.) This means that instead of a # message count, the MM will show "2m" or similar for the time since this # message arrived. # mm_source.set_property_time("time", time.time()) mm_source.show() gtk.mainloop() With functions (second function is executed but doesn't actually work): import gtk def show_window_function(x, y): print x print y # get the indicate module, which does all the work import indicate def function1(): # Create a server item mm = indicate.indicate_server_ref_default() # If someone clicks your server item in the MM, fire the server-display signal mm.connect("server-display", show_window_function) # Set the type of messages that your item uses. It's not at all clear which types # you're allowed to use, here. mm.set_type("message.im") # You must specify a .desktop file: this is where the MM gets the name of your # app from. mm.set_desktop_file("/usr/share/applications/nautilus.desktop") # Show the item in the MM. mm.show() def function2(): # Create a source item mm_source = indicate.Indicator() # Again, it's not clear which subtypes you are allowed to use here. mm_source.set_property("subtype", "im") # "Sender" is the text that appears in the source item in the MM mm_source.set_property("sender", "Unread") # If someone clicks this source item in the MM, fire the user-display signal mm_source.connect("user-display", show_window_function) # Light up the messaging menu so that people know something has changed mm_source.set_property("draw-attention", "true") # Set the count of messages in this source. mm_source.set_property("count", "15") # If you prefer, you can set the time of the last message from this source, # rather than the count. (You can't set both.) This means that instead of a # message count, the MM will show "2m" or similar for the time since this # message arrived. # mm_source.set_property_time("time", time.time()) mm_source.show() function1() function2() gtk.mainloop()

    Read the article

  • XNA Multiplayer Games and Networking

    - by JoshReuben
    ·        XNA communication must by default be lightweight – if you are syncing game state between players from the Game.Update method, you must minimize traffic. That game loop may be firing 60 times a second and player 5 needs to know if his tank has collided with any player 3 and the angle of that gun turret. There are no WCF ServiceContract / DataContract niceties here, but at the same time the XNA networking stack simplifies the details. The payload must be simplistic - just an ordered set of numbers that you would map to meaningful enum values upon deserialization.   Overview ·        XNA allows you to create and join multiplayer game sessions, to manage game state across clients, and to interact with the friends list ·        Dependency on Gamer Services - to receive notifications such as sign-in status changes and game invitations ·        two types of online multiplayer games: system link game sessions (LAN) and LIVE sessions (WAN). ·        Minimum dev requirements: 1 Xbox 360 console + Creators Club membership to test network code - run 1 instance of game on Xbox 360, and 1 on a Windows-based computer   Network Sessions ·        A network session is made up of players in a game + up to 8 arbitrary integer properties describing the session ·        create custom enums – (e.g. GameMode, SkillLevel) as keys in NetworkSessionProperties collection ·        Player state: lobby, in-play   Session Types ·        local session - for split-screen gaming - requires no network traffic. ·        system link session - connects multiple gaming machines over a local subnet. ·        Xbox LIVE multiplayer session - occurs on the Internet. Ranked or unranked   Session Updates ·        NetworkSession class Update method - must be called once per frame. ·        performs the following actions: o   Sends the network packets. o   Changes the session state. o   Raises the managed events for any significant state changes. o   Returns the incoming packet data. ·        synchronize the session à packet-received and state-change events à no threading issues   Session Config ·        Session host - gaming machine that creates the session. XNA handles host migration ·        NetworkSession properties: AllowJoinInProgress , AllowHostMigration ·        NetworkSession groups: AllGamers, LocalGamers, RemoteGamers   Subscribe to NetworkSession events ·        GamerJoined ·        GamerLeft ·        GameStarted ·        GameEnded – use to return to lobby ·        SessionEnded – use to return to title screen   Create a Session session = NetworkSession.Create(         NetworkSessionType.SystemLink,         maximumLocalPlayers,         maximumGamers,         privateGamerSlots,         sessionProperties );   Start a Session if (session.IsHost) {     if (session.IsEveryoneReady)     {        session.StartGame();        foreach (var gamer in SignedInGamer.SignedInGamers)        {             gamer.Presence.PresenceMode =                 GamerPresenceMode.InCombat;   Find a Network Session AvailableNetworkSessionCollection availableSessions = NetworkSession.Find(     NetworkSessionType.SystemLink,       maximumLocalPlayers,     networkSessionProperties); availableSessions.AllowJoinInProgress = true;   Join a Network Session NetworkSession session = NetworkSession.Join(     availableSessions[selectedSessionIndex]);   Sending Network Data var packetWriter = new PacketWriter(); foreach (LocalNetworkGamer gamer in session.LocalGamers) {     // Get the tank associated with this player.     Tank myTank = gamer.Tag as Tank;     // Write the data.     packetWriter.Write(myTank.Position);     packetWriter.Write(myTank.TankRotation);     packetWriter.Write(myTank.TurretRotation);     packetWriter.Write(myTank.IsFiring);     packetWriter.Write(myTank.Health);       // Send it to everyone.     gamer.SendData(packetWriter, SendDataOptions.None);     }   Receiving Network Data foreach (LocalNetworkGamer gamer in session.LocalGamers) {     // Keep reading while packets are available.     while (gamer.IsDataAvailable)     {         NetworkGamer sender;          // Read a single packet.         gamer.ReceiveData(packetReader, out sender);          if (!sender.IsLocal)         {             // Get the tank associated with this packet.             Tank remoteTank = sender.Tag as Tank;              // Read the data and apply it to the tank.             remoteTank.Position = packetReader.ReadVector2();             …   End a Session if (session.AllGamers.Count == 1)         {             session.EndGame();             session.Update();         }   Performance •        Aim to minimize payload, reliable in order messages •        Send Data Options: o   Unreliable, out of order -(SendDataOptions.None) o   Unreliable, in order (SendDataOptions.InOrder) o   Reliable, out of order (SendDataOptions.Reliable) o   Reliable, in order (SendDataOptions.ReliableInOrder) o   Chat data (SendDataOptions.Chat) •        Simulate: NetworkSession.SimulatedLatency , NetworkSession.SimulatedPacketLoss •        Voice support – NetworkGamer properties: HasVoice ,IsTalking , IsMutedByLocalUser

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >