Search Results

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

Page 22/39 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • [C#] GrayScale (by ColorMatrix) causes OutOfMemoryException. Why ?

    - by Tony
    I have 2 forms, A and B. On the Form A, I click a button and an Image is being loaded to a PictureBox located ona the Form B. And, I want to set GrayScale to this image by: public void SetGrayScale(PictureBox pb) { ColorMatrix matrix = new ColorMatrix(new float[][] { new float[] {0.299f, 0.299f, 0.299f, 0, 0}, new float[] {0.587f, 0.587f, 0.587f, 0, 0}, new float[] {0.114f, 0.114f, 0.114f, 0, 0}, new float[] { 0, 0, 0, 1, 0}, new float[] { 0, 0, 0, 0, 0} }); Image image = (Bitmap)pb.Image.Clone(); ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(matrix); Graphics graphics = Graphics.FromImage(image); graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); graphics.Dispose(); pb.Image = image; } This code works properly when the PictureBox is on the same form (A). But, when it is on the Form B, the OutOfMemoryException is raised. Why ?

    Read the article

  • How do I manage disposing an object when I use IoC?

    - by Aval
    How do I manage disposing an object when I use IoC? My case it is Ninject. // normal explicit dispose using (var dc = new EFContext) { } But sometimes I need to keep the context longer or between function calls. So I want to control this behavior through IoC scope. // if i use this way. how do i make sure object is disposed. var dc = ninject.Get<IContext>() // i cannot use this since the scope can change to singleton. right ?? using (var dc = ninject.Get<IContext>()) { } Sample scopes Container.Bind<IContext>().To<EFContext>().InSingletonScope(); Container.Bind<IContext>().To<EFContext>().InRequestScope();

    Read the article

  • Subsonic 3 Simple Repository And Transactions

    - by ChrisKolenko
    Hey everyone, So this is what I have so far. Am I doing something wrong or is there a bug in 3.0.0.3? var Repository = new SimpleRepository("DBConnectionName"); using (TransactionScope ts = new TransactionScope()) { using (SharedDbConnectionScope scs = new SharedDbConnectionScope("connstring", "providerName")) { try { for (int i = 0; i < 5; i++) { Supplier s = new Supplier(); s.SupplierCode = i.ToString(); s.SupplierName = i.ToString(); Repository.Add<Supplier>(s); } ts.Complete(); } catch { } } } I'm getting an error in SubSonic DbDataProvider public DbConnection CurrentSharedConnection { get { return __sharedConnection; } protected set { if(value == null) { __sharedConnection.Dispose(); etc.. __sharedConnection == null :( Object Null Reference Exception :(

    Read the article

  • Are SOLID principles really solid?

    - by Arseny
    The first pattern stands for this acronym is SRP. Here is a quote. the single responsibility principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. That's is simple and clear till we start to code ) Suppose we have a class with well defined SRP. To serialize this class instances we need to add special atrributes to that class. So now the class have other responsibility. Dosen't it violate SRP? Let's see other story. Interface implementation. Then we implement an interface we simply add other responsibility say dispose its resorces or compare its instances or whatever. So my question. Is it possible to keep SRP complete? How can we do it?

    Read the article

  • Using Unity and interfaces, how do I create a concrete class that implements IDisposable

    - by Ryan ONeill
    I have an interface (IDbAccess) for a database access class so that I can unit test it using Unity. It all works fine in Unity and now I want to make the concrete database class implement IDisposable so that it closes the db connections. My problem is that Unity does not understand that my concrete class is disposable because the interface (IDbAccess) cannot implement another interface. So how can I write code like this (pseudo code) so that Unity is aware that it needs to dispose the class as soon as I am done? Using var MyDbAccessInstance = Unity.Resolve<IDbAccess> { } Thanks Ryan

    Read the article

  • Keep an object for the time the connection is running in ASP.NET

    - by vtortola
    Hi, I'm developing a web service with ASP.NET, is not an .asmx or WCF, it's a custom one, so I'm working with the Http classes (context, request, response, etc..). Session is disabled. I'm working with my own handler and module. I'd like to keep a object alive and accessible for the time the connection is alive. I mean, a request enters, I assign a DbCommand to it and that connection will use that command as long is doing things, when that connection is ended, the object should be disposed. I've thought, that I can add it to my IPrincipal implementation, then when the connection is authenticated in the module and the user retrieved, I can add that DbCommand to the IPrincipal, so I can retrieve it from wherever I want in the code, and after in the module EndRequest event, I can dispose it, but I don't know if there is a better approach to do this. What do you think? cheers

    Read the article

  • Non modal "status" form

    - by David Jenings
    At the beginning of a section of C# code that could take several seconds to complete, I'd like to display a non modal form with a label that just says, "Please wait..." WaitForm myWaitForm = null; try { // if conditions suggest process will take awhile myWaitForm = new WaitForm(); myWaitForm.Show(); // do stuff } finally { if (myWaitForm != null) { myWaitForm.Hide(); myWaitForm.Dispose(); myWaitForm = null; } } The problem: the WaitForm doesn't completely display before the rest of the code ties up the thread. So I only see the frame of the form. In Delphi (my old stomping ground) I would call Application.ProcessMessages after the Show() Is there an equivalent in C#? Is there a canned "status" form that I can use in situations like this? Is there a better way to approach this? Thanks in advance. David Jennings

    Read the article

  • OpenFileDialog.AutoUpgradeEnabled doesn't work under Vista or 7?

    - by Digiku
    If I specify OpenFileDialog.AutoUpgradeEnabled = true, my program still shows the old XP-style dialog. Any idea why this would happen? This is after I enable theming in Main() [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Primary()); } and this is my dialog code: private void OpenProgramFile() { OpenFileDialog programFileDialog = new OpenFileDialog(); programFileDialog.Filter = "Program files (*.exe;*.lnk)|*.exe|All files (*.*)|*.*"; programFileDialog.FilterIndex = 0; programFileDialog.Title = "Select program file"; programFileDialog.AutoUpgradeEnabled = true; programFileDialog.ShowHelp = true; DialogResult fileResult = programFileDialog.ShowDialog(); if (fileResult != DialogResult.OK) return false; programFileDialog.Dispose(); } So why would AutoUpgradeEnabled not work?

    Read the article

  • Create Zip file from stream and download it

    - by Navid Farhadi
    I have a DataTable that i want to convert it to xml and then zip it, using DotNetZip. finally user can download it via Asp.Net webpage. My code in below dt.TableName = "Declaration"; MemoryStream stream = new MemoryStream(); dt.WriteXml(stream); ZipFile zipFile = new ZipFile(); zipFile.AddEntry("Report.xml", "", stream); Response.ClearContent(); Response.ClearHeaders(); Response.AppendHeader("content-disposition", "attachment; filename=Report.zip"); zipFile.Save(Response.OutputStream); //Response.Write(zipstream); zipFile.Dispose(); the xml file in zip file is empty.

    Read the article

  • Winforms application hangs when switching to another app

    - by joseluisrod
    Hi, I believe I have a potential threading issue. I have a user control that contains the following code: private void btnVerify_Click(object sender, EventArgs e) { if (!backgroundWorkerVerify.IsBusy) { backgroundWorkerVerify.RunWorkerAsync(); } } private void backgroundWorkerVerify_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { VerifyAppointments(); } private void backgroundWorkerVerify_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { MessageBox.Show("Information was Verified.", "Verify", MessageBoxButtons.OK, MessageBoxIcon.Information); CloseEvent(); } vanilla code. but the issue I have is that when the application is running and the users tabs to another application when they return to mine the application is hung, they get a blank screen and they have to kill it. This started when I put the threading code. Could I have some rogue threads out there? what is the best way to zero in a threading problem? The issue can't be recreated on my machine...I know I must be missing something on how to dispose of a backgroundworker properly. Any thoughts are appreciated, Thanks, Jose

    Read the article

  • SQLConnection.Open(); throwing exception

    - by flavour404
    Hi, Updating an old piece of software but in order to maintain backward compatibility I need to connect to a .mdb (access) database. I am using the following connection but keep getting an exception, why? I have validated the path, database existence etc. and that is all correct. string Server = "localhost"; string Database = drive + "\\btc2\\state\\states.mdb"; string Username = ""; string Password = "Lhotse"; string ConnectionString = "Data Source = " + Server + ";" + "Initial Catalog = " + Database + ";" + "User Id = '';" + "Password = " + Password + ";"; SqlConnection SQLConnection = new SqlConnection(); try { SQLConnection.ConnectionString = ConnectionString; SQLConnection.Open(); } catch (Exception Ex) { // Try to close the connection if (SQLConnection != null) SQLConnection.Dispose(); // //can't connect // // Stop here return false; }

    Read the article

  • How GC collects resources in a static member in C#?

    - by carter-boater
    Dear all, I have a piece of code like this: Class Program { static StreamReader sr = null; static int var=0; static Program() { sr = new StreamReader("input.txt") } ~Program() { sr.Dispose(); } static void main(string args[]) { //do something with input here } } This may not be a good practice, but I just want to use this example to ask how the deconstructor and GC works. My question is: Will ~Program() get called at a non-determined time or it won't be called at all in this case. If the deconstructor won't get called, then how GC collect the unmanaged resources and managed resources. Thank you very much!

    Read the article

  • OpenNETCF DirectShowPlayerControl display is going black randomly when playing videos if the player

    - by Sundar
    I have a application that runs on touch enabled device with WinCE 3.5 OS. I have a show player control to display adds when the system is left idle for some configured amount of time.. So the DirectShowPlayerControl will be iniated every time the show player is launched and will be destroyed when it is closed... The player for the first time plays videos continuously for any amount of time. Once the player is destroyed and recreated the video are changing but the display goes black and in between if some small video is placed that alone is displayed. Whenever the form is closed am calling DirectShowPlayerControl.Dispose() method.

    Read the article

  • How to "kill" background worker completely?

    - by Ken Hung
    Hi All, I am writing a windows application that runs a sequence of digital IO actions repeatedly. This sequence of actions starts when the user click a "START" button, and it is done by a background worker in backgroundWorker1_DoWork(). However, there are occasions when I get the "This backgroundworker is currently busy......." error message. I am thinking of implementing the following in the code, by using a while loop to "kill" the background worker before starting another sequence of action: if (backgroundWorker1.IsBusy == true) { backgroundWorker1.CancelAsync(); while (backgroundWorker1.IsBusy == true) { backgroundWorker1.CancelAsync(); } backgroundWorker1.Dispose(); } backgroundWorker1.RunWorkerAsync(); I think my main concern is, will the backgroundWorker1 be "killed" eventually? If it will, will it take a long time to complete it? Will this coding get me into an infinite loop?

    Read the article

  • code to send email

    - by Alexander
    What am I doing wrong here? private void SendMail(string from, string body) { string mailServerName = "plus.pop.mail.yahoo.com"; MailMessage message = new MailMessage(from, "[email protected]", "feedback", body); SmtpClient mailClient = new SmtpClient(); mailClient.Host = mailServerName; mailClient.Send(message); message.Dispose(); } I got the following error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 209.191.108.191:25

    Read the article

  • How can I limit access to a particular class to one caller at a time in a web service?

    - by MusiGenesis
    I have a web service method in which I create a particular type of object, use it for a few seconds, and then dispose it. Because of problems arising from multiple threads creating and using instances of this class at the same time, I need to restrict the method so that only one caller at a time ever has one of these objects. To do this, I am creating a private static object: private static object _lock = new object(); ... and then inside the web service method I do this around the critical code: lock (_lock) { using (DangerousObject do = new DangerousObject()) { do.MakeABigMess(); do.CleanItUp(); } } I'm not sure this is working, though. Do I have this right? Will this code ensure that only one instance of DangerousObject is instantiated and in use at a time?

    Read the article

  • Compact Framework best practices: Building a GUI

    - by Ciaran
    I'm maintaining a Windows CE app built with the .NET Framework that has about 45 forms. There are 5 'sections' which lead to the function you want. The application is 100% full screen and it is important that it can't be minimized. Since there are so many forms, it's difficult to keep track of which form should be displayed after one is closed. For this, I'm setting the form owner property before showing it, and showing the owner when closing it. I've also been advised that it is best to instantiate all forms when the application loads, and not dispose them to save processing time. I'm not sure about this. My question is, what is the best way to go about showing, hiding forms where you want any 1 form to be in front, full screen all time?

    Read the article

  • FxCop CA2000 Warning in UserControls

    - by esjr
    Running FxCop on a WebProject that contains a UserControl will result in a CA2000 Warning (Call System.IDisposable.Dispose on object) for every ServerControl (Label, TextBox,...) in that UserControl. I understand why this would happen. Replacing the 'offending' ServerControls with a PlaceHolder and then adding the Controls in code (Using...End Using) might be a way around that, but it is not always an option.But, if they are not 'kosher' why have ServerControls you can drop in your ascx/aspx in the first place ?Am I missing something ? If, like in my case, you inherit a sizeable collection of fairly complex UserControls, do I now add every 'offending' Control to the GlobalSupperssions file (that's a lot of mind numbing right-clicking) ?I do not want to suppress all CA2000 warnings since it makes perfect sense to fix them, but not in the case of ServerControls in UserControls.

    Read the article

  • dataset tables row count 'zero'

    - by James123
    I am using dataadapter.Fill() into dataset. But dataset returning tables rows count zero (0). When I ran same sp in sql mgmt. It is returning two tables data. If attributeId = 1 Then spString = "USP_group_1" ElseIf attributeId = 2 Then spString = "USP_group_2" ElseIf attributeId = 3 Then spString = "USP_group_3" End If sqlcmd_q.CommandTimeout = 120 sqlcmd_q.Connection = sqlCnn sqlcmd_q.CommandText = spString sqlcmd_q.CommandType = CommandType.StoredProcedure sqlcmd_q.Parameters.AddWithValue("@client_id", clientId) Try sqlCnn.Open() Dim daGrid As New SqlDataAdapter(sqlcmd_q) daGrid.Fill(dsGrid) daGrid.Dispose() Return dsGrid I don't understand why this happening?

    Read the article

  • Convert PDF to Image Batch

    - by tro
    I am working on a solution where I can convert pdf files to images. I am using the following example from codeproject: http://www.codeproject.com/Articles/317700/Convert-a-PDF-into-a-series-of-images-using-Csharp?msg=4134859#xx4134859xx now I tried with the following code to generate from more then 1000 pdf files new images: using Cyotek.GhostScript; using Cyotek.GhostScript.PdfConversion; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RefClass_PDF2Image { class Program { static void Main(string[] args) { string outputPath = Properties.Settings.Default.outputPath; string pdfPath = Properties.Settings.Default.pdfPath; if (!Directory.Exists(outputPath)) { Console.WriteLine("Der angegebene Pfad " + outputPath + " für den Export wurde nicht gefunden. Bitte ändern Sie den Pfad (outputPath) in der App.Config Datei."); return; } else { Console.WriteLine("Output Pfad: " + outputPath + " gefunden."); } if (!Directory.Exists(pdfPath)) { Console.WriteLine("Der angegebene Pfad " + pdfPath + " zu den PDF Zeichnungen wurde nicht gefunden. Bitte ändern Sie den Pfad (pdfPath) in der App.Config Datei."); return; } else { Console.WriteLine("PDF Pfad: " + pdfPath + " gefunden."); } Pdf2ImageSettings settings = GetPDFSettings(); DateTime start = DateTime.Now; TimeSpan span; Console.WriteLine(""); Console.WriteLine("Extraktion der PDF Zeichnungen wird gestartet: " + start.ToShortTimeString()); Console.WriteLine(""); DirectoryInfo diretoryInfo = new DirectoryInfo(pdfPath); DirectoryInfo[] directories = diretoryInfo.GetDirectories(); Console.WriteLine(""); Console.WriteLine("Es wurden " + directories.Length + " verschiedende Verzeichnisse gefunden."); Console.WriteLine(""); List<string> filenamesPDF = Directory.GetFiles(pdfPath, "*.pdf*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList(); List<string> filenamesOutput = Directory.GetFiles(outputPath, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList(); Console.WriteLine(""); Console.WriteLine("Es wurden " + filenamesPDF.Count + " verschiedende PDF Zeichnungen gefunden."); Console.WriteLine(""); List<string> newFileNames = new List<string>(); int cutLength = pdfPath.Length; for (int i = 0; i < filenamesPDF.Count; i++) { string temp = filenamesPDF[i].Remove(0, cutLength); temp = outputPath + temp; temp = temp.Replace("pdf", "jpg"); newFileNames.Add(temp); } for (int i = 0; i < filenamesPDF.Count; i++) { FileInfo fi = new FileInfo(newFileNames[i]); if (!fi.Exists) { if (!Directory.Exists(fi.DirectoryName)) { Directory.CreateDirectory(fi.DirectoryName); } Bitmap firstPage = new Pdf2Image(filenamesPDF[i], settings).GetImage(); firstPage.Save(newFileNames[i], System.Drawing.Imaging.ImageFormat.Jpeg); firstPage.Dispose(); } //if (i % 20 == 0) //{ // GC.Collect(); // GC.WaitForPendingFinalizers(); //} } Console.ReadLine(); } private static Pdf2ImageSettings GetPDFSettings() { Pdf2ImageSettings settings; settings = new Pdf2ImageSettings(); settings.AntiAliasMode = AntiAliasMode.Medium; settings.Dpi = 150; settings.GridFitMode = GridFitMode.Topological; settings.ImageFormat = ImageFormat.Png24; settings.TrimMode = PdfTrimMode.CropBox; return settings; } } } unfortunately, I always get in the Pdf2Image.cs an out of memory exception. here the code: public Bitmap GetImage(int pageNumber) { Bitmap result; string workFile; //if (pageNumber < 1 || pageNumber > this.PageCount) // throw new ArgumentException("Page number is out of bounds", "pageNumber"); if (pageNumber < 1) throw new ArgumentException("Page number is out of bounds", "pageNumber"); workFile = Path.GetTempFileName(); try { this.ConvertPdfPageToImage(workFile, pageNumber); using (FileStream stream = new FileStream(workFile, FileMode.Open, FileAccess.Read)) { result = new Bitmap(stream); // --->>> here is the out of memory exception stream.Close(); stream.Dispose(); } } finally { File.Delete(workFile); } return result; } how can I fix that to avoid this exception? thanks for any help, tro

    Read the article

  • Custom UITableviewcell shows "fatal error: Can't unwrap Optional.None" issue in swift

    - by user1656286
    I need to load a custom cell in a UITableView. I created a custom subclass of UITableViewCell named "CustomTableViewCell". I have added a UITabelViewCell to the tableview (using drag and drop) as shown in figure. Then in file inspector I set the class of that UITabelViewCell to be "CustomTableViewCell". Here is my code: class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet var tableView : UITableView var items = String[]() override func viewDidLoad() { super.viewDidLoad() items = ["Hi","Hello","How"] self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "CusTomCell") // Do any additional setup after loading the view, typically from a nib. } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{ return items.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("CusTomCell") as CustomTableViewCell cell.labelTitle.text = items[indexPath.row] return cell; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } When I run my code, I get the following error: "fatal error: Can't unwrap Optional.None" as seen in the image.

    Read the article

  • How to convert *.aspx (HTML) page to Image format

    - by Swapnil Fegade
    I want to convert *.aspx (HTML) page's (User Interface) to Image such as JPEG. I am using below code for that Protected Sub btnGet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGet.Click saveURLToImage("http://google.co.in") End Sub Private Sub saveURLToImage(ByVal url As String) If Not String.IsNullOrEmpty(url) Then Dim content As String = "" Dim webRequest__1 As System.Net.WebRequest = WebRequest.Create(url) Dim webResponse As System.Net.WebResponse = webRequest__1.GetResponse() Dim sr As System.IO.StreamReader = New StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")) content = sr.ReadToEnd() 'save to file Dim b As Byte() = Convert.FromBase64String(content) Dim ms As New System.IO.MemoryStream(b, 0, b.Length) Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms) img.Save("c:\pic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg) img.Dispose() ms.Close() End If End Sub But I am getting Error as "Invalid character in a Base-64 string" at line Dim b As Byte() = Convert.FromBase64String(content)

    Read the article

  • linq to sql datacontext for a web application

    - by rap-uvic
    Hello, I'm trying to use linq to sql for my project (very short deadline), and I'm kind of in a bind. I don't know the best way to have a data context handy per request thread. I want something like a singleton class from which all my repository classes can access the current data context. However, singleton class is static and is not thread-safe and therefore not suitable for web apps. I want something that would create a data context at the beginning of the request and dispose of it along with the request. Can anyone please share their solution to this problem? I've been searching for a solution and I've found a good post from Rick Strahl : http://www.west-wind.com/weblog/posts/246222.aspx but I don't completely understand his thread-safe or business object approach. If somebody has a simplified version of his thread-safe approach, i'd love to take a look.

    Read the article

  • How can I limit access to a particular class to one caller at a time in an ASMX web service?

    - by MusiGenesis
    I have a web service method in which I create a particular type of object, use it for a few seconds, and then dispose it. Because of problems arising from multiple threads creating and using instances of this class at the same time, I need to restrict the method so that only one caller at a time ever has one of these objects. To do this, I am creating a private static object: private static object _lock = new object(); ... and then inside the web service method I do this around the critical code: lock (_lock) { using (DangerousObject do = new DangerousObject()) { do.MakeABigMess(); do.CleanItUp(); } } I'm not sure this is working, though. Do I have this right? Will this code ensure that only one instance of DangerousObject is instantiated and in use at a time? Or does each caller get their own copy of _lock, rendering my code here laughable?

    Read the article

  • C# this.Controls.Remove problem

    - by arnoldino
    What is the problem with this code? for (int w = 0; w < this.Controls.Count; w++) { if (this.Controls[w] is TransparentLabel) { la = (TransparentLabel)this.Controls[w]; if (la.Name != "label1") { la.Visible = false; la.Click -= new System.EventHandler(Clicked); this.Controls.Remove(this.Controls[w]); la.Dispose(); } } } I want to clear the screen from the labels, but it doesn't work.

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >