Search Results

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

Page 123/174 | < Previous Page | 119 120 121 122 123 124 125 126 127 128 129 130  | Next Page >

  • Visibility of Class field-data of Mouse Clicked ImageButton located within WrapPanel

    - by Bill
    I am attempting to obtain the class-data behind an ImageButton that is mouse-clicked; which ImageButton is located within a WrapPanel filled with ImageButtons. The problem I am having is obtaining the visibility of the field data within the class behind the image-button. Although I can see the class, I can neither see nor access the field data. Can anyone please point me in the right direction? // Handles the ImageButton mouseClick event within the WrapPanel. private void SolarSystem_Click(Object sender, RoutedEventArgs e) { FrameworkElement fe = e.OriginalSource as FrameworkElement; SelectedPlanet PlanetSelected = new SelectedPlanet(fe); PlanetSelected.Owner = this; MessageBox.Show(PlanetSelected.PlanetName); } // Used to initiate instance of Class and some field data. public SelectedPlanet(FrameworkElement fe) { InitializeComponent(); string sPlanetName = ((PlanetClass)(fe)).PlanetName; return sPlanetName } // Class Data public class PlanetClass { string planetName; public PlanetClass(string planetName) { PlanetName = planetName; } public string PlanetName { set { planetName = value; } get { return planetName; } } }

    Read the article

  • Stop UITextView from jumping when programatically setting text

    - by Michael Waterfall
    Hi there, I have to update a small amount of text in a scrolling UITextView. I'll only be inserting a character where the cursor currently is, and I'll be doing this on a press of a button on my navigation bar. My problem is that whenever I call the setText method of the text view, it jumps to the bottom of the text. I've tried using contentOffset and resetting the selectedRange but it doesn't work! Here's my example: // Remember offset and selection CGPoint contentOffset = [entryTextView contentOffset]; NSRange selectedRange = [entryTextView selectedRange]; // Update text entryTextView.text = entryTextView.text; // Try and reset offset and selection [entryTextView setContentOffset:contentOffset animated:NO]; [entryTextView setSelectedRange: selectedRange]; Is there any way you can update the text without any scroll movement at all... as if they'd just typed something on the keyboard? Many thanks, Michael Edit: I've tried using the textViewDidChange: delegate method but it's still not scrolling up to the original location. - (void)textViewDidChange:(UITextView *)textView { if (self.programChanged) { [textView setSelectedRange:self.selectedRange]; [textView setContentOffset:self.contentOffset animated:NO]; self.programChanged = NO; } } - (void)changeButtonPressed:(id)sender { // Remember position self.programChanged = YES; self.contentOffset = [entryTextView contentOffset]; self.selectedRange = [entryTextView selectedRange]; // Update text entryTextView.text = entryTextView.text; }

    Read the article

  • Why ComboBox hides cursor when DroppedDown is set?

    - by Ivan Danilov
    Let's create WinForms Application (I have Visual Studio 2008 running on Windows Vista, but it seems that described situation takes place almost everywhere from Win98 to Vista, on native or managed code). Write such code: using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public class Form1 : Form { private readonly Button button1 = new Button(); private readonly ComboBox comboBox1 = new ComboBox(); private readonly TextBox textBox1 = new TextBox(); public Form1() { SuspendLayout(); textBox1.Location = new Point(21, 51); button1.Location = new Point(146, 49); button1.Text = "button1"; button1.Click += button1_Click; comboBox1.Items.AddRange(new[] {"1", "2", "3", "4", "5", "6"}); comboBox1.Location = new Point(21, 93); AcceptButton = button1; Controls.AddRange(new Control[] {textBox1, comboBox1, button1}); Text = "Form1"; ResumeLayout(false); PerformLayout(); } private void button1_Click(object sender, EventArgs e) { comboBox1.DroppedDown = true; } } } Then, run app. Place mouse cursor on the form and don't touch mouse anymore. Start to type something in TextBox - cursor will hide because of it. When you press Enter key - event throws and ComboBox will be dropped down. But now cursor won't appear even if you move it! And appears only when you click somewhere. There I've found discussion of this problem. But there's no good solution... Any thoughts? :)

    Read the article

  • C#, Asp.net Uploading files to file server...

    - by Imcl
    Using the link below, I wrote a code for my application. I am not able to get it right though, Please refer the link and help me ot with it... http://stackoverflow.com/questions/263518/c-uploading-files-to-file-server The following is my code:- protected void Button1_Click(object sender, EventArgs e) { filePath = FileUpload1.FileName; try { WebClient client = new WebClient(); NetworkCredential nc = new NetworkCredential(uName, password); Uri addy = new Uri("\\\\192.168.1.3\\upload\\"); client.Credentials = nc; byte[] arrReturn = client.UploadFile(addy, filePath); arrReturn = client.UploadFile(addy, filePath); Console.WriteLine(arrReturn.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); } } I also used:- File.Copy(filePath, "\\192.168.1.3\upload\"); The following line doesnt execute... byte[] arrReturn = client.UploadFile(addy, filePath); tried changing it to:- byte[] arrReturn = client.UploadFile("\\192.168.1.3\upload\", filePath); IT still doesnt work...Any solution to it?? I basically want to transfer a file from the client to the file storage server without actually loggin into the server so that the client cannot access the storage location on the server directly...

    Read the article

  • Application hangs after changing language From “En-Us” to any global language in control panel

    - by user1764824
    I created a WinForms application using C#. When I try to change the culture info, my application gets hanged. Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged); void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e) { if (!PreviousInstance()) { CultureInfo ObjCulture = new CultureInfo(CultureInfo.InvariantCulture.IetfLanguageTag, false); Thread.CurrentThread.CurrentCulture = ObjCulture; Application.CurrentCulture = ObjCulture; } } public void INIT() { CultureInfo objCultureInfo = null; try { objCultureInfo = new CultureInfo("en-US", false); objCultureInfo.NumberFormat.NumberDecimalSeparator = "."; objCultureInfo.NumberFormat.NegativeSign = "-"; objCultureInfo.NumberFormat.NumberNegativePattern = 1; //1 stands for -100. Application.CurrentCulture = objCultureInfo; } } After Changing Language ... My Application gets Hanged and i cant Debug anything When i Try to Evaluate things This Event Called only once.. But if try in a small application it comes every time when Language is changed... ... Nothing shown in Eventviewer either. How can I solve this problem? ..

    Read the article

  • Binding to WPF ViewModel properties

    - by MartinHN
    I'm just playing around with WPF and MVVM, and I have made a simple app that displays a Rectangle that changes color whenever Network availability changes. But when that happens, I get this error: Cannot use a DependencyObject that belongs to a different thread than its parent Freezable. Code XAML <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="400" Width="600"> <DockPanel LastChildFill="True"> <Rectangle x:Name="networkStatusRectangle" Width="200" Height="200" Fill="{Binding NetworkStatusColor}" /> </DockPanel> </Window> Code-behind using System.Windows; using WpfApplication1.ViewModels; namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = new NetworkViewModel(); } } } ViewModel using System.ComponentModel; using System.Net.NetworkInformation; using System.Windows.Media; namespace WpfApplication1.ViewModels { public class NetworkViewModel : INotifyPropertyChanged { private Brush _NetworkStatusColor; public Brush NetworkStatusColor { get { return _NetworkStatusColor; } set { _NetworkStatusColor = value; NotifyOfPropertyChange("NetworkStatusColor"); } } public NetworkViewModel() { NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged); } protected void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { if (e.IsAvailable) { this.NetworkStatusColor = new SolidColorBrush(Colors.Green); } else { this.NetworkStatusColor = new SolidColorBrush(Colors.Red); } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; public void NotifyOfPropertyChange(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } I assume that I should change the NetworkStatusColor property by invoking something?

    Read the article

  • Setting Path and Expiration for session cookie in asp.net

    - by Sergej Andrejev
    Anything I have tried didn't work. Currenly I have following code to change asp.net session cookie expiration date and path, but asp doesn't want to listen to me. I sends same cookie in Set-Cookie header two times sometimes, sometimes it sends it's default cookie ignoring path and expiration date, sometimes it sends everything as expected, and sometimes it doesn't send Set-Cookie at all. What should I do. This drives me nuts :( My code in Global.asax protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e) { /// only apply session cookie persistence to requests requiring session information if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState) { var sessionState = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection; var cookieName = sessionState != null && !string.IsNullOrEmpty(sessionState.CookieName) ? sessionState.CookieName : "ASP.NET_SessionId"; var timeout = sessionState != null ? sessionState.Timeout : TimeSpan.FromMinutes(20); /// Ensure ASP.NET Session Cookies are accessible throughout the subdomains. if (Request.Cookies[cookieName] != null && Session != null && Session.SessionID != null) { Response.Cookies[cookieName].Value = Session.SessionID; Response.Cookies[cookieName].Path = Request.ApplicationPath; Response.Cookies[cookieName].Expires = DateTime.Now.Add(timeout); } } }

    Read the article

  • Simulate Windows Service with ASP.NET

    - by Bayonian
    Hi, I have small web app that generate PDF files as a report. I'm trying to delete those generated PDF files after 10 sec that they are generated. What I want to do is to read a folder with PDF files every 10 sec, and delete all the PDF files inside that folder. I read this post of Easy Background Tasks in ASP.NET. The following code is the VB version. Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) AddTask("DoStuff", 10) End Sub Private Sub AddTask(ByVal name As String, ByVal seconds As Integer) OnCacheRemove = New CacheItemRemovedCallback(CacheItemRemoved) HttpRuntime.Cache.Insert(name, seconds, Nothing, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, _ OnCacheRemove) End Sub Public Sub CacheItemRemoved(ByVal k As String, ByVal v As Object, ByVal r As CacheItemRemovedReason) ' do stuff here if it matches our taskname, like WebRequest DeletePDFilesInFoler() ' re-add our task so it recurs AddTask(k, Convert.ToInt32(v)) End Sub But I got this error Delegate 'System.Web.Caching.CacheItemRemovedCallback' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. If this code works, where I should put it. Right, now I'm putting it in the master page. How to get this error out? Thank you

    Read the article

  • Render User Controls and call their Page_Load

    - by David Murdoch
    The following code will not work because the controls (page1, page2, page3) require that their "Page_Load" event gets called. using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; public partial class utilities_getPDF : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // add user controls to the page AddContentControl("controls/page1"); AddContentControl("controls/page2"); AddContentControl("controls/page3"); // set up the response to download the rendered PDF... Response.ContentType = "application/pdf"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AddHeader("Content-Disposition", "attachment;filename=FileName.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); // get the rendered HTML of the page System.IO.StringWriter stringWrite = new StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); this.Render(htmlWrite); StringReader reader = new StringReader(stringWrite.ToString()); // write the PDF to the OutputStream... Document doc = new Document(PageSize.A4); HTMLWorker parser = new HTMLWorker(doc); PdfWriter.GetInstance(doc, Response.OutputStream); doc.Open(); parser.Parse(reader); doc.Close(); } // the parts are probably irrelevant to the question... private const string contentPage = "~/includes/{0}.ascx"; private void AddContentControl(string page) { content.Controls.Add(myLoadControl(page)); } private Control myLoadControl(string page) { return TemplateControl.LoadControl(string.Format(contentPage, page)); } } So my question is: How can I get the controls HTML?

    Read the article

  • .NET socket timeout - blocking on Close method

    - by Mark
    I'm having trouble implementing a connect timeout using asynchronous socket calls. The idea being that I call BeginConnect on a Socket object, then use a timer to call Close() on the socket after a timeout period has elapsed. This works fine as long as the socket is created on the GUI thread - the Close method returns immediately, and the callback method is executed. However, if the socket is created on any other thread, the Close method blocks until the default IP timeout occurs. Code to reproduce: private Socket client; private void button1_Click(object sender, EventArgs e) { // Creating the socket on a threadpool thread causes Close to block. ThreadPool.QueueUserWorkItem((object state) => { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = client.BeginConnect(IPAddress.Parse("144.1.1.1"), 23, new AsyncCallback(CallbackMethod), client); // Wait for 2 seconds before closing the socket. if (result.AsyncWaitHandle.WaitOne(2000)) { MessageBox.Show("Connected."); } else { MessageBox.Show("Timed out. Closing socket..."); client.Close(); MessageBox.Show("Socket closed."); } }); } private void CallbackMethod(IAsyncResult result) { MessageBox.Show("Callback started."); Socket client = result.AsyncState as Socket; try { client.EndConnect(result); } catch (ObjectDisposedException) { } MessageBox.Show("Callback finished."); } If you remove the QueueUserWorkItem line, creating the socket on the GUI thread, the socket closes instantly without blocking. Can anyone shed some light on what's going on? Thanks. Edit - System.Net trace output seems to be different depending on whether it's being connected on the GUI thread or a different thread: Trace from non-blocking close when using GUI thread Trace from blocking close when using non-GUI thread

    Read the article

  • Passing data to Winforms UI using BeginInvoke

    - by Bi
    I am a C# newbie and have a class that needs to pass row information to a grid in the windows form. What is the best way to do it? I have put in some example code for better understanding. public class GUIController { private My_Main myWindow; public GUIController( My_Main window ) { myWindow = window; } public void UpdateProducts( List<myProduct> newList ) { object[] row = new object[3]; foreach (myProduct product in newList) { row[0] = product.Name; row[1] = product.Status; row[2] = product.Day; //HOW DO I USE BeginInvoke HERE? } } } And the form class below: public class My_Main : Form { //HOW DO I GO ABOUT USING THIS DELEGATE? public delegate void ProductDelegate( string[] row ); public static My_Main theWindow = null; static void Main( ) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); theWindow = new My_Main(); Application.Run(theWindow); } private void My_Main_Load( object sender, EventArgs e ) { /// Create GUIController and pass the window object gui = new GUIController( this ); } public void PopulateGrid( string[] row ) { ProductsGrid.Rows.Add(row); ProductsGrid.Update(); } }

    Read the article

  • C# i am trying to make a zoom effect

    - by thrillercd
    Pls help! i am trying to make a zoom effect on a picturebox by mouse wheel.Everything is ok except that when i use mouse middle button to zoom in or zoom out it is ok but it does not zoom in or zoom out the point which the mouse cursor on.when i zoom in the point what i want it always slide .Pls help me to add a snippet code to make it right working. Here is my code. I am trying to make a zoom effect on a picturebox by mouse wheel. Everything is ok except that when I use mouse middle button to zoom in or zoom out it is ok but it does not zoom in or zoom out the point which the mouse cursor on. When I zoom in the point what I want it always slide. Please help me to add a snippet code to make it right working. Here is my code: int i = 5; int index = 10; private double[] zoomfactor = { .25, .33, .50, .66, .80, 1, 1.25, 1.5, 2.0, 2.5, 3.0 }; private void Zoom(int i) { double new_Zoom = zoomfactor[i]; imgBox.Width = Convert.ToInt32(imgBox.Image.Width * new_Zoom); imgBox.Height = Convert.ToInt32(imgBox.Image.Height * new_Zoom); } private void On_wheel(object sender, System.Windows.Forms.MouseEventArgs e) { i = i + e.Delta / 120; if (i < 0) { i = 0; } else { if (i <= index) i = i; else i = index; } Zoom(i); }

    Read the article

  • How can I simulate this application hang scenario?

    - by Pwninstein
    I have a Windows Forms app that itself launches different threads to do different kinds of work. Occasionally, ALL threads (including the UI thread) become frozen, and my app becomes unresponsive. I've decided it may be a Garbage Collector-related issue, as the GC will freeze all managed threads temporarily. To verify that just managed threads are frozen, I spin up an unmanaged one that writes to a "heartbeat" file with a timestamp every second, and it is not affected (i.e. it still runs): public delegate void ThreadProc(); [DllImport("UnmanagedTest.dll", EntryPoint = "MyUnmanagedFunction")] public static extern void MyUnmanagedFunction(); [DllImport("kernel32")] public static extern IntPtr CreateThread( IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out uint dwThreadId); uint threadId; ThreadProc proc = new ThreadProc(MyUnmanagedFunction); IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(proc); IntPtr threadHandle = CreateThread(IntPtr.Zero, 0, functionPointer, IntPtr.Zero, 0, out threadId); My Question is: how can I simulate this situation, where all managed threads are suspended but unmanaged ones keep on spinning? My first stab: private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(delegate { new Hanger(); GC.Collect(2, GCCollectionMode.Forced); })); t.Start(); } class Hanger{ private int[] m_Integers = new int[10000000]; public Hanger() { } ~Hanger() { Console.WriteLine("About to hang..."); //This doesn't reproduce the desired behavior //while (true) ; //Neither does this //Thread.Sleep(System.Threading.Timeout.Infinite); } } Thanks in advance!!

    Read the article

  • WPF TextBox Interceping RoutedUICommands

    - by Joseph Sturtevant
    I am trying to get Undo/Redo keyboard shortcuts working in my WPF application (I have my own custom functionality implemented using the Command Pattern). It seems, however, that the TextBox control is intercepting my "Undo" RoutedUICommand. What is the simplest way to disable this so that I can catch Ctrl+Z at the root of my UI tree? I would like to avoid putting a ton of code/XAML into each TextBox in my application if possible. The following briefly demonstrates the problem: <Window x:Class="InputBindingSample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:InputBindingSample" Title="Window1" Height="300" Width="300"> <Window.CommandBindings> <CommandBinding Command="loc:Window1.MyUndo" Executed="MyUndo_Executed" /> </Window.CommandBindings> <DockPanel LastChildFill="True"> <StackPanel> <Button Content="Ctrl+Z Works If Focus Is Here" /> <TextBox Text="Ctrl+Z Doesn't Work If Focus Is Here" /> </StackPanel> </DockPanel> </Window> using System.Windows; using System.Windows.Input; namespace InputBindingSample { public partial class Window1 { public static readonly RoutedUICommand MyUndo = new RoutedUICommand("MyUndo", "MyUndo", typeof(Window1), new InputGestureCollection(new[] { new KeyGesture(Key.Z, ModifierKeys.Control) })); public Window1() { InitializeComponent(); } private void MyUndo_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("MyUndo!"); } } }

    Read the article

  • Referencing a Newly inserted Row's seeded PK in C# Linq

    - by Laurence Burke
    I want to use the primary key that was just created on the dc.submitchanges() to create a new EmployeeAddress row that references the employee to the address. protected void btnAdd_Click(object sender, EventArgs e) { if (txtZip.Text != "" && txtAdd1.Text != "" && txtCity.Text != "") { TestDataClassDataContext dc = new TestDataClassDataContext(); Address addr = new Address() { AddressLine1 = txtAdd1.Text, AddressLine2 = txtAdd2.Text, City = txtCity.Text, PostalCode = txtZip.Text, StateProvinceID = Convert.ToInt32(ddlState.SelectedValue) }; dc.Addresses.InsertOnSubmit(addr); lblSuccess.Visible = true; lblErrMsg.Visible = false; dc.SubmitChanges(); // // TODO: insert new row in EmployeeAddress to reference CurEmp to newly created address // SetAddrList(); } else { lblErrMsg.Text = "Invalid Input"; lblErrMsg.Visible = true; } } protected void SetAddrList() { TestDataClassDataContext dc = new TestDataClassDataContext(); dc.ObjectTrackingEnabled = false; var addList = from addr in dc.Addresses from eaddr in dc.EmployeeAddresses where eaddr.EmployeeID == _curEmpID && addr.AddressID == eaddr.AddressID select new { AddValue = addr.AddressID, AddText = addr.AddressID, }; ddlAddList.DataSource = addList; ddlAddList.DataValueField = "AddValue"; ddlAddList.DataTextField = "AddText"; ddlAddList.DataBind(); ddlAddList.Items.Add(new ListItem("<Add Address>", "-1")); }

    Read the article

  • how to set UISwitch pointer to access switch from one uiviewcontroller another uiviewcontroller

    - by Rkm
    System UIViewcontroller has button event.Tap on Button fire InfoTableviewController. InfoTableview has UISwitch . How to set NSMutableArray of UIswitch pointer for System UIViewcontroller to access switch . SystemUIviewcontroller button event - (IBAction) Info_Button_Clicked:(id) sender { // pushcontroller Info *info = [[Info alloc]initWithNibName:@"Info" bundle:[NSBundle mainBundle]]; [self.navigationController pushViewController:info animated:YES]; [info release]; } Here for Info TableviewController // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = nil; if ([indexPath section] == 0) { static NSString *kDisplayCell_ID = @"DisplayCellID"; cell = [self.tableView dequeueReusableCellWithIdentifier: kDisplayCell_ID]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: kDisplayCell_ID] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } else { // the cell is being recycled, remove old embedded controls UIView *viewToRemove = nil; viewToRemove = [cell.contentView viewWithTag:1]; if (viewToRemove) [viewToRemove removeFromSuperview]; } cell.textLabel.text = [[self.Soundarray objectAtIndex: indexPath.row] valueForKey:@"labelKey"]; UIControl *control = [[self.Soundarray objectAtIndex: indexPath.row] valueForKey:@"viewKey"]; [cell.contentView addSubview:control]; return cell; } }

    Read the article

  • SQL Cache Dependency not working with Stored Procedure

    - by pjacko
    Hello, I can't get SqlCacheDependency to work with a simple stored proc (SQL Server 2008): create proc dbo.spGetPeteTest as set ANSI_NULLS ON set ANSI_PADDING ON set ANSI_WARNINGS ON set CONCAT_NULL_YIELDS_NULL ON set QUOTED_IDENTIFIER ON set NUMERIC_ROUNDABORT OFF set ARITHABORT ON select Id, Artist, Album from dbo.PeteTest And here's my ASP.NET code (3.5 framework): -- global.asax protected void Application_Start(object sender, EventArgs e) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString; System.Data.SqlClient.SqlDependency.Start(connectionString); } -- Code-Behind private DataTable GetAlbums() { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["UnigoConnection"].ConnectionString; DataTable dtAlbums = new DataTable(); using (SqlConnection connection = new SqlConnection(connectionString)) { // Works using select statement, but NOT SP with same text //SqlCommand command = new SqlCommand( // "select Id, Artist, Album from dbo.PeteTest", connection); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandType = CommandType.StoredProcedure; command.CommandText = "dbo.spGetPeteTest"; System.Web.Caching.SqlCacheDependency new_dependency = new System.Web.Caching.SqlCacheDependency(command); SqlDataAdapter DA1 = new SqlDataAdapter(); DA1.SelectCommand = command; DataSet DS1 = new DataSet(); DA1.Fill(DS1); dtAlbums = DS1.Tables[0]; Cache.Insert("Albums", dtAlbums, new_dependency); } return dtAlbums; } Anyone have any luck with getting this to work with SPs? Thanks!

    Read the article

  • Send HTTP 404 from Application_Error

    - by Dmitriy Nagirnyak
    Hi, First of all, quickly what exactly I want to achieve: translate particular exception into the HTTP 404 so the ASP.NET can handle it further. I am handling exceptions in the ASP.NET (MVC2) this way: protected void Application_Error(object sender, EventArgs e) { var err = Server.GetLastError(); if (err == null) return; err = err.GetBaseException(); var noObject = err as ObjectNotFoundException; if (noObject != null) HandleObjectNotFound(); var handled = noObject != null; if (!handled) Logger.Fatal("Unhandled exception has occured in application.", err); } private void HandleObjectNotFound() { Server.ClearError(); Response.Clear(); // new HttpExcepton(404, "Not Found"); // Throw or not to throw? Response.StatusCode = 404; Response.StatusDescription = "Not Found"; Response.StatusDescription = "Not Found"; Response.Write("The whole HTML body explaining whata 404 is??"); } The problem is that I cannot configure default customErrors to work with it. When it is on then it never redirects to the page specified in customErrors: <error statusCode="404" redirect="404.html"/>. I also tried to raise new HttpExcepton(404, "Not Found") from the handler but then the response code is 200 which I don't understand why. So the questions are: What is the proper way of translating AnException into HTTP 404 response? How does customErrors section work when handling exceptions in Application_Error? Why throwing HttpException(404) renders (blank) page with success (200) status? Thanks, Dmitriy.

    Read the article

  • How to avoid an HttpException due to timeout

    - by Dan
    I'm working on a website powered by .NET asp/C# code. The clients require that sessions have a 25 minute timeout. However, sometimes the site is used, and a user stays connected for long periods of time (longer than 25 mins). Session_End is triggered: protected void Session_End(Object sender, EventArgs e) { Hashtable trackingInformaiton = (Hashtable)Application["trackingInformation"]; trackingInformaiton.Remove(Session["trackingID"]); } The user returns some time later, but when they interact with the website, they get an error, and we get this email notification: User: Unauthenticated User Error: System.Web.HttpException Description: Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request... The telling part of the stack trace is System.Web.UI.Control.AddedControl. Apparently, the server has thrown away the session data, and is sending new data, but the client is trying to deal with old data. Hence the error that "the control tree into which viewstate is being loaded [doesn't] match the control tree that was used to save the viewstate during the prevoius request." So here's the question. How can I force instruct the user's browser to redirect to a "you're logged out" screen when the connection times out? (Is it something I should add to the Session_End method?)

    Read the article

  • Dynamic controls not creating with RSS reader function

    - by TuxMeister
    Hello, I am working on a test project for an RSS reader. I am using Chilkat's module for .NET 3.5. What I am trying to do is this: For each item in the RSS feed, I want to dynamically create some controls (labels) that contain stuff like the title, the link and the publication date. The problem is that only the first control comes up "rssTitle", but not the rest and it's definitely not creating the rest, nor cycling through the RSS items. Any ideas where I'm wrong in my code? Imports Chilkat Public Class Form1 Dim rss As New Chilkat.Rss Dim success As Boolean Dim rssTitle As New Label Dim rssLink As New Label Dim rssPubDate As New Label Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click success = rss.DownloadRss("http://www.engadget.com/rss.xml") If success <> True Then MessageBox.Show(rss.LastErrorText) Exit Sub End If Dim rssChannel As Chilkat.Rss rssChannel = rss.GetChannel(0) If rssChannel Is Nothing Then MessageBox.Show("No channel found.") Exit Sub End If Dim numItems As Long numItems = rssChannel.NumItems Dim i As Long For i = 0 To numItems - 1 Dim rssItem As Chilkat.Rss rssItem = rssChannel.GetItem(i) Me.Controls.Add(rssTitle) With rssTitle .Name = "rssTitle" & Me.Controls.Count.ToString + 1 .Text = "Title: " & rssItem.GetString("title") .Left = 12 .Top = 12 End With Me.Controls.Add(rssLink) With rssLink .Name = "rssLink" & Me.Controls.Count.ToString + 1 .Text = "Link: " & rssItem.GetString("link") .Left = 12 .Top = 12 End With Me.Controls.Add(rssPubDate) With rssPubDate .Name = "rssPubDate" & Me.Controls.Count.ToString + 1 .Text = "Pub date: " & rssItem.GetString("pubDate") .Left = 12 .Top = 12 End With Next End Sub End Class I'm grateful for any help. Thanks!

    Read the article

  • Numeric Data Entry in WPF

    - by Matt Hamilton
    How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control?private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled = !isControl && !isNumeric && !isNumPadNumeric; }

    Read the article

  • COMException in System.WIndows.Forms.dll with Interactive Brokers TWS API

    - by Lirik
    Hi, I've been trying to run the sample project provided with the tutorial at stockbotprogramming http://www.stockbotprogramming.com/sharpcibtutorial1.php , but I keep getting a COMException every time I run the application. I have the TWS Client running and the sample VB projects provided with the API are able to connect just fine, but when I try to use the C# sample provided by the tutorial then I get the following exception: An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.Windows.Forms.dll Th exception happens when I try to add the TWS ActiveX control: namespace CSharpTutorial1 { public partial class Form1 : Form { private AxTWSLib.AxTws tws; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { tws = new AxTWSLib.AxTws(); tws.BeginInit(); tws.Enabled = true; tws.Location = new System.Drawing.Point(32, 664); tws.Name = "tws"; Controls.Add(tws); // <-- EXCEPTION HERE! tws.EndInit(); tws.connect("127.0.0.1", 7496, 0); String msg = "Connected to TWS server version " + tws.serverVersion + "at " + tws.TwsConnectionTime; MessageBox.Show(msg); } } } Does anybody know what could be causing this exception? Any ideas on how to fix it?

    Read the article

  • TypeError: coercing to Unicode: need string or buffer, User found

    - by Clemens
    hi, i have to crawl last.fm for users (university exercise). I'm new to python and get following error: Traceback (most recent call last): File "crawler.py", line 23, in <module> for f in user_.get_friends(limit='200'): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 2717, in get_friends for node in _collect_nodes(limit, self, "user.getFriends", False): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 3409, in _collect_nodes doc = sender._request(method_name, cacheable, params) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 969, in _request return _Request(self.network, method_name, params).execute(cacheable) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 721, in __init__ self.sign_it() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 727, in sign_it self.params['api_sig'] = self._get_signature() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 740, in _get_signature string += self.params[name] TypeError: coercing to Unicode: need string or buffer, User found i use the pylast lib for crawling. what i want to do: i want to get a users friends and the friends of the users friends. the error occurs, when i have a for loop in another for loop. here's the code: network = pylast.get_lastfm_network(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash) user = network.get_user("vidarnelson") friends = user.get_friends(limit='200') i = 1 for friend in friends: user_ = network.get_user(friend) print '#%d %s' % (i, friend) i = i + 1 for f in user_.get_friends(limit='200'): print f any advice? thanks in advance. regards!

    Read the article

  • Extremely slow MFMailComposeViewControllerDelegate

    - by Jeff B
    I have a bit of a strange problem. I am trying to send in-app email. I am also using Cocos2d. It works, so far as I get the mail window and I can send mail, but it is extremely slow. It seems to only accept touches every second or so. I checked the cpu usage, and it is quite low. I paused my director, so nothing else should be happening. Any ideas? I am pulling my hair out. I looked at some examples and did the following: Made my scene the mail delegate: @interface MyLayer : CCLayer <MFMailComposeViewControllerDelegate> { ... } And implemented the following function in the scenes: -(void) showEmailWindow: (id) sender { [[CCDirector sharedDirector] pause]; MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; [picker setSubject: @"My subject here"]; NSString *emailBody = @"<h1>Here is my email!</h1>"; [picker setMessageBody:emailBody isHTML:YES]; [myMail presentModalViewController:picker animated:NO]; [picker release]; } I also implemented the mailComposeController, to handle the callback.

    Read the article

  • WinForms Load Event / Static Initialization Strangeness

    - by Eric J.
    Background I'm troubleshooting an WinForms 2.0 program that's already been burned to CD for distribution to an internet-challenged target audience. Some users are experiencing a fatal error that I can reproduce locally. Reproducing the Error I get the fatal error when I log into my Vista box using a standard user that I just created, even if I run the program as administrator. I do not get the fatal error when I log in as local administrator. I'm not sure that being administrator is necessarily the trigger (since runas did not help). I have reproduced this half a dozen times under each account with consistent results. The faulty code Base.cs (base class for several user controls, only one of which is shown on first screen) private void BaseWindow_Load(object sender, EventArgs e) { // This message shown once in both cases MessageBox.Show("BaseWindow_Load for " + this.GetType().FullName); SkinManager.ApplySkin(this); } SkinManager.cs private static Skin skin = null; public static void ApplySkin(UserControl applyTo) { if (skin == null) { skin = new Skin(SkinsDirectory, "Default"); } } Skin.cs internal Skin(string skinPath, string skinName) { config = SkinConfig.Load(path); } SkinConfig.cs public static SkinConfig Load(string path) { // This message shown only once running as Admin but twice running as standard user System.Windows.Forms.MessageBox.Show("@1"); // !!! LOCK path HERE !!! } A user control loads on the first form, which triggers a call to SkinManager.ApplySkin, which checks if skin is null and, if so assigns it (without thread synchronization or recursion protection), which ultimately causes a file to be opened. When logged in as local admin, that sequence completes just fine. When logged in as my test standard user, ApplySkin is always called a second time while skin is still null, causing a second attempt to load, causing the file to be locked on the second attempt. The error handling is draconian at this point and the program terminates. The Question While this code can be easily fixed, I would like to understand why the error is happening only in some cases.

    Read the article

< Previous Page | 119 120 121 122 123 124 125 126 127 128 129 130  | Next Page >