Search Results

Search found 958 results on 39 pages for 'dispose'.

Page 18/39 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • User Control as container at design time

    - by Luca
    I'm designing a simple expander control. I've derived from UserControl, drawn inner controls, built, run; all ok. Since an inner Control is a Panel, I'd like to use it as container at design time. Indeed I've used the attributes: [Designer(typeof(ExpanderControlDesigner))] [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] Great I say. But it isn't... The result is that I can use it as container at design time but: The added controls go back the inner controls already embedded in the user control Even if I push to top a control added at design time, at runtime it is back again on controls embedded to the user control I cannot restrict the container area at design time into a Panel area What am I missing? Here is the code for completeness... why this snippet of code is not working? [Designer(typeof(ExpanderControlDesigner))] [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] public partial class ExpanderControl : UserControl { public ExpanderControl() { InitializeComponent(); .... [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] internal class ExpanderControlDesigner : ControlDesigner { private ExpanderControl MyControl; public override void Initialize(IComponent component) { base.Initialize(component); MyControl = (ExpanderControl)component; // Hook up events ISelectionService s = (ISelectionService)GetService(typeof(ISelectionService)); IComponentChangeService c = (IComponentChangeService)GetService(typeof(IComponentChangeService)); s.SelectionChanged += new EventHandler(OnSelectionChanged); c.ComponentRemoving += new ComponentEventHandler(OnComponentRemoving); } private void OnSelectionChanged(object sender, System.EventArgs e) { } private void OnComponentRemoving(object sender, ComponentEventArgs e) { } protected override void Dispose(bool disposing) { ISelectionService s = (ISelectionService)GetService(typeof(ISelectionService)); IComponentChangeService c = (IComponentChangeService)GetService(typeof(IComponentChangeService)); // Unhook events s.SelectionChanged -= new EventHandler(OnSelectionChanged); c.ComponentRemoving -= new ComponentEventHandler(OnComponentRemoving); base.Dispose(disposing); } public override System.ComponentModel.Design.DesignerVerbCollection Verbs { get { DesignerVerbCollection v = new DesignerVerbCollection(); v.Add(new DesignerVerb("&asd", new EventHandler(null))); return v; } } } I've found many resources (Interaction, designed, limited area), but nothing was usefull for being operative... Actually there is a trick, since System.Windows.Forms classes can be designed (as usual) and have a correct behavior at runtime (TabControl, for example).

    Read the article

  • ByRef vs ByVal generates errors!?

    - by serhio
    ByRef vs ByVal generates errors!? I had a method that used an Object Function Foo(ByRef bar as CustomObject) as Boolean this method generated errors, because some strange .NET Runtime things changed the bar object, causing its Dispose()al. A lot of time spent to understand the thing(where the ... object is changed), until somebody replaced ByRef by ByVal and object wasn't change anymore when passing to this method... Somebody could explain this, what happens?

    Read the article

  • Few doubts regarding Bitmaps , Images & `using` blocks

    - by imageWorker
    I caught up in this problem. http://stackoverflow.com/questions/2559826/garbage-collector-not-doing-its-job-memory-consumption-1-5gb-outofmemory-exc I feel that there is something wrong in my understanding. Please clarify these things. Destructor & IDisposable.Dispose are two methods for freeing resources that are not not under the control of .NET. Which means, everything except memory. right? using blocks are just better way of calling IDisposable.Dispose() method of an object. This is the main code I'm referring to. class someclass { static someMethod(Bitmap img) { Bitmap bmp = new Bitmap(img); //statement1 // some code here and return } } here is class I'm using for testing: class someotherClass { public static voide Main() { foreach (string imagePath in imagePathsArray) { using (Bitmap img1 = new Bitmap(imagePath)) { someclass.someMethod(img1); // does some more processing on `img1` } } } } Is there any memory leak with statement1? Question1: If each image size is say 10MB. Then does this bmp object occupy atleast 10MB? What I mean is, will it make completely new copy of entire image? or just refer to it? Question2:should I or should I not put the statement1 in using block? My Argument: We should not. Because using is not for freeing memory but for freeing the resources (file handle in this case). If I use it in using block. It closes file handle here encapsulated by this bmp object. It means we are also closing filehandle for the caller's img1 object. Which is not correct? As of the memory leak. No there is no scope of memory leak here. Because reference bmp is destroyed when this method is returned. Which leaves memory it refered without any pointer. So, its garbage collected. Am I right? Edit: class someclass { static Bitmap someMethod(Bitmap img) { Bitmap bmp = new Bitmap(img); //can I use `using` block on this enclosing `return bmp`; ??? // do some processing on bmp here return bmp; } }

    Read the article

  • How would I define "GetDataFromNumber" so that my class contains a definition?

    - by JB
    My code gets an error saying: 'Eagle_Eye_Class_Finder.GetSchedule' does not contain a definition for 'GetDataFromNumber' and no extension method 'GetDataFromNumber'. using System; using System.IO; using System.Data; using System.Text; using System.Drawing; using System.Data.OleDb; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using System.Drawing.Printing; using System.Collections.Generic; namespace Eagle_Eye_Class_Finder { /// This form is the entry form, it is the first form the user will see when the app is run. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button button2; private System.Windows.Forms.DateTimePicker dateTimePicker1; private IContainer components; private Timer timer1; private BindingSource form1BindingSource; public static Form Mainform = null; // creates new instance of second form YOURCLASSSCHEDULE SecondForm = new YOURCLASSSCHEDULE(); public Form1() { InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// Clean up any resources being used. protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.textBox1 = new System.Windows.Forms.TextBox(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.button2 = new System.Windows.Forms.Button(); this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.form1BindingSource = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).BeginInit(); this.SuspendLayout(); // // textBox1 // this.textBox1.BackColor = System.Drawing.SystemColors.ActiveCaption; this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.form1BindingSource, "Text", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "900456317")); this.textBox1.Location = new System.Drawing.Point(328, 280); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(208, 20); this.textBox1.TabIndex = 2; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(258, 410); this.progressBar1.MarqueeAnimationSpeed = 10; this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(344, 8); this.progressBar1.TabIndex = 3; this.progressBar1.Click += new System.EventHandler(this.progressBar1_Click); // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.SystemColors.ControlLightLight; this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(680, 400); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(120, 112); this.pictureBox1.TabIndex = 4; this.pictureBox1.TabStop = false; this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Mistral", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Image = ((System.Drawing.Image)(resources.GetObject("button2.Image"))); this.button2.Location = new System.Drawing.Point(699, 442); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(78, 28); this.button2.TabIndex = 5; this.button2.Text = "OK"; this.button2.Click += new System.EventHandler(this.button2_Click); // // dateTimePicker1 // this.dateTimePicker1.Location = new System.Drawing.Point(336, 104); this.dateTimePicker1.Name = "dateTimePicker1"; this.dateTimePicker1.Size = new System.Drawing.Size(200, 20); this.dateTimePicker1.TabIndex = 6; this.dateTimePicker1.ValueChanged += new System.EventHandler(this.dateTimePicker1_ValueChanged); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // form1BindingSource // this.form1BindingSource.DataSource = typeof(Eagle_Eye_Class_Finder.Form1); // // Form1 // this.AcceptButton = this.button2; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(856, 556); this.Controls.Add(this.dateTimePicker1); this.Controls.Add(this.button2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.progressBar1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Eagle Eye Class Finder"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// The main entry point for the application. [STAThread] static void Main() { Application.Run(new Form1()); } public void Form1_Load(object sender, System.EventArgs e) { } public void textBox1_TextChanged(object sender, System.EventArgs e) { //allows only numbers to be entered in textbox string Str = textBox1.Text.Trim(); double Num; bool isNum = double.TryParse(Str, out Num); if (isNum) Console.ReadLine(); else MessageBox.Show("Enter A Valid ID Number!"); } public void button2_Click(object sender, System.EventArgs e) { string text = textBox1.Text; Mainform = this; this.Hide(); GetSchedule myScheduleFinder = new GetSchedule(); string result = myScheduleFinder.GetDataFromNumber(text);<<<-----MY PROBLEM if (!string.IsNullOrEmpty(result)) { MessageBox.Show(result); } else { MessageBox.Show("Enter A Valid ID Number!"); } } public void dateTimePicker1_ValueChanged(object sender, System.EventArgs e) { } public void pictureBox1_Click(object sender, System.EventArgs e) { } public void progressBar1_Click(object sender, EventArgs e) { //this.progressBar1 = new System.progressBar1(); //progressBar1.Maximum = 200; //progressBar1.Minimum = 0; //progressBar1.Step = 20; } private void timer1_Tick(object sender, EventArgs e) { //if (progressBar1.Value >= 200 ) //{ //progressBar1.Value = 0; //} //return; //} //progressBar1.Value != 20; } } }

    Read the article

  • NHibernate + Sql Compact + IoC - Connection Managment

    - by Michael
    When working with NHibernate and Sql Compact in a Windows Form application I am wondering what is the best practice for managing connections. With SQL CE I have read that you should keep your connection open vs closing it as one would typically do with standard SQL. If that is the case and your using a IoC, would you make your repositories lifetime be singletons so they exist forever or dispose of them after you perform a "Unit of Work". Also is there a way to determine the number of connections open to Sql CE?

    Read the article

  • How to verify StructureMap is disposing of objects properly

    - by Kevin Pang
    I'm currently using StructureMap to inject instances of NHibernate ISessions using the following code: ObjectFactory.Initialize(x => { x.ForRequestedType<ISession>() .CacheBy(InstanceScope.PerRequest) .TheDefault.Is.ConstructedBy(y => NHibernateSessionManager.Instance.GetSession()); }); I'm assuming that the CacheBy(InstanceScope.PerRequest) will properly dispose of the ISession it creates, but I'd like to make sure. What's the easiest way to test this?

    Read the article

  • not use "using" statement for TransactionScope

    - by hotyi
    i always using the following format to use transactionscope. using(TransactionScope scope = new TransactionScope()){ .... } sometimes i want to wrap the transactionscope to a new class, for example DbContext class, i want to using the statement like dbContext.Begin(); ... dbContext.Submit(); it seems the transactioncope class need use "using"statement to do dispose, i want to know if there is anyway not use "using".

    Read the article

  • Is it possible to pass a structure of delegates from managed to native?

    - by Veiva
    I am writing a wrapper for the game programming library "Allegro" and its less stable 4.9 branch. Now, I have done good insofar, except for when it comes to wrapping a structure of function pointers. Basically, I can't change the original code, despite having access to it, because that would require me to fork it in some manner. I need to know how I can somehow pass a structure of delegates from managed to native without causing an AccessViolationException that has occurred so far. Now, for the code. Here is the Allegro definition of the structure: typedef struct ALLEGRO_FILE_INTERFACE { AL_METHOD(ALLEGRO_FILE*, fi_fopen, (const char *path, const char *mode)); AL_METHOD(void, fi_fclose, (ALLEGRO_FILE *handle)); AL_METHOD(size_t, fi_fread, (ALLEGRO_FILE *f, void *ptr, size_t size)); AL_METHOD(size_t, fi_fwrite, (ALLEGRO_FILE *f, const void *ptr, size_t size)); AL_METHOD(bool, fi_fflush, (ALLEGRO_FILE *f)); AL_METHOD(int64_t, fi_ftell, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_fseek, (ALLEGRO_FILE *f, int64_t offset, int whence)); AL_METHOD(bool, fi_feof, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_ferror, (ALLEGRO_FILE *f)); AL_METHOD(int, fi_fungetc, (ALLEGRO_FILE *f, int c)); AL_METHOD(off_t, fi_fsize, (ALLEGRO_FILE *f)); } ALLEGRO_FILE_INTERFACE; My simple attempt at wrapping it: public delegate IntPtr AllegroInternalOpenFileDelegate(string path, string mode); public delegate void AllegroInternalCloseFileDelegate(IntPtr file); public delegate int AllegroInternalReadFileDelegate(IntPtr file, IntPtr data, int size); public delegate int AllegroInternalWriteFileDelegate(IntPtr file, IntPtr data, int size); public delegate bool AllegroInternalFlushFileDelegate(IntPtr file); public delegate long AllegroInternalTellFileDelegate(IntPtr file); public delegate bool AllegroInternalSeekFileDelegate(IntPtr file, long offset, int where); public delegate bool AllegroInternalIsEndOfFileDelegate(IntPtr file); public delegate bool AllegroInternalIsErrorFileDelegate(IntPtr file); public delegate int AllegroInternalUngetCharFileDelegate(IntPtr file, int c); public delegate long AllegroInternalFileSizeDelegate(IntPtr file); [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct AllegroInternalFileInterface { [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalOpenFileDelegate fi_fopen; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalCloseFileDelegate fi_fclose; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalReadFileDelegate fi_fread; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalWriteFileDelegate fi_fwrite; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFlushFileDelegate fi_fflush; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalTellFileDelegate fi_ftell; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalSeekFileDelegate fi_fseek; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsEndOfFileDelegate fi_feof; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsErrorFileDelegate fi_ferror; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalUngetCharFileDelegate fi_fungetc; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFileSizeDelegate fi_fsize; } I have a simple auxiliary wrapper that turns an ALLEGRO_FILE_INTERFACE into an ALLEGRO_FILE, like so: #define ALLEGRO_NO_MAGIC_MAIN #include <allegro5/allegro5.h> #include <stdlib.h> #include <string.h> #include <assert.h> __declspec(dllexport) ALLEGRO_FILE * al_aux_create_file(ALLEGRO_FILE_INTERFACE * fi) { ALLEGRO_FILE * file; assert(fi && "`fi' null"); file = (ALLEGRO_FILE *)malloc(sizeof(ALLEGRO_FILE)); if (!file) return NULL; file->vtable = (ALLEGRO_FILE_INTERFACE *)malloc(sizeof(ALLEGRO_FILE_INTERFACE)); if (!(file->vtable)) { free(file); return NULL; } memcpy(file->vtable, fi, sizeof(ALLEGRO_FILE_INTERFACE)); return file; } __declspec(dllexport) void al_aux_destroy_file(ALLEGRO_FILE * f) { assert(f && "`f' null"); assert(f->vtable && "`f->vtable' null"); free(f->vtable); free(f); } Lastly, I have a class that accepts a Stream and provides the proper methods to interact with the stream. Just to make sure, here it is: /// <summary> /// A semi-opaque data type that allows one to load fonts, etc from a stream. /// </summary> public class AllegroFile : AllegroResource, IDisposable { AllegroInternalFileInterface fileInterface; Stream fileStream; /// <summary> /// Gets the file interface. /// </summary> internal AllegroInternalFileInterface FileInterface { get { return fileInterface; } } /// <summary> /// Constructs an Allegro file from the stream provided. /// </summary> /// <param name="stream">The stream to use.</param> public AllegroFile(Stream stream) { fileStream = stream; fileInterface = new AllegroInternalFileInterface(); fileInterface.fi_fopen = Open; fileInterface.fi_fclose = Close; fileInterface.fi_fread = Read; fileInterface.fi_fwrite = Write; fileInterface.fi_fflush = Flush; fileInterface.fi_ftell = GetPosition; fileInterface.fi_fseek = Seek; fileInterface.fi_feof = GetIsEndOfFile; fileInterface.fi_ferror = GetIsError; fileInterface.fi_fungetc = UngetCharacter; fileInterface.fi_fsize = GetLength; Resource = AllegroFunctions.al_aux_create_file(ref fileInterface); if (!IsValid) throw new AllegroException("Unable to create file"); } /// <summary> /// Disposes of all resources. /// </summary> ~AllegroFile() { Dispose(); } /// <summary> /// Disposes of all resources used. /// </summary> public void Dispose() { if (IsValid) { Resource = IntPtr.Zero; // Should call AllegroFunctions.al_aux_destroy_file fileStream.Dispose(); } } IntPtr Open(string path, string mode) { return IntPtr.Zero; } void Close(IntPtr file) { fileStream.Close(); } int Read(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; int read = fileStream.Read(d, 0, size); Marshal.Copy(d, 0, data, size); return read; } int Write(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; Marshal.Copy(data, d, 0, size); fileStream.Write(d, 0, size); return size; } bool Flush(IntPtr file) { fileStream.Flush(); return true; } long GetPosition(IntPtr file) { return fileStream.Position; } bool Seek(IntPtr file, long offset, int whence) { SeekOrigin origin = SeekOrigin.Begin; if (whence == 1) origin = SeekOrigin.Current; else if (whence == 2) origin = SeekOrigin.End; fileStream.Seek(offset, origin); return true; } bool GetIsEndOfFile(IntPtr file) { return fileStream.Position == fileStream.Length; } bool GetIsError(IntPtr file) { return false; } int UngetCharacter(IntPtr file, int character) { return -1; } long GetLength(IntPtr file) { return fileStream.Length; } } Now, when I do something like this: AllegroFile file = new AllegroFile(new FileStream("Test.bmp", FileMode.Create, FileAccess.ReadWrite)); bitmap.SaveToFile(file, ".bmp"); ...I get an AccessViolationException. I think I understand why (the garbage collector can relocate structs and classes whenever), but I'd think that the method stub that is created by the framework would take this into consideration and route the calls to the valid classes. However, it seems obviously so that I'm wrong. So basically, is there any way I can successfully wrap that structure? (And I'm sorry for all the code! Hope it's not too much...)

    Read the article

  • How to close a java swing application from the code

    - by hstoerr
    What is the proper way to terminate a Swing application from the code, and what are the pitfalls? I'd tried to close my application automatically after a timer fires. But just calling dispose() on the JFrame didn't do the trick - the window vanished but the application did not terminate. However when closing the window with the close button, the application does terminate. What should I do?

    Read the article

  • Equivalent of System.Windows.Forms.Cursor in Web Application

    - by Vishwa
    Hi I have a code in windows application now i am trying to implement in web Application but it is showimg that it ths no cursor class (System.Windows.Forms.Cursor )so..wat is the equivalent in web application. Here is my code private void btnGo_Click(System.Object sender, System.EventArgs e) { this.Cursor = Cursors.WaitCursor; Application.DoEvents(); // Load the images. Bitmap bm1 = (Bitmap) (Image.FromFile(txtFile1.Text)); Bitmap bm2 = (Bitmap) (Image.FromFile(txtFile2.Text)); // Make a difference image. int wid = Math.Min(bm1.Width, bm2.Width); int hgt = Math.Min(bm1.Height, bm2.Height); Bitmap bm3 = new Bitmap(wid, hgt); // Create the difference image. bool are_identical = true; int r1; int g1; int b1; int r2; int g2; int b2; int r3; int g3; int b3; Color eq_color = Color.White; Color ne_color = Color.Transparent; for (int x = 0; x <= wid - 1; x++) { for (int y = 0; y <= hgt - 1; y++) { if (bm1.GetPixel(x, y).Equals(bm2.GetPixel(x, y))) { bm3.SetPixel(x, y, eq_color); } else { bm1.SetPixel(x, y, ne_color); are_identical = false; } } } // Display the result. picResult.Image = bm1; Bitmap Logo = new Bitmap(picResult.Image); Logo.MakeTransparent(Logo.GetPixel(1, 1)); picResult.Image = (Image)Logo; this.Cursor = Cursors.Default; if ((bm1.Width != bm2.Width) || (bm1.Height != bm2.Height)) { are_identical = false; } if (are_identical) { MessageBox.Show("The images are identical"); } else { MessageBox.Show("The images are different"); } //bm1.Dispose() // bm2.Dispose() }

    Read the article

  • delphi vs c# post returns different strings - utf problem?

    - by argh
    I'm posting two forms - one in c# and one in delphi. But the result string seems to be different: c# returns: ¤@@1@@@@1@@@@1@@xsm˱Â0Ð... delphi returns: #$1E'@@1@@@@1@@@@1@@x'#$009C... and sice both are compressed streams I'm getting errors while trying to decompress it... The C# is 'correct' - ie. extracts. I'm not an expert on delphi - I just need to convert some piece of code from c# to delphi. c# code: string GetData(Hashtable aParam, string ServerURL) { string Result = ""; WebRequest Request = HttpWebRequest.Create(ServerURL); Request.Method = "POST"; Request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; UTF8Encoding encUTF8 = new System.Text.UTF8Encoding(false); StreamWriter writer = new StreamWriter(Request.GetRequestStream(), encUTF8); foreach (DictionaryEntry element in aParam) { writer.Write(element.Key + "=" + element.Value + "&"); } writer.Close(); writer.Dispose(); WebResponse Response = Request.GetResponse(); StreamReader Reader = new StreamReader(Response.GetResponseStream(), System.Text.Encoding.Default); Result = Reader.ReadToEnd(); Reader.Close(); Response.Close(); Reader.Dispose(); return Result; } delphi code: function GetData(aParam:TStringList; ServerURL:string):string; var req: TIdHTTP; res: string; begin req := TIdHTTP.Create(); with req do begin Request.ContentType := 'application/x-www-form-urlencoded; charset=UTF-8'; Request.Method := 'POST'; Request.CharSet := 'utf-8'; Request.AcceptCharSet := 'utf-8'; res := Post(ServerURL, aParam); end; Result := res; req.Free; end; -edit- I'm using delphi 2010

    Read the article

  • Why does GC not clear the Dialog references?

    - by Pavel
    I have a dialog. Every time I create it and then dispose, it stays in memory. It seems to be a memory leak somewhere, but I can't figure it out. Do you have any ideas? See the screenshot of heap dump for more information. Thanks in advance. http://img441.imageshack.us/img441/5764/leak.png

    Read the article

  • .NET datetime issue with SQL stored procedure

    - by DanO
    I am getting the below error when executing my application on a Windows XP machine with .NET 2.0 installed. On my computer Windows 7 .NET 2.0 - 3.5 I am not having any issues. The target SQL server version is 2005. This error started occurring when I added the datetime to the stored procedure. I have been reading alot about using .NET datetime with SQL datetime and I still have not figured this out. If someone can point me in the right direction I would appreciate it. Here is the where I believe the error is coming from. private static void InsertRecon(string computerName, int EncryptState, TimeSpan FindTime, Int64 EncryptSize, DateTime timeWritten) { SqlConnection DBC = new SqlConnection("server=server;UID=InventoryServer;Password=pass;database=Inventory;connection timeout=30"); SqlCommand CMD = new SqlCommand(); try { CMD.Connection = DBC; CMD.CommandType = CommandType.StoredProcedure; CMD.CommandText = "InsertReconData"; CMD.Parameters.Add("@CNAME", SqlDbType.NVarChar); CMD.Parameters.Add("@ENCRYPTEXIST", SqlDbType.Int); CMD.Parameters.Add("@RUNTIME", SqlDbType.Time); CMD.Parameters.Add("@ENCRYPTSIZE", SqlDbType.BigInt); CMD.Parameters.Add("@TIMEWRITTEN", SqlDbType.DateTime); CMD.Parameters["@CNAME"].Value = computerName; CMD.Parameters["@ENCRYPTEXIST"].Value = EncryptState; CMD.Parameters["@RUNTIME"].Value = FindTime; CMD.Parameters["@ENCRYPTSIZE"].Value = EncryptSize; CMD.Parameters["@TIMEWRITTEN"].Value = timeWritten; DBC.Open(); CMD.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException e) { PostMessage(e.Message); } finally { DBC.Close(); CMD.Dispose(); DBC.Dispose(); } } Unhandled Exception: System.ArgumentOutOfRangeException: The SqlDbType enumeration value, 32, is invalid. Parameter name: SqlDbType at System.Data.SqlClient.MetaType.GetMetaTypeFromSqlDbType(SqlDbType target) at System.Data.SqlClient.SqlParameter.set_SqlDbType(SqlDbType value) at System.Data.SqlClient.SqlParameter..ctor(String parameterName, SqlDbType dbType) at System.Data.SqlClient.SqlParameterCollection.Add(String parameterName, SqlDbType sqlDbType) at ReconHelper.getFilesInfo.InsertRecon(String computerName, Int32 EncryptState, TimeSpan FindTime, Int64 EncryptSize, DateTime timeWritten) at ReconHelper.getFilesInfo.Main(String[] args)

    Read the article

  • User Control as container

    - by Luca
    I'm designing a simple expander control. I've derived from UserControl, drawn inner controls, built, run; all ok. Since an inner Control is a Panel, I'd like to use it as container at design time. Indeed I've used the attributes: [Designer(typeof(ExpanderControlDesigner))] [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] Great I say. But it isn't... The result is that I can use it as container at design time but: The added controls go back the inner controls already embedded in the user control Even if I push to top a control added at design time, at runtime it is back again on controls embedded to the user control I cannot restrict the container area at design time into a Panel area What am I missing? Here is the code for completeness... why this snippet of code is not working? [Designer(typeof(ExpanderControlDesigner))] [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] public partial class ExpanderControl : UserControl { public ExpanderControl() { InitializeComponent(); .... [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] internal class ExpanderControlDesigner : ControlDesigner { private ExpanderControl MyControl; public override void Initialize(IComponent component) { base.Initialize(component); MyControl = (ExpanderControl)component; // Hook up events ISelectionService s = (ISelectionService)GetService(typeof(ISelectionService)); IComponentChangeService c = (IComponentChangeService)GetService(typeof(IComponentChangeService)); s.SelectionChanged += new EventHandler(OnSelectionChanged); c.ComponentRemoving += new ComponentEventHandler(OnComponentRemoving); } private void OnSelectionChanged(object sender, System.EventArgs e) { } private void OnComponentRemoving(object sender, ComponentEventArgs e) { } protected override void Dispose(bool disposing) { ISelectionService s = (ISelectionService)GetService(typeof(ISelectionService)); IComponentChangeService c = (IComponentChangeService)GetService(typeof(IComponentChangeService)); // Unhook events s.SelectionChanged -= new EventHandler(OnSelectionChanged); c.ComponentRemoving -= new ComponentEventHandler(OnComponentRemoving); base.Dispose(disposing); } public override System.ComponentModel.Design.DesignerVerbCollection Verbs { get { DesignerVerbCollection v = new DesignerVerbCollection(); v.Add(new DesignerVerb("&asd", new EventHandler(null))); return v; } } } I've found many resources (Interaction, designed, limited area), but nothing was usefull for being operative...

    Read the article

  • TimeOuts with HttpWebRequest when running Selenium concurrently in .NET

    - by domsom
    I have a download worker that uses ThreadPool-threads to download files. After enhancing these to apply some Selenium tests to the downloaded files, I am constantly experiencing TimeOut-exceptions with the file downloaders and delays running the Selenium tests. More precisely: When the program starts, the download threads start downloading and a couple of pages are seamlessly processed via Selenium Shortly after, the first download threads start throwing TimeOut exceptions from HttpWebRequest. At the same time, commands stop flowing to Selenium (as observed in the SeleniumRC log), but the thread running Selenium is not getting any exception This situation holds as long as there are entries in the download list: new download threads are being started and terminate after receiving TimeOuts (without trying to lock Selenium) As soon as no more download threads are being started, Selenium starts receiving commands again and the threads waiting for the lock are processed sequentially as designed Now here's the download code: HttpWebRequest request = null; WebResponse response = null; Stream stream = null; StreamReader sr = null; try { request = (HttpWebRequest) WebRequest.Create(uri); request.ServicePoint.ConnectionLimit = MAX_CONNECTIONS_PER_HOST; response = request.GetResponse(); stream = response.GetResponseStream(); // Read the stream... } finally { if (request != null) request.Abort(); if (response != null) response.Close(); if (stream != null) { stream.Close(); stream.Dispose(); } if (sr != null) { sr.Close(); sr.Dispose(); } } And this is how Selenium is used afterwards in the same thread: lock(SeleniumLock) { selenium.Open(url); // Run some Selenium commands, but no selenium.stop() } Where selenium is a static variable that is initialized in the static constructor of the class (via selenium.start()). I assume I am running into the CLR connection limit, so I added these lines during initalization: ThreadPool.GetMaxThreads (out maxWorkerThreads, out maxCompletionPortThreads); HttpUtility.MAX_CONNECTIONS_PER_HOST = maxWorkerThreads; System.Net.ServicePointManager.DefaultConnectionLimit = maxWorkerThreads + 1; The + 1 is for the connection to the SeleniumRC, due to my guess that the Selenium client code also uses HttpWebRequest. It seems like I'm still running into some kind of deadlock - although the threads waiting for the Selenium lock do not hold any resources. Any ideas on how to get this working?

    Read the article

  • Id property not populated

    - by fingers
    I have an identity mapping like so: Id(x => x.GuidId).Column("GuidId") .GeneratedBy.GuidComb().UnsavedValue(Guid.Empty); When I retrieve an object from the database, the GuidId property of my object is Guid.Empty, not the actual Guid (the property in the class is of type System.Guid). However, all of the other properties in the object are populated just fine. The database field's data type (SQL Server 2005) is uniqueidentifier, and marked as RowGuid. The application that is connecting to the database is a VB.NET Web Site project (not a "Web Application" or "MVC Web Application" - just a regular "Web Site" project). I open the NHibernate session through a custom HttpModule. Here is the HttpModule: public class NHibernateModule : System.Web.IHttpModule { public static ISessionFactory SessionFactory; public static ISession Session; private static FluentConfiguration Configuration; static NHibernateModule() { if (Configuration == null) { string connectionString = cfg.ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString; Configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(cs => cs.Is(connectionString))) .ExposeConfiguration(c => c.Properties.Add("current_session_context_class", "web")) .Mappings(x => x.FluentMappings.AddFromAssemblyOf<LeadMap>().ExportTo("C:\\Mappings")); } SessionFactory = Configuration.BuildSessionFactory(); } public void Init(HttpApplication context) { context.BeginRequest += delegate { Session = SessionFactory.OpenSession(); CurrentSessionContext.Bind(Session); }; context.EndRequest += delegate { CurrentSessionContext.Unbind(SessionFactory); }; } public void Dispose() { Session.Dispose(); } } The strangest part of all, is that from my unit test project, the GuidId property is returned as I would expect. I even rigged it to go for the exact row in the exact database as the web site was hitting. The only differences I can think of between the two projects are The unit test project is in C# Something with the way the session is managed between the HttpModule and my unit tests The configuration for the unit tests is as follows: Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(cs => cs.Is(connectionString))) .Mappings(x => x.FluentMappings.AddFromAssemblyOf<LeadDetailMap>()); I am fresh out of ideas. Any help would be greatly appreciated. Thanks

    Read the article

  • Best practices for displaying large number of images as thumbnails in c#

    - by andySF
    I got to a point where it's very difficult to get answers by debugging and tracing object, so i need some help. What I'm trying to do: A history form for my screen capture pet project. The history must list all images as thumbnails (ex: picasa). What I've done: I created a HistoryItem:UserControl. This history item has a few buttons, a check box, a label and a picture box. The buttons are for delete/edit/copy image. The check box is used for selecting one or more images and the label is for some info text. The picture box is getting the image from a public property that is a path and a method creates a proportional thumbnail to display it when the control has been loaded. This user control has two public events. One for deleting the image and one for bubbling the events for mouse enter and mouse leave trough all controls. For this I use EventBroadcastProvider. The bubbling is useful because wherever I move the mouse over the control, the buttons appear. The dispose method has been extended and I manually remove the events. All images are loaded by looping a xml file that contains the path of all images. For each image in this XML I create a new HitoryItem that is added (after a little coding to sort and limit the amount of images loaded) to a flow layout panel. The problem: When I lunch the history form, and the flow layout panel is populated with my HistoryItem custom control, my memory usage increases drastically.From 14Mb to around 100MB with 100 images loaded. By closing the history form and disposing whatever I could dispose and even trying to call GC.Collect() the memory increase remain. I search for any object that could not be disposed properly like an image or event but wherever I used them they are disposed. The problem seams to be from multiple sources. One is that the events for bubbling are not disposing properly, and the other is from the picture box itself. All of this i could see by commenting all the code to a limited version when only the custom control without any image processing and even events is loaded. Without the events the memory consumption is reduced by axiomatically 20%. So my real question is if this logic, flow layout panels and custom controls with picture boxes, is the best solution for displaying large amounts of images as thumbnails. Thank you!

    Read the article

  • Invalid Cross-Thread Operations from BackgroundWorker2_RunWorkerCompleted in C#

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

    Read the article

  • Why do I get a WCF timeout even though my service call and callback are successful?

    - by KallDrexx
    I'm playing around with hooking up an in-game console to a WCF interface, so an external application can send console commands and receive console output. To accomplish this I created the following service contracts: public interface IConsoleNetworkCallbacks { [OperationContract(IsOneWay = true)] void NewOutput(IEnumerable<string> text, string category); } [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IConsoleNetworkCallbacks))] public interface IConsoleInterface { [OperationContract] void ProcessInput(string input); [OperationContract] void ChangeCategory(string category); } On the server I implemented it with: public class ConsoleNetworkInterface : IConsoleInterface, IDisposable { public ConsoleNetworkInterface() { ConsoleManager.Instance.RegisterOutputUpdateHandler(OutputHandler); } public void Dispose() { ConsoleManager.Instance.UnregisterOutputHandler(OutputHandler); } public void ProcessInput(string input) { ConsoleManager.Instance.ProcessInput(input); } public void ChangeCategory(string category) { ConsoleManager.Instance.UnregisterOutputHandler(OutputHandler); ConsoleManager.Instance.RegisterOutputUpdateHandler(OutputHandler, category); } protected void OutputHandler(IEnumerable<string> text, string category) { var callbacks = OperationContext.Current.GetCallbackChannel<IConsoleNetworkCallbacks>(); callbacks.NewOutput(text, category); } } On the client I implemented the callback with: public class Callbacks : IConsoleNetworkCallbacks { public void NewOutput(IEnumerable<string> text, string category) { MessageBox.Show(string.Format("{0} lines received for '{1}' category", text.Count(), category)); } } Finally, I establish the service host with the following class: public class ConsoleServiceHost : IDisposable { protected ServiceHost _host; public ConsoleServiceHost() { _host = new ServiceHost(typeof(ConsoleNetworkInterface), new Uri[] { new Uri("net.pipe://localhost") }); _host.AddServiceEndpoint(typeof(IConsoleInterface), new NetNamedPipeBinding(), "FrbConsolePipe"); _host.Open(); } public void Dispose() { _host.Close(); } } and use the following code on my client to establish the connection: protected Callbacks _callbacks; protected IConsoleInterface _proxy; protected void ConnectToConsoleServer() { _callbacks = new Callbacks(); var factory = new DuplexChannelFactory<IConsoleInterface>(_callbacks, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/FrbConsolePipe")); _proxy = factory.CreateChannel(); _proxy.ProcessInput("Connected"); } So what happens is that my ConnectToConsoleServer() is called and then it gets all the way to _proxy.ProcessInput("Connected");. In my game (on the server) I immediately see the output caused by the ProcessInput call, but the client is still stalled on the _proxy.ProcessInput() call. After a minute my client gets a JIT TimeoutException however at the same time my MessageBox message appears. So obviously not only is my command being sent immediately, my callback is being correctly called. So why am I getting a timeout exception? Note: Even removing the MessageBox call, I still have this issue, so it's not an issue of the GUI blocking the callback response.

    Read the article

  • Equivalent of System.Windows.Forms.Cursor in Web Application(Asp.Net)

    - by Vishwa
    Hi I have a code in windows application now i am trying to implement in web Application but it is showimg that it ths no cursor class (System.Windows.Forms.Cursor )so..wat is the equivalent in web application. Here is my code private void btnGo_Click(System.Object sender, System.EventArgs e) { this.Cursor = Cursors.WaitCursor; Application.DoEvents(); // Load the images. Bitmap bm1 = (Bitmap) (Image.FromFile(txtFile1.Text)); Bitmap bm2 = (Bitmap) (Image.FromFile(txtFile2.Text)); // Make a difference image. int wid = Math.Min(bm1.Width, bm2.Width); int hgt = Math.Min(bm1.Height, bm2.Height); Bitmap bm3 = new Bitmap(wid, hgt); // Create the difference image. bool are_identical = true; int r1; int g1; int b1; int r2; int g2; int b2; int r3; int g3; int b3; Color eq_color = Color.White; Color ne_color = Color.Transparent; for (int x = 0; x <= wid - 1; x++) { for (int y = 0; y <= hgt - 1; y++) { if (bm1.GetPixel(x, y).Equals(bm2.GetPixel(x, y))) { bm3.SetPixel(x, y, eq_color); } else { bm1.SetPixel(x, y, ne_color); are_identical = false; } } } // Display the result. picResult.Image = bm1; Bitmap Logo = new Bitmap(picResult.Image); Logo.MakeTransparent(Logo.GetPixel(1, 1)); picResult.Image = (Image)Logo; this.Cursor = Cursors.Default; if ((bm1.Width != bm2.Width) || (bm1.Height != bm2.Height)) { are_identical = false; } if (are_identical) { MessageBox.Show("The images are identical"); } else { MessageBox.Show("The images are different"); } //bm1.Dispose() // bm2.Dispose() }

    Read the article

  • Variable scope and the 'using' statement in .NET

    - by pete the pagan-gerbil
    If a variable is at class level (ie, private MyDataAccessClass _dataAccess;, can it be used as part of a using statement within the methods of that class to dispose of it correctly? Is it wise to use this method, or is it better to always declare a new variable with a using statement (ie, using (MyDataAccessClass dataAccess = new MyDataAccessClass()) instead of using (_dataAccess = new MyDataAccessClass()))?

    Read the article

  • Automatically unsubscribe an event

    - by Cat
    Is it possible to do something like this in C#? Probably with Expressions. private void RegisterEvent(EventHandler handler, Action<EventArgs> action) { handler += action; m_toUnsubscribe.Add(handler, action); } ... in Dispose() { foreach(var pair in m_toUnsubscribe) { pair.handler -= pair.action; } }

    Read the article

  • DataGridView cells not editable when using an outside thread call

    - by joslinm
    Hi, I'm not able to edit my datagridview cells when a number of identical calls takes place on another thread. Here's the situation: Dataset table is created in the main window The program receives in files and processes them on a background thread in class TorrentBuilder : BackgroundWorker creating an array objects of another class Torrent My program receives those objects from the BW result and adds them into the dataset The above happens either on my main window thread or in another thread: I have a separate thread watching a folder for files to come in, and when they do come in, they proceed to call TorrentBuilder.RunWorkerAsynch() from that thread, receive the result, and call an outside class that adds the Torrent objects into the table. When the files are received by the latter thread, the datagridview isn't editable. All of the values come up properly into the datagridview, but when I click on a cell to edit it: I can write letters and everything, but when I click out of it, it immediately reverts back to its original value. If I restart the program, I can edit the same cells just fine. If the values are freshly added from the main window thread, I can edit the cells just fine. The outside thread is called from my main window thread, and sits there in the background. I don't believe it to be ReadOnly because I would have gotten an exception. Here's some code: From my main window class: private void dataGridView_DragDrop(object sender, DragEventArgs e) { ArrayList al = new ArrayList(); string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string file in files) { string extension = Path.GetExtension(file); if (Path.GetExtension(file).Equals(".zip") || Path.GetExtension(file).Equals(".rar")) { foreach (string unzipped in dh.UnzipFile(file)) al.Add(unzipped); } else if (Path.GetExtension(file).Equals(".torrent")) { al.Add(file); } } dataGridViewProgressBar.Visible = true; tb.RunWorkerCompleted += new RunWorkerCompletedEventHandler(tb_DragDropCompleted); tb.ProgressChanged += new ProgressChangedEventHandler(tb_DragDropProgress); tb.RunWorkerAsync() } void tb_DragDropCompleted(object sender, RunWorkerCompletedEventArgs e) { data.AddTorrents((Torrent[])e.Result); builder.Dispose(); dh.MoveProcessedFiles(data); dataGridViewProgressBar.Visible = false; } From my outside Thread while (autocheck) { if (torrentFiles != null) { builder.RunWorkerAsync(torrentFiles); while (builder.IsBusy) Thread.Sleep(500); } } void builder_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { data.AddTorrents((Torrent[])e.Result); builder.Dispose(); dh.MoveProcessedFiles(xml); data.Save(); //Save just does an `AcceptChanges()` and saves to a XML file }

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >