Search Results

Search found 461 results on 19 pages for 'eventhandler'.

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

  • Getting Build Errors in Program to Change Button Name When Clicked

    - by Rishabh
    Imports System Imports System.Windows.Forms Class MyButtonClass Inherits Form Private mrButton As Button Public Sub MyButtonClass() mrButton = New Button() mrButton.Text = "Click me " mrButton.Click += New System.EventHandler(MyButtonClickEventHandler) Me.Controls.Add(mrButton) End Sub Shared Sub Main() Application.Run(New MyButtonClass()) End Sub Private Sub MyButtonClickEventHandler(ByVal sender As Object, ByVal e As EventArgs) mrButton.Text = "You clicked me!" End Sub End Class

    Read the article

  • javafx tableview get selected data from ObservableList

    - by user3717821
    i am working on a javafx project and i need your help . while i am trying to get selected data from table i can get selected data from normal cell but can't get data from ObservableList inside tableview. code for my database: -- phpMyAdmin SQL Dump -- version 4.0.4 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 10, 2014 at 06:20 AM -- Server version: 5.1.33-community -- PHP Version: 5.4.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `test` -- -- -------------------------------------------------------- -- -- Table structure for table `customer` -- CREATE TABLE IF NOT EXISTS `customer` ( `col0` int(11) NOT NULL, `col1` varchar(255) DEFAULT NULL, `col2` int(11) DEFAULT NULL, PRIMARY KEY (`col0`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `customer` -- INSERT INTO `customer` (`col0`, `col1`, `col2`) VALUES (12, 'adasdasd', 231), (22, 'adasdasd', 231), (212, 'adasdasd', 231); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; my javafx codes: import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import javafx.application.Application; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TablePosition; import javafx.scene.control.TableView; import javafx.scene.control.TableView.TableViewSelectionModel; import javafx.scene.control.cell.ChoiceBoxTableCell; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.StringConverter; class DBConnector { private static Connection conn; private static String url = "jdbc:mysql://localhost/test"; private static String user = "root"; private static String pass = "root"; public static Connection connect() throws SQLException{ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); }catch(ClassNotFoundException cnfe){ System.err.println("Error: "+cnfe.getMessage()); }catch(InstantiationException ie){ System.err.println("Error: "+ie.getMessage()); }catch(IllegalAccessException iae){ System.err.println("Error: "+iae.getMessage()); } conn = DriverManager.getConnection(url,user,pass); return conn; } public static Connection getConnection() throws SQLException, ClassNotFoundException{ if(conn !=null && !conn.isClosed()) return conn; connect(); return conn; } } public class DynamicTable extends Application{ Object newValue; //TABLE VIEW AND DATA private ObservableList<ObservableList> data; private TableView<ObservableList> tableview; //MAIN EXECUTOR public static void main(String[] args) { launch(args); } //CONNECTION DATABASE public void buildData(){ tableview.setEditable(true); Callback<TableColumn<Map, String>, TableCell<Map, String>> cellFactoryForMap = new Callback<TableColumn<Map, String>, TableCell<Map, String>>() { @Override public TableCell call(TableColumn p) { return new TextFieldTableCell(new StringConverter() { @Override public String toString(Object t) { return t.toString(); } @Override public Object fromString(String string) { return string; } }); } }; Connection c ; data = FXCollections.observableArrayList(); try{ c = DBConnector.connect(); //SQL FOR SELECTING ALL OF CUSTOMER String SQL = "SELECT * from CUSTOMer"; //ResultSet ResultSet rs = c.createStatement().executeQuery(SQL); /********************************** * TABLE COLUMN ADDED DYNAMICALLY * **********************************/ for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){ //We are using non property style for making dynamic table final int j = i; TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1)); if(j==1){ final ObservableList<String> logLevelList = FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG"); col.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList)); tableview.getColumns().addAll(col); } else{ col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){ public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) { return new SimpleStringProperty(param.getValue().get(j).toString()); } }); tableview.getColumns().addAll(col); } if(j!=1) col.setCellFactory(cellFactoryForMap); System.out.println("Column ["+i+"] "); } /******************************** * Data added to ObservableList * ********************************/ while(rs.next()){ //Iterate Row ObservableList<String> row = FXCollections.observableArrayList(); for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){ //Iterate Column row.add(rs.getString(i)); } System.out.println("Row [1] added "+row ); data.add(row); } //FINALLY ADDED TO TableView tableview.setItems(data); }catch(Exception e){ e.printStackTrace(); System.out.println("Error on Building Data"); } } @Override public void start(Stage stage) throws Exception { //TableView Button showDataButton = new Button("Add"); showDataButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { ObservableList<String> row = FXCollections.observableArrayList(); for(int i=1 ; i<=3; i++){ //Iterate Column row.add("asdasd"); } data.add(row); //FINALLY ADDED TO TableView tableview.setItems(data); } }); tableview = new TableView(); buildData(); //Main Scene BorderPane root = new BorderPane(); root.setCenter(tableview); root.setBottom(showDataButton); Scene scene = new Scene(root,500,500); stage.setScene(scene); stage.show(); tableview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observableValue, Object oldValue, Object newValue) { //Check whether item is selected and set value of selected item to Label if (tableview.getSelectionModel().getSelectedItem() != null) { TableViewSelectionModel selectionModel = tableview.getSelectionModel(); ObservableList selectedCells = selectionModel.getSelectedCells(); TablePosition tablePosition = (TablePosition) selectedCells.get(0); Object val = tablePosition.getTableColumn().getCellData(newValue); System.out.println("Selected Value " + val); System.out.println("Selected row " + newValue); } } }); } } please help me..

    Read the article

  • Wrapping ASP.NET Client Callbacks

    - by Ricardo Peres
    Client Callbacks are probably the less known (and I dare say, less loved) of all the AJAX options in ASP.NET, which also include the UpdatePanel, Page Methods and Web Services. The reason for that, I believe, is it’s relative complexity: Get a reference to a JavaScript function; Dynamically register function that calls the above reference; Have a JavaScript handler call the registered function. However, it has some the nice advantage of being self-contained, that is, doesn’t need additional files, such as web services, JavaScript libraries, etc, or static methods declared on a page, or any kind of attributes. So, here’s what I want to do: Have a DOM element which exposes a method that is executed server side, passing it a string and returning a string; Have a server-side event that handles the client-side call; Have two client-side user-supplied callback functions for handling the success and error results. I’m going to develop a custom control without user interface that does the registration of the client JavaScript method as well as a server-side event that can be hooked by some handler on a page. My markup will look like this: 1: <script type="text/javascript"> 1:  2:  3: function onCallbackSuccess(result, context) 4: { 5: } 6:  7: function onCallbackError(error, context) 8: { 9: } 10:  </script> 2: <my:CallbackControl runat="server" ID="callback" SendAllData="true" OnCallback="OnCallback"/> The control itself looks like this: 1: public class CallbackControl : Control, ICallbackEventHandler 2: { 3: #region Public constructor 4: public CallbackControl() 5: { 6: this.SendAllData = false; 7: this.Async = true; 8: } 9: #endregion 10:  11: #region Public properties and events 12: public event EventHandler<CallbackEventArgs> Callback; 13:  14: [DefaultValue(true)] 15: public Boolean Async 16: { 17: get; 18: set; 19: } 20:  21: [DefaultValue(false)] 22: public Boolean SendAllData 23: { 24: get; 25: set; 26: } 27:  28: #endregion 29:  30: #region Protected override methods 31:  32: protected override void Render(HtmlTextWriter writer) 33: { 34: writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); 35: writer.RenderBeginTag(HtmlTextWriterTag.Span); 36:  37: base.Render(writer); 38:  39: writer.RenderEndTag(); 40: } 41:  42: protected override void OnInit(EventArgs e) 43: { 44: String reference = this.Page.ClientScript.GetCallbackEventReference(this, "arg", "onCallbackSuccess", "context", "onCallbackError", this.Async); 45: String script = String.Concat("\ndocument.getElementById('", this.ClientID, "').callback = function(arg, context, onCallbackSuccess, onCallbackError){", ((this.SendAllData == true) ? "__theFormPostCollection.length = 0; __theFormPostData = ''; WebForm_InitCallback(); " : String.Empty), reference, ";};\n"); 46:  47: this.Page.ClientScript.RegisterStartupScript(this.GetType(), String.Concat("callback", this.ClientID), script, true); 48:  49: base.OnInit(e); 50: } 51:  52: #endregion 53:  54: #region Protected virtual methods 55: protected virtual void OnCallback(CallbackEventArgs args) 56: { 57: EventHandler<CallbackEventArgs> handler = this.Callback; 58:  59: if (handler != null) 60: { 61: handler(this, args); 62: } 63: } 64:  65: #endregion 66:  67: #region ICallbackEventHandler Members 68:  69: String ICallbackEventHandler.GetCallbackResult() 70: { 71: CallbackEventArgs args = new CallbackEventArgs(this.Context.Items["Data"] as String); 72:  73: this.OnCallback(args); 74:  75: return (args.Result); 76: } 77:  78: void ICallbackEventHandler.RaiseCallbackEvent(String eventArgument) 79: { 80: this.Context.Items["Data"] = eventArgument; 81: } 82:  83: #endregion 84: } And the event argument class: 1: [Serializable] 2: public class CallbackEventArgs : EventArgs 3: { 4: public CallbackEventArgs(String argument) 5: { 6: this.Argument = argument; 7: this.Result = String.Empty; 8: } 9:  10: public String Argument 11: { 12: get; 13: private set; 14: } 15:  16: public String Result 17: { 18: get; 19: set; 20: } 21: } You will notice two properties on the CallbackControl: Async: indicates if the call should be made asynchronously or synchronously (the default); SendAllData: indicates if the callback call will include the view and control state of all of the controls on the page, so that, on the server side, they will have their properties set when the Callback event is fired. The CallbackEventArgs class exposes two properties: Argument: the read-only argument passed to the client-side function; Result: the result to return to the client-side callback function, set from the Callback event handler. An example of an handler for the Callback event would be: 1: protected void OnCallback(Object sender, CallbackEventArgs e) 2: { 3: e.Result = String.Join(String.Empty, e.Argument.Reverse()); 4: } Finally, in order to fire the Callback event from the client, you only need this: 1: <input type="text" id="input"/> 2: <input type="button" value="Get Result" onclick="document.getElementById('callback').callback(callback(document.getElementById('input').value, 'context', onCallbackSuccess, onCallbackError))"/> The syntax of the callback function is: arg: some string argument; context: some context that will be passed to the callback functions (success or failure); callbackSuccessFunction: some function that will be called when the callback succeeds; callbackFailureFunction: some function that will be called if the callback fails for some reason. Give it a try and see if it helps!

    Read the article

  • General Purpose ASP.NET Data Source Control

    - by Ricardo Peres
    OK, you already know about the ObjectDataSource control, so what’s wrong with it? Well, for once, it doesn’t pass any context to the SelectMethod, you only get the parameters supplied on the SelectParameters plus the desired ordering, starting page and maximum number of rows to display. Also, you must have two separate methods, one for actually retrieving the data, and the other for getting the total number of records (SelectCountMethod). Finally, you don’t get a chance to alter the supplied data before you bind it to the target control. I wanted something simple to use, and more similar to ASP.NET 4.5, where you can have the select method on the page itself, so I came up with CustomDataSource. Here’s how to use it (I chose a GridView, but it works equally well with any regular data-bound control): 1: <web:CustomDataSourceControl runat="server" ID="datasource" PageSize="10" OnData="OnData" /> 2: <asp:GridView runat="server" ID="grid" DataSourceID="datasource" DataKeyNames="Id" PageSize="10" AllowPaging="true" AllowSorting="true" /> The OnData event handler receives a DataEventArgs instance, which contains some properties that describe the desired paging location and size, and it’s where you return the data plus the total record count. Here’s a quick example: 1: protected void OnData(object sender, DataEventArgs e) 2: { 3: //just return some data 4: var data = Enumerable.Range(e.StartRowIndex, e.PageSize).Select(x => new { Id = x, Value = x.ToString(), IsPair = ((x % 2) == 0) }); 5: e.Data = data; 6: //the total number of records 7: e.TotalRowCount = 100; 8: } Here’s the code for the DataEventArgs: 1: [Serializable] 2: public class DataEventArgs : EventArgs 3: { 4: public DataEventArgs(Int32 pageSize, Int32 startRowIndex, String sortExpression, IOrderedDictionary parameters) 5: { 6: this.PageSize = pageSize; 7: this.StartRowIndex = startRowIndex; 8: this.SortExpression = sortExpression; 9: this.Parameters = parameters; 10: } 11:  12: public IEnumerable Data 13: { 14: get; 15: set; 16: } 17:  18: public IOrderedDictionary Parameters 19: { 20: get; 21: private set; 22: } 23:  24: public String SortExpression 25: { 26: get; 27: private set; 28: } 29:  30: public Int32 StartRowIndex 31: { 32: get; 33: private set; 34: } 35:  36: public Int32 PageSize 37: { 38: get; 39: private set; 40: } 41:  42: public Int32 TotalRowCount 43: { 44: get; 45: set; 46: } 47: } As you can guess, the StartRowIndex and PageSize receive the starting row and the desired page size, where the page size comes from the PageSize property on the markup. There’s also a SortExpression, which gets passed the sorted-by column and direction (if descending) and a dictionary containing all the values coming from the SelectParameters collection, if any. All of these are read only, and it is your responsibility to fill in the Data and TotalRowCount. The code for the CustomDataSource is very simple: 1: [NonVisualControl] 2: public class CustomDataSourceControl : DataSourceControl 3: { 4: public CustomDataSourceControl() 5: { 6: this.SelectParameters = new ParameterCollection(); 7: } 8:  9: protected override DataSourceView GetView(String viewName) 10: { 11: return (new CustomDataSourceView(this, viewName)); 12: } 13:  14: internal void GetData(DataEventArgs args) 15: { 16: this.OnData(args); 17: } 18:  19: protected virtual void OnData(DataEventArgs args) 20: { 21: EventHandler<DataEventArgs> data = this.Data; 22:  23: if (data != null) 24: { 25: data(this, args); 26: } 27: } 28:  29: [Browsable(false)] 30: [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] 31: [PersistenceMode(PersistenceMode.InnerProperty)] 32: public ParameterCollection SelectParameters 33: { 34: get; 35: private set; 36: } 37:  38: public event EventHandler<DataEventArgs> Data; 39:  40: public Int32 PageSize 41: { 42: get; 43: set; 44: } 45: } Also, the code for the accompanying internal – as there is no need to use it from outside of its declaring assembly - data source view: 1: sealed class CustomDataSourceView : DataSourceView 2: { 3: private readonly CustomDataSourceControl dataSourceControl = null; 4:  5: public CustomDataSourceView(CustomDataSourceControl dataSourceControl, String viewName) : base(dataSourceControl, viewName) 6: { 7: this.dataSourceControl = dataSourceControl; 8: } 9:  10: public override Boolean CanPage 11: { 12: get 13: { 14: return (true); 15: } 16: } 17:  18: public override Boolean CanRetrieveTotalRowCount 19: { 20: get 21: { 22: return (true); 23: } 24: } 25:  26: public override Boolean CanSort 27: { 28: get 29: { 30: return (true); 31: } 32: } 33:  34: protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) 35: { 36: IOrderedDictionary parameters = this.dataSourceControl.SelectParameters.GetValues(HttpContext.Current, this.dataSourceControl); 37: DataEventArgs args = new DataEventArgs(this.dataSourceControl.PageSize, arguments.StartRowIndex, arguments.SortExpression, parameters); 38:  39: this.dataSourceControl.GetData(args); 40:  41: arguments.TotalRowCount = args.TotalRowCount; 42: arguments.MaximumRows = this.dataSourceControl.PageSize; 43: arguments.AddSupportedCapabilities(DataSourceCapabilities.Page | DataSourceCapabilities.Sort | DataSourceCapabilities.RetrieveTotalRowCount); 44: arguments.RetrieveTotalRowCount = true; 45:  46: if (!(args.Data is ICollection)) 47: { 48: return (args.Data.OfType<Object>().ToList()); 49: } 50: else 51: { 52: return (args.Data); 53: } 54: } 55: } As always, looking forward to hearing from you!

    Read the article

  • Asp.net Custom user control button. How to stop multiple clicks by user.

    - by Laurence Burke
    I am trying to modify an open source Forum called YetAnotherForum.net in the project they have a custom user control called Yaf:ThemeButton. Now its rendered as an anchor with an onclick method in this code ThemeButton.cs using System; using System.Web.UI; using System.Web.UI.WebControls; namespace YAF.Controls { /// <summary> /// The theme button. /// </summary> public class ThemeButton : BaseControl, IPostBackEventHandler { /// <summary> /// The _click event. /// </summary> protected static object _clickEvent = new object(); /// <summary> /// The _command event. /// </summary> protected static object _commandEvent = new object(); /// <summary> /// The _attribute collection. /// </summary> protected AttributeCollection _attributeCollection; /// <summary> /// The _localized label. /// </summary> protected LocalizedLabel _localizedLabel = new LocalizedLabel(); /// <summary> /// The _theme image. /// </summary> protected ThemeImage _themeImage = new ThemeImage(); /// <summary> /// Initializes a new instance of the <see cref="ThemeButton"/> class. /// </summary> public ThemeButton() : base() { Load += new EventHandler(ThemeButton_Load); this._attributeCollection = new AttributeCollection(ViewState); } /// <summary> /// ThemePage for the optional button image /// </summary> public string ImageThemePage { get { return this._themeImage.ThemePage; } set { this._themeImage.ThemePage = value; } } /// <summary> /// ThemeTag for the optional button image /// </summary> public string ImageThemeTag { get { return this._themeImage.ThemeTag; } set { this._themeImage.ThemeTag = value; } } /// <summary> /// Localized Page for the optional button text /// </summary> public string TextLocalizedPage { get { return this._localizedLabel.LocalizedPage; } set { this._localizedLabel.LocalizedPage = value; } } /// <summary> /// Localized Tag for the optional button text /// </summary> public string TextLocalizedTag { get { return this._localizedLabel.LocalizedTag; } set { this._localizedLabel.LocalizedTag = value; } } /// <summary> /// Defaults to "yafcssbutton" /// </summary> public string CssClass { get { return (ViewState["CssClass"] != null) ? ViewState["CssClass"] as string : "yafcssbutton"; } set { ViewState["CssClass"] = value; } } /// <summary> /// Setting the link property will make this control non-postback. /// </summary> public string NavigateUrl { get { return (ViewState["NavigateUrl"] != null) ? ViewState["NavigateUrl"] as string : string.Empty; } set { ViewState["NavigateUrl"] = value; } } /// <summary> /// Localized Page for the optional link description (title) /// </summary> public string TitleLocalizedPage { get { return (ViewState["TitleLocalizedPage"] != null) ? ViewState["TitleLocalizedPage"] as string : "BUTTON"; } set { ViewState["TitleLocalizedPage"] = value; } } /// <summary> /// Localized Tag for the optional link description (title) /// </summary> public string TitleLocalizedTag { get { return (ViewState["TitleLocalizedTag"] != null) ? ViewState["TitleLocalizedTag"] as string : string.Empty; } set { ViewState["TitleLocalizedTag"] = value; } } /// <summary> /// Non-localized Title for optional link description /// </summary> public string TitleNonLocalized { get { return (ViewState["TitleNonLocalized"] != null) ? ViewState["TitleNonLocalized"] as string : string.Empty; } set { ViewState["TitleNonLocalized"] = value; } } /// <summary> /// Gets Attributes. /// </summary> public AttributeCollection Attributes { get { return this._attributeCollection; } } /// <summary> /// Gets or sets CommandName. /// </summary> public string CommandName { get { if (ViewState["commandName"] != null) { return ViewState["commandName"].ToString(); } return null; } set { ViewState["commandName"] = value; } } /// <summary> /// Gets or sets CommandArgument. /// </summary> public string CommandArgument { get { if (ViewState["commandArgument"] != null) { return ViewState["commandArgument"].ToString(); } return null; } set { ViewState["commandArgument"] = value; } } #region IPostBackEventHandler Members /// <summary> /// The i post back event handler. raise post back event. /// </summary> /// <param name="eventArgument"> /// The event argument. /// </param> void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { OnCommand(new CommandEventArgs(CommandName, CommandArgument)); OnClick(EventArgs.Empty); } #endregion /// <summary> /// Setup the controls before render /// </summary> /// <param name="sender"> /// </param> /// <param name="e"> /// </param> private void ThemeButton_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(this._themeImage.ThemeTag)) { // add the theme image... Controls.Add(this._themeImage); } // render the text if available if (!String.IsNullOrEmpty(this._localizedLabel.LocalizedTag)) { Controls.Add(this._localizedLabel); } } /// <summary> /// The render. /// </summary> /// <param name="output"> /// The output. /// </param> protected override void Render(HtmlTextWriter output) { // get the title... string title = GetLocalizedTitle(); output.BeginRender(); output.WriteBeginTag("a"); output.WriteAttribute("id", ClientID); if (!String.IsNullOrEmpty(CssClass)) { output.WriteAttribute("class", CssClass); } if (!String.IsNullOrEmpty(title)) { output.WriteAttribute("title", title); } else if (!String.IsNullOrEmpty(TitleNonLocalized)) { output.WriteAttribute("title", TitleNonLocalized); } if (!String.IsNullOrEmpty(NavigateUrl)) { output.WriteAttribute("href", NavigateUrl.Replace("&", "&amp;")); } else { // string.Format("javascript:__doPostBack('{0}','{1}')",this.ClientID,"")); output.WriteAttribute("href", Page.ClientScript.GetPostBackClientHyperlink(this, string.Empty)); } bool wroteOnClick = false; // handle additional attributes (if any) if (this._attributeCollection.Count > 0) { // add attributes... foreach (string key in this._attributeCollection.Keys) { // get the attribute and write it... if (key.ToLower() == "onclick") { // special handling... add to it... output.WriteAttribute(key, string.Format("{0};{1}", this._attributeCollection[key], "this.blur();this.display='none';")); wroteOnClick = true; } else if (key.ToLower().StartsWith("on") || key.ToLower() == "rel" || key.ToLower() == "target") { // only write javascript attributes -- and a few other attributes... output.WriteAttribute(key, this._attributeCollection[key]); } } } // IE fix if (!wroteOnClick) { output.WriteAttribute("onclick", "this.blur();this.style.display='none';"); } output.Write(HtmlTextWriter.TagRightChar); output.WriteBeginTag("span"); output.Write(HtmlTextWriter.TagRightChar); // render the optional controls (if any) base.Render(output); output.WriteEndTag("span"); output.WriteEndTag("a"); output.EndRender(); } /// <summary> /// The get localized title. /// </summary> /// <returns> /// The get localized title. /// </returns> protected string GetLocalizedTitle() { if (Site != null && Site.DesignMode == true && !String.IsNullOrEmpty(TitleLocalizedTag)) { return String.Format("[TITLE:{0}]", TitleLocalizedTag); } else if (!String.IsNullOrEmpty(TitleLocalizedPage) && !String.IsNullOrEmpty(TitleLocalizedTag)) { return PageContext.Localization.GetText(TitleLocalizedPage, TitleLocalizedTag); } else if (!String.IsNullOrEmpty(TitleLocalizedTag)) { return PageContext.Localization.GetText(TitleLocalizedTag); } return null; } /// <summary> /// The on click. /// </summary> /// <param name="e"> /// The e. /// </param> protected virtual void OnClick(EventArgs e) { var handler = (EventHandler) Events[_clickEvent]; if (handler != null) { handler(this, e); } } /// <summary> /// The on command. /// </summary> /// <param name="e"> /// The e. /// </param> protected virtual void OnCommand(CommandEventArgs e) { var handler = (CommandEventHandler) Events[_commandEvent]; if (handler != null) { handler(this, e); } RaiseBubbleEvent(this, e); } /// <summary> /// The click. /// </summary> public event EventHandler Click { add { Events.AddHandler(_clickEvent, value); } remove { Events.RemoveHandler(_clickEvent, value); } } /// <summary> /// The command. /// </summary> public event CommandEventHandler Command { add { Events.AddHandler(_commandEvent, value); } remove { Events.RemoveHandler(_commandEvent, value); } } } } now that is just cs file its handled like this in the .ascx page of the actual website <YAF:ThemeButton ID="Save" runat="server" CssClass="yafcssbigbutton leftItem" TextLocalizedTag="SAVE" OnClick="Save_Click" /> now it is given an OnClick codebehind function that does some serverside function like this protected void Save_Click(object sender, EventArgs e) { //some serverside code here } now I have a problem with the user being able to click multiple times and firing that serverside function multiple times. I have added in the code as of right now an extra onclick="this.style.display='none'" in the .cs code but that is a ugly fix I was wondering if anyone would have a better idea of disabling the ThemeButton clientside?? pls any feedback if I need to give more examples or further explain the question thanks.

    Read the article

  • Conflict between two Javascripts (MailChimp validation etc. scripts & jQuery hSlides.js)

    - by Brian
    I have two scripts running on the same page, one is the jQuery.hSlides.js script http://www.jesuscarrera.info/demos/hslides/ and the other is a custom script that is used for MailChimp list signup integration. The hSlides panel can be seen in effect here: http://theatricalbellydance.com. I've turned off the MailChimp script because it was conflicting with the hSlides script, causing it not to to fail completely (as seen here http://theatricalbellydance.com/home2/). Can someone tell me what could be done to the hSlides script to stop the conflict with the MailChimp script? The MailChimp Script var fnames = new Array(); var ftypes = new Array(); fnames[0] = 'EMAIL'; ftypes[0] = 'email'; fnames[3] = 'MMERGE3'; ftypes[3] = 'text'; fnames[1] = 'FNAME'; ftypes[1] = 'text'; fnames[2] = 'LNAME'; ftypes[2] = 'text'; fnames[4] = 'MMERGE4'; ftypes[4] = 'address'; fnames[6] = 'MMERGE6'; ftypes[6] = 'number'; fnames[9] = 'MMERGE9'; ftypes[9] = 'text'; fnames[5] = 'MMERGE5'; ftypes[5] = 'text'; fnames[7] = 'MMERGE7'; ftypes[7] = 'text'; fnames[8] = 'MMERGE8'; ftypes[8] = 'text'; fnames[10] = 'MMERGE10'; ftypes[10] = 'text'; fnames[11] = 'MMERGE11'; ftypes[11] = 'text'; fnames[12] = 'MMERGE12'; ftypes[12] = 'text'; var err_style = ''; try { err_style = mc_custom_error_style; } catch (e) { err_style = 'margin: 1em 0 0 0; padding: 1em 0.5em 0.5em 0.5em; background: rgb(255, 238, 238) none repeat scroll 0% 0%; font-weight: bold; float: left; z-index: 1; width: 80%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: rgb(255, 0, 0);'; } var mce_jQuery = jQuery.noConflict(); mce_jQuery(document).ready(function ($) { var options = { errorClass: 'mce_inline_error', errorElement: 'div', errorStyle: err_style, onkeyup: function () {}, onfocusout: function () {}, onblur: function () {} }; var mce_validator = mce_jQuery("#mc-embedded-subscribe-form").validate(options); options = { url: 'http://theatricalbellydance.us1.list-manage.com/subscribe/post-json?u=1d127e7630ced825cb1a8b5a9&id=9f12d2a6bb&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8", beforeSubmit: function () { mce_jQuery('#mce_tmp_error_msg').remove(); mce_jQuery('.datefield', '#mc_embed_signup').each(function () { var txt = 'filled'; var fields = new Array(); var i = 0; mce_jQuery(':text', this).each(function () { fields[i] = this; i++; }); mce_jQuery(':hidden', this).each(function () { if (fields[0].value == 'MM' && fields[1].value == 'DD' && fields[2].value == 'YYYY') { this.value = ''; } else if (fields[0].value == '' && fields[1].value == '' && fields[2].value == '') { this.value = ''; } else { this.value = fields[0].value + '/' + fields[1].value + '/' + fields[2].value; } }); }); return mce_validator.form(); }, success: mce_success_cb }; mce_jQuery('#mc-embedded-subscribe-form').ajaxForm(options); }); function mce_success_cb(resp) { mce_jQuery('#mce-success-response').hide(); mce_jQuery('#mce-error-response').hide(); if (resp.result == "success") { mce_jQuery('#mce-' + resp.result + '-response').show(); mce_jQuery('#mce-' + resp.result + '-response').html(resp.msg); mce_jQuery('#mc-embedded-subscribe-form').each(function () { this.reset(); }); } else { var index = -1; var msg; try { var parts = resp.msg.split(' - ', 2); if (parts[1] == undefined) { msg = resp.msg; } else { i = parseInt(parts[0]); if (i.toString() == parts[0]) { index = parts[0]; msg = parts[1]; } else { index = -1; msg = resp.msg; } } } catch (e) { index = -1; msg = resp.msg; } try { if (index == -1) { mce_jQuery('#mce-' + resp.result + '-response').show(); mce_jQuery('#mce-' + resp.result + '-response').html(msg); } else { err_id = 'mce_tmp_error_msg'; html = '<div id="' + err_id + '" style="' + err_style + '"> ' + msg + '</div>'; var input_id = '#mc_embed_signup'; var f = mce_jQuery(input_id); if (ftypes[index] == 'address') { input_id = '#mce-' + fnames[index] + '-addr1'; f = mce_jQuery(input_id).parent().parent().get(0); } else if (ftypes[index] == 'date') { input_id = '#mce-' + fnames[index] + '-month'; f = mce_jQuery(input_id).parent().parent().get(0); } else { input_id = '#mce-' + fnames[index]; f = mce_jQuery().parent(input_id).get(0); } if (f) { mce_jQuery(f).append(html); mce_jQuery(input_id).focus(); } else { mce_jQuery('#mce-' + resp.result + '-response').show(); mce_jQuery('#mce-' + resp.result + '-response').html(msg); } } } catch (e) { mce_jQuery('#mce-' + resp.result + '-response').show(); mce_jQuery('#mce-' + resp.result + '-response').html(msg); } } } The hslides script: /* * hSlides (1.0) // 2008.02.25 // <http://plugins.jquery.com/project/hslides> * * REQUIRES jQuery 1.2.3+ <http://jquery.com/> * * Copyright (c) 2008 TrafficBroker <http://www.trafficbroker.co.uk> * Licensed under GPL and MIT licenses * * hSlides is an horizontal accordion navigation, sliding the panels around to reveal one of interest. * * Sample Configuration: * // this is the minimum configuration needed * $('#accordion').hSlides({ * totalWidth: 730, * totalHeight: 140, * minPanelWidth: 87, * maxPanelWidth: 425 * }); * * Config Options: * // Required configuration * totalWidth: Total width of the accordion // default: 0 * totalHeight: Total height of the accordion // default: 0 * minPanelWidth: Minimum width of the panel (closed) // default: 0 * maxPanelWidth: Maximum width of the panel (opened) // default: 0 * // Optional configuration * midPanelWidth: Middle width of the panel (centered) // default: 0 * speed: Speed for the animation // default: 500 * easing: Easing effect for the animation. Other than 'swing' or 'linear' must be provided by plugin // default: 'swing' * sensitivity: Sensitivity threshold (must be 1 or higher) // default: 3 * interval: Milliseconds for onMouseOver polling interval // default: 100 * timeout: Milliseconds delay before onMouseOut // default: 300 * eventHandler: Event to open panels: click or hover. For the hover option requires hoverIntent plugin <http://cherne.net/brian/resources/jquery.hoverIntent.html> // default: 'click' * panelSelector: HTML element storing the panels // default: 'li' * activeClass: CSS class for the active panel // default: none * panelPositioning: Accordion panelPositioning: top -> first panel on the bottom and next on the top, other value -> first panel on the top and next to the bottom // default: 'top' * // Callback funtctions. Inside them, we can refer the panel with $(this). * onEnter: Funtion raised when the panel is activated. // default: none * onLeave: Funtion raised when the panel is deactivated. // default: none * * We can override the defaults with: * $.fn.hSlides.defaults.easing = 'easeOutCubic'; * * @param settings An object with configuration options * @author Jesus Carrera <[email protected]> */ (function($) { $.fn.hSlides = function(settings) { // override default configuration settings = $.extend({}, $.fn.hSlides.defaults, settings); // for each accordion return this.each(function(){ var wrapper = this; var panelLeft = 0; var panels = $(settings.panelSelector, wrapper); var panelPositioning = 1; if (settings.panelPositioning != 'top'){ panelLeft = ($(settings.panelSelector, wrapper).length - 1) * settings.minPanelWidth; panels = $(settings.panelSelector, wrapper).reverse(); panelPositioning = -1; } // necessary styles for the wrapper $(this).css('position', 'relative').css('overflow', 'hidden').css('width', settings.totalWidth).css('height', settings.totalHeight); // set the initial position of the panels var zIndex = 0; panels.each(function(){ // necessary styles for the panels $(this).css('position', 'absolute').css('left', panelLeft).css('zIndex', zIndex).css('height', settings.totalHeight).css('width', settings.maxPanelWidth); zIndex ++; // if this panel is the activated by default, set it as active and move the next (to show this one) if ($(this).hasClass(settings.activeClass)){ $.data($(this)[0], 'active', true); if (settings.panelPositioning != 'top'){ panelLeft = ($(settings.panelSelector, wrapper).index(this) + 1) * settings.minPanelWidth - settings.maxPanelWidth; }else{ panelLeft = panelLeft + settings.maxPanelWidth; } }else{ // check if we are centering and some panel is active // this is why we can't add/remove the active class in the callbacks: positioning the panels if we have one active if (settings.midPanelWidth && $(settings.panelSelector, wrapper).hasClass(settings.activeClass) == false){ panelLeft = panelLeft + settings.midPanelWidth * panelPositioning; }else{ panelLeft = panelLeft + settings.minPanelWidth * panelPositioning; } } }); // iterates through the panels setting the active and changing the position var movePanels = function(){ // index of the new active panel var activeIndex = $(settings.panelSelector, wrapper).index(this); // iterate all panels panels.each(function(){ // deactivate if is the active if ( $.data($(this)[0], 'active') == true ){ $.data($(this)[0], 'active', false); $(this).removeClass(settings.activeClass).each(settings.onLeave); } // set position of current panel var currentIndex = $(settings.panelSelector, wrapper).index(this); panelLeft = settings.minPanelWidth * currentIndex; // if the panel is next to the active, we need to add the opened width if ( (currentIndex * panelPositioning) > (activeIndex * panelPositioning)){ panelLeft = panelLeft + (settings.maxPanelWidth - settings.minPanelWidth) * panelPositioning; } // animate $(this).animate({left: panelLeft}, settings.speed, settings.easing); }); // activate the new active panel $.data($(this)[0], 'active', true); $(this).addClass(settings.activeClass).each(settings.onEnter); }; // center the panels if configured var centerPanels = function(){ var panelLeft = 0; if (settings.panelPositioning != 'top'){ panelLeft = ($(settings.panelSelector, wrapper).length - 1) * settings.minPanelWidth; } panels.each(function(){ $(this).removeClass(settings.activeClass).animate({left: panelLeft}, settings.speed, settings.easing); if ($.data($(this)[0], 'active') == true){ $.data($(this)[0], 'active', false); $(this).each(settings.onLeave); } panelLeft = panelLeft + settings.midPanelWidth * panelPositioning ; }); }; // event handling if(settings.eventHandler == 'click'){ $(settings.panelSelector, wrapper).click(movePanels); }else{ var configHoverPanel = { sensitivity: settings.sensitivity, interval: settings.interval, over: movePanels, timeout: settings.timeout, out: function() {} } var configHoverWrapper = { sensitivity: settings.sensitivity, interval: settings.interval, over: function() {}, timeout: settings.timeout, out: centerPanels } $(settings.panelSelector, wrapper).hoverIntent(configHoverPanel); if (settings.midPanelWidth != 0){ $(wrapper).hoverIntent(configHoverWrapper); } } }); }; // invert the order of the jQuery elements $.fn.reverse = function(){ return this.pushStack(this.get().reverse(), arguments); }; // default settings $.fn.hSlides.defaults = { totalWidth: 0, totalHeight: 0, minPanelWidth: 0, maxPanelWidth: 0, midPanelWidth: 0, speed: 500, easing: 'swing', sensitivity: 3, interval: 100, timeout: 300, eventHandler: 'click', panelSelector: 'li', activeClass: false, panelPositioning: 'top', onEnter: function() {}, onLeave: function() {} }; })(jQuery);

    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

  • Take care to unhook Anonymous Delegates

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

    Read the article

  • How to minimize the usage of static variables and objects

    - by Peter Penzov
    I'm trying to implement this JavaFX code where I want to call remote Java class and pass boolean flag: final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation"); toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { //DataTabs.renderTab = toolbarSubMenuNavigation.isSelected(); DataTabs.setRenderTab(toolbarSubMenuNavigation.isSelected()); // call here the getter setter and send boolean flag System.out.println("subsystem1 #1 Enabled!"); } }); Java class which I want to call: public class DataTabs { private static boolean renderTab; // make members *private* private static TabPane tabPane; public static boolean isRenderTab() { return DataTabs.renderTab; } public static void setRenderTab(boolean renderTab) { DataTabs.renderTab = renderTab; tabPane.setVisible(renderTab); } // somewhere below // set visible the tab pane TabPane tabPane = DataTabs.tabPane = new TabPane(); tabPane.setVisible(renderTab); } This implementation works but I want to optimize it to use less static variables and objects. Can you tell me which sections of the code how can be optimized?

    Read the article

  • Event handler generation in Visual Studio 2012

    - by Jalpesh P. Vadgama
    This post will be a part of Visual Studio 2012 feature series There are lots of new features there in visual studio 2012. Event handler generation is one of them. In earlier version of visual studio there was no way to create event handler from source view directly.  Now visual studio 2012 have event handler generation functionality. So if you are editing an event view in source view intellisense will display add new event handler template and once you click on it. It will create a new event handler in the cs file. It will also put a eventhandler name against event name so you don’t need to write that. So, let’s take a simple example of button click event so once I write onclick attribute their smart intellisense will pop up . Now once you click on <Create New Event> It will create event handler in .cs file like following. It will also put submitButton_Click on onClick attribute. Hope you liked it. Stay tuned for more. Till then happy programming..

    Read the article

  • WCF net.tcp windows service - call duration and calls outstanding increases over time

    - by Brook
    I have a windows service which uses the ServiceHost class to host a WCF Service using the net.tcp binding. I have done some tweaking to the config to throttle sessions as well as number of connections, but it seems that every once in a while my "Calls outstanding" and "Call duration" shoot up and stay up in perfmon. It seems to me I have a leak somewhere, but the code I have is all fairly minimal, I'm relying on ServiceHost to handle the details. Here's how I start my service ServiceHost host = new ServiceHost(type); host.Faulted+=new EventHandler(Faulted); host.Open(); My Faulted event just does the following (more or less, logging etc removed) if (host.State == CommunicationState.Faulted) { host.Abort(); } else { host.Close(); } host = new ServiceHost(type); host.Faulted+=new EventHandler(Faulted); host.Open(); Here's some snippets from my app.config to show some of the things I've tried <runtime> <gcConcurrent enabled="true" /> <generatePublisherEvidence enabled="false" /> </runtime> ......... <behaviors> <serviceBehaviors> <behavior name="Throttled"> <serviceThrottling maxConcurrentCalls="300" maxConcurrentSessions="300" maxConcurrentInstances="300" /> .......... <services> <service name="MyService" behaviorConfiguration="Throttled"> <endpoint address="net.tcp://localhost:49001/MyService" binding="netTcpBinding" bindingConfiguration="Tcp" contract="IMyService"> </endpoint> </service> </services> .......... <netTcpBinding> <binding name="Tcp" openTimeout="00:00:10" closeTimeout="00:00:10" portSharingEnabled="true" receiveTimeout="00:5:00" sendTimeout="00:5:00" hostNameComparisonMode="WeakWildcard" listenBacklog="1000" maxConnections="1000"> <reliableSession enabled="false"/> <security mode="None"/> </binding> </netTcpBinding> .......... <!--for my diagnostics--> <diagnostics performanceCounters="ServiceOnly" wmiProviderEnabled="true" /> There's obviously some resource getting tied up, but I thought I covered everything with my config. I'm only getting about ~150 clients so I don't think I'm coming up against my "300" limit. "Calls per second" stays constant at anywhere from 2-5 calls per second. The service will run for hours and hours with 0-2 "calls outstanding" and very low "call duration" and then eventually it will shoot up to 30 calls oustanding and 20s call duration. Any tips on what might be causing my "calls outstanding" and "call duration" to spike? Where am I leaking? Point me in the right direction?

    Read the article

  • ASP.NET resseting SessionID cookie when cookie expiration date is set

    - by Sergej Andrejev
    I have two pages: Default.aspx and WebForm1.aspx. One of these pages stores a session variable which works fine until I add code which ads expiration date to SessionID cookie. What happens is: Open default.aspx Set-Cookie ASP.NET_SessionId=14jhsdfq23jkh13jkh12k1; expires=Fri, 19-Mar-2010 07:31:47 GMT; path=/ Click on link to open WebForm1.aspx No cookies set Click on link to open Default.aspx (Cookie is reset) Set-Cookie ASP.NET_SessionId=; expires=Fri, 19-Mar-2010 07:31:47 GMT; path=/ So the question would be how should I set SessionID cookie expiration date correctly? Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lnk.Click += new EventHandler(lnk_Click); Session["t"] = Guid.NewGuid(); Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(2); } void lnk_Click(object sender, EventArgs e) { Response.Redirect("WebForm1.aspx"); } } } Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:LinkButton runat="server" ID="lnk" Text=">>>" /> </div> </form> </body> </html> WebForm1.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lnk.Click += new EventHandler(lnk_Click); } void lnk_Click(object sender, EventArgs e) { Response.Redirect("Default.aspx"); } } } WebForm1.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:LinkButton runat="server" ID="lnk" Text=">>>" /> </div> </form> </body> </html>

    Read the article

  • Constant Memory Leak in SpeechSynthesizer

    - by DudeFX
    I have developed a project which I would like to release which uses c#, WPF and the System.Speech.Synthesizer object. The issue preventing the release of this project is that whenever SpeakAsync is called it leaves a memory leak that grows to the point of eventual failure. I believe I have cleaned up properly after using this object, but cannot find a cure. I have run the program through Ants Memory Profiler and it reports that WAVEHDR and WaveHeader is growing with each call. I have created a sample project to try to pinpoint the cause, but am still at a loss. Any help would be appreciated. The project uses VS2008 and is a c# WPF project that targets .NET 3.5 and Any CPU. You need to manually add a reference to System.Speech. Here is the Code: <Window x:Class="SpeechTest.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"> <Grid> <StackPanel Orientation="Vertical"> <Button Content="Start Speaking" Click="Start_Click" Margin="10" /> <Button Content="Stop Speaking" Click="Stop_Click" Margin="10" /> <Button Content="Exit" Click="Exit_Click" Margin="10"/> </StackPanel> </Grid> // Start of code behind using System; using System.Windows; using System.Speech.Synthesis; namespace SpeechTest { public partial class Window1 : Window { // speak setting private bool speakingOn = false; private int curLine = 0; private string [] speakLines = { "I am wondering", "Why whenever Speech is called", "A memory leak occurs", "If you run this long enough", "It will eventually crash", "Any help would be appreciated" }; public Window1() { InitializeComponent(); } private void Start_Click(object sender, RoutedEventArgs e) { speakingOn = true; SpeakLine(); } private void Stop_Click(object sender, RoutedEventArgs e) { speakingOn = false; } private void Exit_Click(object sender, RoutedEventArgs e) { App.Current.Shutdown(); } private void SpeakLine() { if (speakingOn) { // Create our speak object SpeechSynthesizer spk = new SpeechSynthesizer(); spk.SpeakCompleted += new EventHandler(spk_Completed); // Speak the line spk.SpeakAsync(speakLines[curLine]); } } public void spk_Completed(object sender, SpeakCompletedEventArgs e) { if (sender is SpeechSynthesizer) { // get access to our Speech object SpeechSynthesizer spk = (SpeechSynthesizer)sender; // Clean up after speaking (thinking the event handler is causing the memory leak) spk.SpeakCompleted -= new EventHandler(spk_Completed); // Dispose the speech object spk.Dispose(); // bump it curLine++; // check validity if (curLine = speakLines.Length) { // back to the beginning curLine = 0; } // Speak line SpeakLine(); } } } } I run this program on Windows 7 64 bit and it will run and eventually halt when attempting to create a new SpeechSynthesizer object. When run on Windows Vista 64 bit the memory will grow from a starting point of 34k to so far about 400k and growing. Can anyone see anything in the code that might be causing this, or is this an issue with the Speech object itself. Any help would be appreciated.

    Read the article

  • Problem with System.Diagnostics.Process RedirectStandardOutput to appear in Winforms Textbox in real

    - by Jonathan Websdale
    I'm having problems with the redirected output from a console application being presented in a Winforms textbox in real-time. The messages are being produced line by line however as soon as interaction with the Form is called for, nothing appears to be displayed. Following the many examples on both Stackoverflow and other forums, I can't seem to get the redirected output from the process to display in the textbox on the form until the process completes. By adding debug lines to the 'stringWriter_StringWritten' method and writing the redirected messages to the debug window I can see the messages arriving during the running of the process but these messages will not appear on the form's textbox until the process completes. Grateful for any advice on this. Here's an extract of the code public partial class RunExternalProcess : Form { private static int numberOutputLines = 0; private static MyStringWriter stringWriter; public RunExternalProcess() { InitializeComponent(); // Create the output message writter RunExternalProcess.stringWriter = new MyStringWriter(); stringWriter.StringWritten += new EventHandler(stringWriter_StringWritten); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = "myCommandLineApp.exe"; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; using (var pProcess = new System.Diagnostics.Process()) { pProcess.StartInfo = startInfo; pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(RunExternalProcess.Process_OutputDataReceived); pProcess.EnableRaisingEvents = true; try { pProcess.Start(); pProcess.BeginOutputReadLine(); pProcess.BeginErrorReadLine(); pProcess.WaitForExit(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { pProcess.OutputDataReceived -= new System.Diagnostics.DataReceivedEventHandler(RunExternalProcess.Process_OutputDataReceived); } } } private static void Process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { RunExternalProcess.OutputMessage(e.Data); } } private static void OutputMessage(string message) { RunExternalProcess.stringWriter.WriteLine("[" + RunExternalProcess.numberOutputLines++.ToString() + "] - " + message); } private void stringWriter_StringWritten(object sender, EventArgs e) { System.Diagnostics.Debug.WriteLine(((MyStringWriter)sender).GetStringBuilder().ToString()); SetProgressTextBox(((MyStringWriter)sender).GetStringBuilder().ToString()); } private delegate void SetProgressTextBoxCallback(string text); private void SetProgressTextBox(string text) { if (this.ProgressTextBox.InvokeRequired) { SetProgressTextBoxCallback callback = new SetProgressTextBoxCallback(SetProgressTextBox); this.BeginInvoke(callback, new object[] { text }); } else { this.ProgressTextBox.Text = text; this.ProgressTextBox.Select(this.ProgressTextBox.Text.Length, 0); this.ProgressTextBox.ScrollToCaret(); } } } public class MyStringWriter : System.IO.StringWriter { // Define the event. public event EventHandler StringWritten; public MyStringWriter() : base() { } public MyStringWriter(StringBuilder sb) : base(sb) { } public MyStringWriter(StringBuilder sb, IFormatProvider formatProvider) : base(sb, formatProvider) { } public MyStringWriter(IFormatProvider formatProvider) : base(formatProvider) { } protected virtual void OnStringWritten() { if (StringWritten != null) { StringWritten(this, EventArgs.Empty); } } public override void Write(char value) { base.Write(value); this.OnStringWritten(); } public override void Write(char[] buffer, int index, int count) { base.Write(buffer, index, count); this.OnStringWritten(); } public override void Write(string value) { base.Write(value); this.OnStringWritten(); } }

    Read the article

  • ASP.NET Membership API not working on Win2008 server/IIS7

    - by Program.X
    I have a very odd problem. I have a web app that uses the .NET Membership API to provide login functionality. This works fine on my local dev machine, using WebDev 4.0 server. I'm using .NET 4.0 with some URL Rewriting, but not on the pages where login is required. I have a Windows Server 2008 with IIS7 However, the Membership API seemingly does not work on the server. I have set up remote debugging and the LoginUser.LoggedIn event of the LoginUser control gets fired okay, but the MembershipUser is null. I get no answer about the username/password being invalid so it seems to be recognising it. If I enter an invalid username/password, I get an invalid username/password response. Some code, if it helps: <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="validation-error-list" ValidationGroup="LoginUserValidationGroup"/> <div class="accountInfo"> <fieldset class="login"> <legend>Account Information</legend> <p> <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label> <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" CssClass="validation-error" Display="Dynamic" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label> <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" CssClass="validation-error" Display="Dynamic" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:CheckBox ID="RememberMe" runat="server"/> <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label> </p> </fieldset> <p class="login-action"> <asp:Button ID="LoginButton" runat="server" CommandName="Login" CssClass="submitButton" Text="Log In" ValidationGroup="LoginUserValidationGroup"/> </p> and the code behind: protected void Page_Load(object sender, EventArgs e) { LoginUser.LoginError += new EventHandler(LoginUser_LoginError); LoginUser.LoggedIn += new EventHandler(LoginUser_LoggedIn); } void LoginUser_LoggedIn(object sender, EventArgs e) { // this code gets run so it appears logins work Roles.DeleteCookie(); // this behaviour has been removed for testing - no difference } void LoginUser_LoginError(object sender, EventArgs e) { HtmlGenericControl htmlGenericControl = LoginUser.FindControl("errorMessageSpan") as HtmlGenericControl; if (htmlGenericControl != null) htmlGenericControl.Visible = true; } I have "Fiddled" with the Login form reponse and I get the following Cookie-Set headers: Set-Cookie: ASP.NET_SessionId=lpyyiyjw45jjtuav1gdu4jmg; path=/; HttpOnly Set-Cookie: .ASPXAUTH=A7AE08E071DD20872D6BBBAD9167A709DEE55B352283A7F91E1066FFB1529E5C61FCEDC86E558CEA1A837E79640BE88D1F65F14FA8434AA86407DA3AEED575E0649A1AC319752FBCD39B2A4669B0F869; path=/; HttpOnly Set-Cookie: .ASPXROLES=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/; HttpOnly I don't know what is useful here because it is obviously encrypted but I find the .APXROLES cookie having no value interesting. It seems to fail to register the cookie, but passes authentication

    Read the article

  • How can I read the verbose output from a Cmdlet in C# using Exchange Powershell

    - by mrkeith
    Environment: Exchange 2007 sp3 (2003 sp2 mixed mode) Visual Studio 2008, .Net 3.5 Hello, I'm working with an Exchange powershell move-mailbox cmdlet and have noted when I do so from the Exchange Management shell (using the Verbose switch) there is a ton of real-time information provided. To provide a little context, I'm attempting to create a UI application that moves mailboxes similarly to the Exchange Management Console but desire to support an input file and specific server/database destinations for each entry (and threading). Here's roughly what I have at present but I'm not sure if there is an event I need to register for or what... And to be clear, I desire to get this information in real-time so I may update my UI to reflect what's occurring in the move sequence for the appropriate user (pretty much like the native functionality offered in the Management Console). And in case you are wondering, the reason why I'm not content with the Management Console functionality is, I have an algorithm which I'm using to balance users depending on storage limit, Blackberry use, journaling, exception mailbox size etc which demands user be mapped to specific locations... and I do not desire to create many/several move groups for each common destination or to hunt for lists of users individually through the management console UI. I can not seem to find any good documentation or examples of how to tie into reading the verbose messages that are provided within the console using C# (I see value in being able to read this kind of information in many different scenarios). I've explored the Invoke and InvokeAsync methods and the StateChanged & DataReady events but none of these seem to provide the information (verbose comments) that I'm after. Any direction or examples that can be provided will be very appreciated! A code sample which is little more than how I would ordinarily call any other powershell command follows: // config to use ExMgmt shell, create runspace and open it RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(); PSSnapInException snapInException = null; PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException); if (snapInException != null) throw snapInException; Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig); try { runspace.Open(); // create a pipeline and feed script text Pipeline pipeline = runspace.CreatePipeline(); string targetDatabase = @"myServer\myStorageGroup\myDB"; string mbxOwner = "[email protected]"; Command myMoveMailbox = new Command("Move-Mailbox", false, false); myMoveMailbox.Parameters.Add("Identity", mbxOwner); myMoveMailbox.Parameters.Add("TargetDatabase", targetDatabase); myMoveMailbox.Parameters.Add("Verbose"); myMoveMailbox.Parameters.Add("ValidateOnly"); myMoveMailbox.Parameters.Add("Confirm", false); pipeline.Commands.Add(myMoveMailbox); System.Collections.ObjectModel.Collection output = null; // these next few lines that are commented out are where I've tried // registering for events and calling asynchronously but this doesn't // seem to get me anywhere closer // //pipeline.StateChanged += new EventHandler(pipeline_StateChanged); //pipeline.Output.DataReady += new EventHandler(Output_DataReady); //pipeline.InvokeAsync(); //pipeline.Input.Close(); //return; tried these variations that are commented out but none seem to be useful output = pipeline.Invoke(); // Check for errors in the pipeline and throw an exception if necessary if (pipeline.Error != null && pipeline.Error.Count 0) { StringBuilder pipelineError = new StringBuilder(); pipelineError.AppendFormat("Error calling Test() Cmdlet. "); foreach (object item in pipeline.Error.ReadToEnd()) pipelineError.AppendFormat("{0}\n", item.ToString()); throw new Exception(pipelineError.ToString()); } foreach (PSObject psObject in output) { // blah, blah, blah // this is normally where I would read details about a particular PS command // but really pertains to a command once it finishes and has nothing to do with // the verbose messages that I'm after... since this part of the methods pertains // to the after-effects of a command having run, I'm suspecting I need to look to // the asynch invoke method but am not certain or knowing how. } } finally { runspace.Close(); } Thanks! Keith

    Read the article

  • Objective-C: Scope problems cellForRowAtIndexPath

    - by Mr. McPepperNuts
    How would I set each individual row in cellForRowAtIndexPath to the results of an array populated by a Fetch Request? (Fetch Request made when button is pressed.) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // ... set up cell code here ... cell.textLabel.text = [results objectAtIndex:indexPath valueForKey:@"name"]; } warning: 'NSArray' may not respond to '-objectAtIndexPath:' Edit: - (NSArray *)SearchDatabaseForText:(NSString *)passdTextToSearchFor{ NSManagedObject *searchObj; XYZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains [cd] %@", passdTextToSearchFor]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:managedObjectContext]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [request setEntity: entity]; [request setPredicate: predicate]; NSError *error; results = [managedObjectContext executeFetchRequest:request error:&error]; // NSLog(@"results %@", results); if([results count] == 0){ NSLog(@"No results found"); searchObj = nil; self.tempString = @"No results found."; }else{ if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) { NSLog(@"results %@", [[results objectAtIndex:0] name]); searchObj = [results objectAtIndex:0]; }else{ NSLog(@"No results found"); self.tempString = @"No results found."; searchObj = nil; } } [tableView reloadData]; [request release]; [sortDescriptors release]; return results; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ textToSearchFor = mySearchBar.text; results = [self SearchDatabaseForText:textToSearchFor]; self.tempString = [myGlobalSearchObject valueForKey:@"name"]; NSLog(@"results count: %d", [results count]); NSLog(@"results 0: %@", [[results objectAtIndex:0] name]); NSLog(@"results 1: %@", [[results objectAtIndex:1] name]); } @end Console prints: 2010-06-10 16:11:18.581 XYZApp[10140:207] results count: 2 2010-06-10 16:11:18.581 XYZApp[10140:207] results 0: BB Bugs 2010-06-10 16:11:18.582 XYZApp[10140:207] results 1: BB Annie Program received signal: “EXC_BAD_ACCESS”. (gdb) Edit 2: BT: #0 0x95a91edb in objc_msgSend () #1 0x03b1fe20 in ?? () #2 0x0043cd2a in -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] () #3 0x0043ca9e in -[UITableViewRowData invalidateAllSections] () #4 0x002fc82f in -[UITableView(_UITableViewPrivate) _updateRowData] () #5 0x002f7313 in -[UITableView noteNumberOfRowsChanged] () #6 0x00301500 in -[UITableView reloadData] () #7 0x00008623 in -[SearchViewController SearchDatabaseForText:] (self=0x3d16190, _cmd=0xf02b, passdTextToSearchFor=0x3b29630) #8 0x000086ad in -[SearchViewController searchBarSearchButtonClicked:] (self=0x3d16190, _cmd=0x16492cc, searchBar=0x3d2dc50) #9 0x0047ac13 in -[UISearchBar(UISearchBarStatic) _searchFieldReturnPressed] () #10 0x0031094e in -[UIControl(Deprecated) sendAction:toTarget:forEvent:] () #11 0x00312f76 in -[UIControl(Internal) _sendActionsForEventMask:withEvent:] () #12 0x0032613b in -[UIFieldEditor webView:shouldInsertText:replacingDOMRange:givenAction:] () #13 0x01d5a72d in __invoking___ () #14 0x01d5a618 in -[NSInvocation invoke] () #15 0x0273fc0a in SendDelegateMessage () #16 0x033168bf in -[_WebSafeForwarder forwardInvocation:] () #17 0x01d7e6f4 in ___forwarding___ () #18 0x01d5a6c2 in __forwarding_prep_0___ () #19 0x03320fd4 in WebEditorClient::shouldInsertText () #20 0x0279dfed in WebCore::Editor::shouldInsertText () #21 0x027b67a5 in WebCore::Editor::insertParagraphSeparator () #22 0x0279d662 in WebCore::EventHandler::defaultTextInputEventHandler () #23 0x0276cee6 in WebCore::EventTargetNode::defaultEventHandler () #24 0x0276cb70 in WebCore::EventTargetNode::dispatchGenericEvent () #25 0x0276c611 in WebCore::EventTargetNode::dispatchEvent () #26 0x0279d327 in WebCore::EventHandler::handleTextInputEvent () #27 0x0279d229 in WebCore::Editor::insertText () #28 0x03320f4d in -[WebHTMLView(WebNSTextInputSupport) insertText:] () #29 0x0279d0b4 in -[WAKResponder tryToPerform:with:] () #30 0x03320a33 in -[WebView(WebViewEditingActions) _performResponderOperation:with:] () #31 0x03320990 in -[WebView(WebViewEditingActions) insertText:] () #32 0x00408231 in -[UIWebDocumentView insertText:] () #33 0x003ccd31 in -[UIKeyboardImpl acceptWord:firstDelete:addString:] () #34 0x003d2c8c in -[UIKeyboardImpl addInputString:fromVariantKey:] () #35 0x004d1a00 in -[UIKeyboardLayoutStar sendStringAction:forKey:] () #36 0x004d0285 in -[UIKeyboardLayoutStar handleHardwareKeyDownFromSimulator:] () #37 0x002b5bcb in -[UIApplication handleEvent:withNewEvent:] () #38 0x002b067f in -[UIApplication sendEvent:] () #39 0x002b7061 in _UIApplicationHandleEvent () #40 0x02542d59 in PurpleEventCallback () #41 0x01d55b80 in CFRunLoopRunSpecific () #42 0x01d54c48 in CFRunLoopRunInMode () #43 0x02541615 in GSEventRunModal () #44 0x025416da in GSEventRun () #45 0x002b7faf in UIApplicationMain () #46 0x00002578 in main (argc=1, argv=0xbfffef5c) at /Users/default/Documents/iPhone Projects/XYZApp/main.m:14

    Read the article

  • How to Print in VS10, Printing gives unhandled exception. Access Denied

    - by Smoka
    Im newish to coding, currently on a Windows Forms App using CLI in VS10 Everything seems to work, my document shows fine in the Preview dialog but then crash's. Heres only the code that seems relevant private: System::Drawing::Printing::PrintDocument^ docPrint; private: System::Windows::Forms::PrintDialog^ dlgPrint; private: System::Windows::Forms::PrintPreviewDialog^ dlgPrintPreview; this->button2 = (gcnew System::Windows::Forms::Button()); this->docPrint = (gcnew System::Drawing::Printing::PrintDocument()); this->dlgPrint = (gcnew System::Windows::Forms::PrintDialog()); this->dlgPrintPreview = (gcnew System::Windows::Forms::PrintPreviewDialog()); this->button2->Location = System::Drawing::Point(152, 355); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(75, 23); this->button2->TabIndex = 53; this->button2->Text = L"Print"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click_1); // // docPrint // this->docPrint->DocumentName = L"ResultsPage"; this->docPrint->PrintPage += gcnew System::Drawing::Printing::PrintPageEventHandler(this, &Form1::docPrint_PrintPage); // // dlgPrint // this->dlgPrint->Document = this->docPrint; this->dlgPrint->UseEXDialog = true; // // dlgPrintPreview // this->dlgPrintPreview->AutoScrollMargin = System::Drawing::Size(0, 0); this->dlgPrintPreview->AutoScrollMinSize = System::Drawing::Size(0, 0); this->dlgPrintPreview->ClientSize = System::Drawing::Size(400, 300); this->dlgPrintPreview->Document = this->docPrint; this->dlgPrintPreview->Enabled = true; this->dlgPrintPreview->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"dlgPrintPreview.Icon"))); this->dlgPrintPreview->Name = L"dlgPrintPreview"; this->dlgPrintPreview->Visible = false; this->dlgPrintPreview->Load += gcnew System::EventHandler(this, &Form1::dlgPrintPreview_Load); private: System::Void docPrint_PrintPage(System::Object^ sender, System::Drawing::Printing::PrintPageEventArgs^ e) { String ^ strDisplay = L"A Axis Rotations"; String ^ strDisplay2 = L"Centerline of Y" + CL_Y->Text + " + Z" + CL_Z->Text; String ^ strDisplay3 = L"Initial Position Y" + G54_Y->Text + " + Z" + G54_Z->Text; System::Drawing::Font ^ fntString = gcnew System::Drawing::Font(L"Times New Roman", 38, FontStyle::Bold); e->Graphics->DrawString(strDisplay, fntString, Brushes::Black, 200,20); e->Graphics->DrawString(strDisplay2, fntString, Brushes::Black, 80,150); e->Graphics->DrawString(strDisplay3, fntString, Brushes::Black, 80,220); e->Graphics->DrawString(Results->Text, fntString,Brushes::Black, 50,400); } private: System::Void button2_Click_1(System::Object^ sender, System::EventArgs^ e) { // docPrint->Print; dlgPrintPreview->ShowDialog(); } private: System::Void dlgPrintPreview_Load(System::Object^ sender, System::EventArgs^ e) { } Sorry if the formatting is ugly here. In case this is all wrong. what is the minimum requirements in code for a print job? Is there an easier way?

    Read the article

  • Windows Phone 7: Building a simple dictionary web client

    - by TechTwaddle
    Like I mentioned in this post a while back, I came across a dictionary web service called Aonaware that serves up word definitions from various dictionaries and is really easy to use. The services page on their website, http://services.aonaware.com/DictService/DictService.asmx, lists all the operations that are supported by the dictionary service. Here they are, Word Dictionary Web Service The following operations are supported. For a formal definition, please review the Service Description. Define Define given word, returning definitions from all dictionaries DefineInDict Define given word, returning definitions from specified dictionary DictionaryInfo Show information about the specified dictionary DictionaryList Returns a list of available dictionaries DictionaryListExtended Returns a list of advanced dictionaries (e.g. translating dictionaries) Match Look for matching words in all dictionaries using the given strategy MatchInDict Look for matching words in the specified dictionary using the given strategy ServerInfo Show remote server information StrategyList Return list of all available strategies on the server Follow the links above to get more information on each API. In this post we will be building a simple windows phone 7 client which uses this service to get word definitions for words entered by the user. The application will also allow the user to select a dictionary from all the available ones and look up the word definition in that dictionary. So of all the apis above we will be using only two, DictionaryList() to get a list of all supported dictionaries and DefineInDict() to get the word definition from a particular dictionary. Before we get started, a note to you all; I would have liked to implement this application using concepts from data binding, item templates, data templates etc. I have a basic understanding of what they are but, being a beginner, I am not very comfortable with those topics yet so I didn’t use them. I thought I’ll get this version out of the way and maybe in the next version I could give those a try. A somewhat scary mock-up of the what the final application will look like, Select Dictionary is a list picker control from the silverlight toolkit (you need to download and install the toolkit if you haven’t already). Below it is a textbox where the user can enter words to look up and a button beside it to fetch the word definition when clicked. Finally we have a textblock which occupies the remaining area and displays the word definition from the selected dictionary. Create a silverlight application for windows phone 7, AonawareDictionaryClient, and add references to the silverlight toolkit and the web service. From the solution explorer right on References and select Microsoft.Phone.Controls.Toolkit from under the .NET tab, Next, add a reference to the web service. Again right click on References and this time select Add Service Reference In the resulting dialog paste the service url in the Address field and press go, (url –> http://services.aonaware.com/DictService/DictService.asmx) once the service is discovered, provide a name for the NameSpace, in this case I’ve called it AonawareDictionaryService. Press OK. You can now use the classes and functions that are generated in the AonawareDictionaryClient.AonawareDictionaryService namespace. Let’s get the UI done now. In MainPage.xaml add a namespace declaration to use the toolkit controls, xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" the content of LayoutRoot is changed as follows, (sorry, no syntax highlighting in this post) <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,5,0,5">     <TextBlock x:Name="ApplicationTitle" Text="AONAWARE DICTIONARY CLIENT" Style="{StaticResource PhoneTextNormalStyle}"/>     <!--<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>--> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">     <Grid.RowDefinitions>         <RowDefinition Height="Auto"/>         <RowDefinition Height="Auto"/>         <RowDefinition Height="*"/>     </Grid.RowDefinitions>     <toolkit:ListPicker Grid.Column="1" x:Name="listPickerDictionaryList"                         Header="Select Dictionary :">     </toolkit:ListPicker>     <Grid Grid.Row="1" Margin="0,5,0,0">         <Grid.ColumnDefinitions>             <ColumnDefinition Width="*"/>             <ColumnDefinition Width="Auto" />         </Grid.ColumnDefinitions>         <TextBox x:Name="txtboxInputWord" Grid.Column="0" GotFocus="OnTextboxInputWordGotFocus" />         <Button x:Name="btnGo" Grid.Column="1" Click="OnButtonGoClick" >             <Button.Content>                 <Image Source="/images/button-go.png"/>             </Button.Content>         </Button>     </Grid>     <ScrollViewer Grid.Row="2" x:Name="scrollViewer">         <TextBlock  Margin="12,5,12,5"  x:Name="txtBlockWordMeaning" HorizontalAlignment="Stretch"                    VerticalAlignment="Stretch" TextWrapping="Wrap"                    FontSize="26" />     </ScrollViewer> </Grid> I have commented out the PageTitle as it occupies too much valuable space, and the ContentPanel is changed to contain three rows. First row contains the list picker control, second row contains the textbox and the button, and the third row contains a textblock within a scroll viewer. The designer will now be showing the final ui, Now go to MainPage.xaml.cs, and add the following namespace declarations, using Microsoft.Phone.Controls; using AonawareDictionaryClient.AonawareDictionaryService; using System.IO.IsolatedStorage; A class called DictServiceSoapClient would have been created for you in the background when you added a reference to the web service. This class functions as a wrapper to the services exported by the web service. All the web service functions that we saw at the start can be access through this class, or more precisely through an object of this class. Create a data member of type DictServiceSoapClient in the Mainpage class, and a function which initializes it, DictServiceSoapClient DictSvcClient = null; private DictServiceSoapClient GetDictServiceSoapClient() {     if (null == DictSvcClient)     {         DictSvcClient = new DictServiceSoapClient();     }     return DictSvcClient; } We have two major tasks remaining. First, when the application loads we need to populate the list picker with all the supported dictionaries and second, when the user enters a word and clicks on the arrow button we need to fetch the word’s meaning. Populating the List Picker In the OnNavigatingTo event of the MainPage, we call the DictionaryList() api. This can also be done in the OnLoading event handler of the MainPage; not sure if one has an advantage over the other. Here’s the code for OnNavigatedTo, protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {     DictServiceSoapClient client = GetDictServiceSoapClient();     client.DictionaryListCompleted += new EventHandler<DictionaryListCompletedEventArgs>(OnGetDictionaryListCompleted);     client.DictionaryListAsync();     base.OnNavigatedTo(e); } Windows Phone 7 supports only async calls to web services. When we added a reference to the dictionary service, asynchronous versions of all the functions were generated automatically. So in the above function we register a handler to the DictionaryListCompleted event which will occur when the call to DictionaryList() gets a response from the server. Then we call the DictionaryListAsynch() function which is the async version of the DictionaryList() api. The result of this api will be sent to the handler OnGetDictionaryListCompleted(), void OnGetDictionaryListCompleted(object sender, DictionaryListCompletedEventArgs e) {     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;     Dictionary[] listOfDictionaries;     if (e.Error == null)     {         listOfDictionaries = e.Result;         PopulateListPicker(listOfDictionaries, settings);     }     else if (settings.Contains("SavedDictionaryList"))     {         listOfDictionaries = settings["SavedDictionaryList"] as Dictionary[];         PopulateListPicker(listOfDictionaries, settings);     }     else     {         MessageBoxResult res = MessageBox.Show("An error occured while retrieving dictionary list, do you want to try again?", "Error", MessageBoxButton.OKCancel);         if (MessageBoxResult.OK == res)         {             GetDictServiceSoapClient().DictionaryListAsync();         }     }     settings.Save(); } I have used IsolatedStorageSettings to store a few things; the entire dictionary list and the dictionary that is selected when the user exits the application, so that the next time when the user starts the application the current dictionary is set to the last selected value. First we check if the api returned any error, if the error object is null e.Result will contain the list (actually array) of Dictionary type objects. If there was an error, we check the isolated storage settings to see if there is a dictionary list stored from a previous instance of the application and if so, we populate the list picker based on this saved list. Note that in this case there are chances that the dictionary list might be out of date if there have been changes on the server. Finally, if none of these cases are true, we display an error message to the user and try to fetch the list again. PopulateListPicker() is passed the array of Dictionary objects and the settings object as well, void PopulateListPicker(Dictionary[] listOfDictionaries, IsolatedStorageSettings settings) {     listPickerDictionaryList.Items.Clear();     foreach (Dictionary dictionary in listOfDictionaries)     {         listPickerDictionaryList.Items.Add(dictionary.Name);     }     settings["SavedDictionaryList"] = listOfDictionaries;     string savedDictionaryName;     if (settings.Contains("SavedDictionary"))     {         savedDictionaryName = settings["SavedDictionary"] as string;     }     else     {         savedDictionaryName = "WordNet (r) 2.0"; //default dictionary, wordnet     }     foreach (string dictName in listPickerDictionaryList.Items)     {         if (dictName == savedDictionaryName)         {             listPickerDictionaryList.SelectedItem = dictName;             break;         }     }     settings["SavedDictionary"] = listPickerDictionaryList.SelectedItem as string; } We first clear all the items from the list picker, add the dictionary names from the array and then create a key in the settings called SavedDictionaryList and store the dictionary list in it. We then check if there is saved dictionary available from a previous instance, if there is, we set it as the selected item in the list picker. And if not, we set “WordNet ® 2.0” as the default dictionary. Before returning, we save the selected dictionary in the “SavedDictionary” key of the isolated storage settings. Fetching word definitions Getting this part done is very similar to the above code. We get the input word from the textbox, call into DefineInDictAsync() to fetch the definition and when DefineInDictAsync completes, we get the result and display it in the textblock. Here is the handler for the button click, private void OnButtonGoClick(object sender, RoutedEventArgs e) {     txtBlockWordMeaning.Text = "Please wait..";     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;     if (txtboxInputWord.Text.Trim().Length <= 0)     {         MessageBox.Show("Please enter a word in the textbox and press 'Go'");     }     else     {         Dictionary[] listOfDictionaries = settings["SavedDictionaryList"] as Dictionary[];         string selectedDictionary = listPickerDictionaryList.SelectedItem.ToString();         string dictId = "wn"; //default dictionary is wordnet (wn is the dict id)         foreach (Dictionary dict in listOfDictionaries)         {             if (dict.Name == selectedDictionary)             {                 dictId = dict.Id;                 break;             }         }         DictServiceSoapClient client = GetDictServiceSoapClient();         client.DefineInDictCompleted += new EventHandler<DefineInDictCompletedEventArgs>(OnDefineInDictCompleted);         client.DefineInDictAsync(dictId, txtboxInputWord.Text.Trim());     } } We validate the input and then select the dictionary id based on the currently selected dictionary. We need the dictionary id because the api DefineInDict() expects the dictionary identifier and not the dictionary name. We could very well have stored the dictionary id in isolated storage settings too. Again, same as before, we register a event handler for the DefineInDictCompleted event and call the DefineInDictAsync() method passing in the dictionary id and the input word. void OnDefineInDictCompleted(object sender, DefineInDictCompletedEventArgs e) {     WordDefinition wd = e.Result;     scrollViewer.ScrollToVerticalOffset(0.0f);     if (wd.Definitions.Length == 0)     {         txtBlockWordMeaning.Text = String.Format("No definitions were found for '{0}' in '{1}'", txtboxInputWord.Text.Trim(), listPickerDictionaryList.SelectedItem.ToString().Trim());     }     else     {         foreach (Definition def in wd.Definitions)         {             string str = def.WordDefinition;             str = str.Replace("  ", " "); //some formatting             txtBlockWordMeaning.Text = str;         }     } } When the api completes, e.Result will contain a WordDefnition object. This class is also generated in the background while adding the service reference. We check the word definitions within this class to see if any results were returned, if not, we display a message to the user in the textblock. If a definition was found the text on the textblock is set to display the definition of the word. Adding final touches, we now need to save the current dictionary when the application exits. A small but useful thing is selecting the entire word in the input textbox when the user selects it. This makes sure that if the user has looked up a definition for a really long word, he doesn’t have to press ‘clear’ too many times to enter the next word, protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e) {     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;     settings["SavedDictionary"] = listPickerDictionaryList.SelectedItem as string;     settings.Save();     base.OnNavigatingFrom(e); } private void OnTextboxInputWordGotFocus(object sender, RoutedEventArgs e) {     TextBox txtbox = sender as TextBox;     if (txtbox.Text.Trim().Length > 0)     {         txtbox.SelectionStart = 0;         txtbox.SelectionLength = txtbox.Text.Length;     } } OnNavigatingFrom() is called whenever you navigate away from the MainPage, since our application contains only one page that would mean that it is exiting. I leave you with a short video of the application in action, but before that if you have any suggestions on how to make the code better and improve it please do leave a comment. Until next time…

    Read the article

  • Naudio,how to tell playback is completed

    - by Du Sijun
    I am using Naudio lib to write a simple win form audio recorder/player. My problem is how can I tell the playback is completed? I need to close the wave stream after that. I knew there is a PlaybackStopped event listed below: wfr = new NAudio.Wave.WaveFileReader(this.outputFilename); audioOutput = new DirectSoundOut(); WaveChannel32 wc = new NAudio.Wave.WaveChannel32(wfr); audioOutput.Init(wc); audioOutput.PlaybackStopped += new EventHandler<StoppedEventArgs>(audioOutput_PlaybackStopped); audioOutput.Play(); But this PlaybackStopped event seems can only be triggered by calling audioOutput.stop(), do anyone know how to determine if playback is complected? Thanks in advance C#,windows form,Naudio,windows 7,64bits

    Read the article

  • Recursion in Ecore-File?!

    - by Dominik
    Hey guys, just tried to convert towards a Ecore-Model from a given UML-Model. After this I am trying to create a Generator Model. Everytime I try to do this I get the Error Message, that there is a "Unhandled event loop exception" with this log: org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NullPointerException) at org.eclipse.swt.SWT.error(SWT.java:3884) at org.eclipse.swt.SWT.error(SWT.java:3799) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:137) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3885) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3506) at org.eclipse.jface.window.Window.runEventLoop(Window.java:825) at org.eclipse.jface.window.Window.open(Window.java:801) at org.eclipse.gmf.internal.bridge.ui.dashboard.DashboardMediator$RunWizardAction.run(DashboardMediator.java:316) at org.eclipse.gmf.internal.bridge.ui.dashboard.HyperlinkFigure$1.mousePressed(HyperlinkFigure.java:63) at org.eclipse.draw2d.Figure.handleMousePressed(Figure.java:873) at org.eclipse.draw2d.SWTEventDispatcher.dispatchMousePressed(SWTEventDispatcher.java:214) at org.eclipse.draw2d.LightweightSystem$EventHandler.mouseDown(LightweightSystem.java:513) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:179) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3910) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3503) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2369) at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2221) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:500) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:493) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:113) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:194) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514) at org.eclipse.equinox.launcher.Main.run(Main.java:1311) Caused by: java.lang.NullPointerException at org.eclipse.emf.converter.util.ConverterUtil.computeRequiredPackages(ConverterUtil.java:374) at org.eclipse.emf.converter.ui.contribution.base.ModelConverterPackagePage.validate(ModelConverterPackagePage.java:965) at org.eclipse.emf.importer.ui.contribution.base.ModelImporterPackagePage.validate(ModelImporterPackagePage.java:101) at org.eclipse.emf.converter.ui.contribution.base.ModelConverterPackagePage$1.run(ModelConverterPackagePage.java:155) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134) ... 34 more After this there occurs another exception with this text: "Unable to create editor ID org.eclipse.emf.codegen.ecore.genmodel.presentation.GenModelEditorID:An unexpected exception was thrown." The session data says: eclipse.buildId=unknown java.version=1.6.0_13 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_DE Framework arguments: -product org.eclipse.epp.package.modeling.product Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.modeling.product -consoleLog With this long log: java.lang.NullPointerException at org.eclipse.emf.ecore.util.EcoreUtil.getURI(EcoreUtil.java:2887) at org.eclipse.emf.codegen.ecore.genmodel.impl.GenModelImpl.diagnose(GenModelImpl.java:2930) at org.eclipse.emf.codegen.ecore.genmodel.presentation.GenModelEditor.validate(GenModelEditor.java:1773) at org.eclipse.emf.codegen.ecore.genmodel.presentation.GenModelEditor.initialize(GenModelEditor.java:596) at org.eclipse.emf.codegen.ecore.genmodel.presentation.GenModelEditor.createPages(GenModelEditor.java:1080) at org.eclipse.ui.part.MultiPageEditorPart.createPartControl(MultiPageEditorPart.java:357) at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:662) at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:462) at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595) at org.eclipse.ui.internal.EditorReference.getEditor(EditorReference.java:286) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditorBatched(WorkbenchPage.java:2857) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2762) at org.eclipse.ui.internal.WorkbenchPage.access$11(WorkbenchPage.java:2754) at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:2705) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2701) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2685) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2668) at org.eclipse.emf.converter.ui.contribution.base.ModelConverterWizard.openEditor(ModelConverterWizard.java:318) at org.eclipse.emf.importer.ui.contribution.base.ModelImporterWizard.performFinish(ModelImporterWizard.java:167) at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:752) at org.eclipse.gmf.internal.bridge.ui.dashboard.DashboardMediator$RunWizardAction$1.finishPressed(DashboardMediator.java:311) at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:373) at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:624) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:228) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3910) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3503) at org.eclipse.jface.window.Window.runEventLoop(Window.java:825) at org.eclipse.jface.window.Window.open(Window.java:801) at org.eclipse.gmf.internal.bridge.ui.dashboard.DashboardMediator$RunWizardAction.run(DashboardMediator.java:316) at org.eclipse.gmf.internal.bridge.ui.dashboard.HyperlinkFigure$1.mousePressed(HyperlinkFigure.java:63) at org.eclipse.draw2d.Figure.handleMousePressed(Figure.java:873) at org.eclipse.draw2d.SWTEventDispatcher.dispatchMousePressed(SWTEventDispatcher.java:214) at org.eclipse.draw2d.LightweightSystem$EventHandler.mouseDown(LightweightSystem.java:513) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:179) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3910) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3503) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2369) at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2221) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:500) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:493) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:113) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:194) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514) at org.eclipse.equinox.launcher.Main.run(Main.java:1311) Has anyone an idea what is going wrong? I looked a while at my model but were not able to find something wrong. I just thought there might be a recursion due to the "Unhandled event loop exception" but is this even possible? Thanks in advance, Dominik

    Read the article

  • C# process restart loop

    - by Andrej
    Hi, I'm trying to make a console app that would monitor some process and restart it if it exits. So, the console app is always on, it's only job is to restart some other process. I posted my code below.. it basically works but just for one process restart... I would appriciate any help!! Thanks in advance! { System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(SOME_PROCESS); p[0].Exited += new EventHandler(Startup_Exited); while (!p[0].HasExited) { p[0].WaitForExit(); } //Application.Run(); } private static void Startup_Exited(object sender, EventArgs e) { System.Diagnostics.Process.Start(AGAIN_THAT_SAME_PROCESS); }

    Read the article

  • How to get the value of a SELECT HtmlElement in C# webBrowser control

    - by AndrewW
    Hi, In a C# WebBrowser control, I have generated a SELECT HtmlElement with a number of OPTION elements using w.RenderBeginTag(HtmlTextWriterTag.Select). I need to get the value of the select when the user changes it, and so added an event handler in the WebBrowser DocumentCompleted event. private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { .... webBrowser1.Document.GetElementById("id_select_0").AttachEventHandler("onchange", new EventHandler(ddSelectedIndexChanged)); .... } protected void ddSelectedIndexChanged(object sender, EventArgs e) { .... } The event handler does get called, but the sender parameter is null and e is empty. Does anyone know how to overcome this problem? Andrew

    Read the article

  • FileSystemWatcher Changed event is raised twice

    - by user214707
    I have an application where I am looking for a text file and if there are any changes made to the file I am using the onchanged eventhandler to handle the event. I am using the notifyfilters.Lastwritetime but still the event is getting fired twice.Here is the code. public void Initialize() { FileSystemWatcher _fileWatcher = new FileSystemWatcher(); _fileWatcher.Path = "C:\\Folder"; _fileWatcher.NotifyFilter = NotifyFilters.LastWrite; _fileWatcher.Filter = "Version.txt"; _fileWatcher.Changed += new FileSystemEventHandler(OnChanged); _fileWatcher.EnableRaisingEvents = true; } private void OnChanged(object source, FileSystemEventArgs e) { ....... } I my case the Onchanged is called twice when I change the text file version.txt and save it.Please help.

    Read the article

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