Search Results

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

Page 29/39 | < Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >

  • ASP.NET MVC and NHibernate coupling

    - by Ben
    I have just started learning NHibernate. Over the past few months I have been using IoC / DI (structuremap) and the repository pattern and it has made my applications much more loosely coupled and easier to test. When switching my persistence layer to NHibernate I decided to stick with my repositories. Currently I am creating a new session on each method call but of course this means that I can not benefit from lazy loading. Therefore I wish to implement session-per-request but in doing so this will make my web project dependent on NHibernate (perhaps this is not such a bad thing?). I was planning to inject ISession into my repositories and create and dispose sessions on beginrequest/endrequest events (see http://ayende.com/Blog/archive/2009/08/05/do-you-need-a-framework.aspx) Is this a good approach? Presumably I cannot use session-per-request without having a reference to NHibernate in my web project? Having the web project dependent on NHibernate prompts my next (few) questions - why even bother with the repository? Since my web app is calling services that talk to the repositories, why not ditch the repositories and just add my NHibernate persistance code inside the services? And finally, is there really any need to split out into so many projects. Is a web project and an infrastructure project sufficient? I realise that I have veered off a bit from my original question but it seems that everyone seems to have their own opinion on these topics. Some people use the repository pattern with NHibernate, some don't. Some people stick their mapping files with the related classes, others have a separate project for this. Many thanks, Ben

    Read the article

  • C# StripStatusText Update Issue

    - by ikurtz
    I am here due to a strange behaviour in Button_Click event. The code is attached. The issue is the first StripStatus message is never displayed. any ideas as to why? private void FireBtn_Click(object sender, EventArgs e) { // Control local controls for launching attack AwayTableLayoutPanel.Enabled = false; AwayCancelBtn.Enabled = false; FireBtn.Enabled = false; ////////////// Below statusBar message is never displayed but the folowing sound clip is. GameToolStripStatusLabel.Text = "(Home vs. Away)(Attack Coordinate: (" + GameModel.alphaCoords(GridLock.Column) + "," + GridLock.Row + "))(Action: Fire)"; //////////////////////////////////////////// if (audio) { SoundPlayer fire = new SoundPlayer(Properties.Resources.fire); fire.PlaySync(); fire.Dispose(); } // compile attack message XmlSerializer s; StringWriter w; FireGridUnit fireGridUnit = new FireGridUnit(); fireGridUnit.FireGridLocation = GridLock; s = new XmlSerializer(typeof(FireGridUnit)); w = new StringWriter(); s.Serialize(w, fireGridUnit); ////////////////////////////////////////////////////////// // send attack message GameMessage GameMessageAction = new GameMessage(); GameMessageAction.gameAction = GameMessage.GameAction.FireAttack; GameMessageAction.statusMessage = w.ToString(); s = new XmlSerializer(typeof(GameMessage)); w = new StringWriter(); s.Serialize(w, GameMessageAction); SendGameMsg(w.ToString()); GameToolStripStatusLabel.Text = "(Home vs. Away)(Attack Coordinate: (" + GameModel.alphaCoords(GridLock.Column) + "," + GridLock.Row + "))(Action: Awaiting Fire Result)"; } EDIT: if I put in a messageBox after the StripStatus message the status is updated.

    Read the article

  • How can I read a DBF file with incorrectly defined column data types using ADO.NET?

    - by Jason
    I have a several DBF files generated by a third party that I need to be able to query. I am having trouble because all of the column types have been defined as characters, but the data within some of these fields actually contain binary data. If I try to read these fields using an OleDbDataReader as anything other than a string or character array, I get an InvalidCastException thrown, but I need to be able to read them as a binary value or at least cast/convert them after they are read. The columns that actually DO contain text are being returned as expected. For example, the very first column is defined as a character field with a length of 2 bytes, but the field contains a 16-bit integer. I have written the following test code to read the first column and convert it to the appropriate data type, but the value is not coming out right. The first row of the database has a value of 17365 (0x43D5) in the first column. Running the following code, what I end up getting is 17215 (0x433F). I'm pretty sure it has to do with using the ASCII encoding to get the bytes from the string returned by the data reader, but I'm not sure of another way to get the value into the format that I need, other that to write my own DBF reader and bypass ADO.NET altogether which I don't want to do unless I absolutely have to. Any help would be greatly appreciated. byte[] c0; int i0; string con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ASTM;Extended Properties=dBASE III;User ID=Admin;Password=;"; using (OleDbConnection c = new OleDbConnection(con)) { c.Open(); OleDbCommand cmd = c.CreateCommand(); cmd.CommandText = "SELECT * FROM astm2007"; OleDbDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { c0 = Encoding.ASCII.GetBytes(dr.GetValue(0).ToString()); i0 = BitConverter.ToInt16(c0, 0); } dr.Dispose(); }

    Read the article

  • NHibernate Session per Call in WCF - How to Rollback

    - by Corey Coogan
    I've implemented some components to use WCF with both an IoC Container (StructureMap) and the Session per Call pattern. The NHibernate stuff is most taken from here: http://realfiction.net/Content/Entry/133. It seems to be OK, but I want to open a transaction with each call and commit at the end, rather than just Flush() which how its being done in the article. Here's where I am running into some problems and could use some advice. I haven't figured out a good way to rollback. I realize I can check the CommunicationState and if there's an exception, rollback, like so: public void Detach(InstanceContext owner) { if (Session != null) { try { if(owner.State == CommunicationState.Faulted) RollbackTransaction(); else CommitTransaction(); } finally { Session.Dispose(); } } } void CommitTransaction() { if(Session.Transaction != null && Session.Transaction.IsActive) Session.Transaction.Commit(); } void RollbackTransaction() { if (Session.Transaction != null && Session.Transaction.IsActive) Session.Transaction.Rollback(); } However, I almost never return a faulted state from a service call. I would typically handle the exception and return an appropriate indicator on my response object and rollback the transaction myself. The only way I can think of handling this would be to inject not only repositories into my WCF services, but also an ISession so I can rollback and handle the way I want. That doesn't sit well with me and seems kind of leaky. Anyone else handling the same problem?

    Read the article

  • Is there anyway to close a StreamWriter without closing it's BaseStream?

    - by Binary Worrier
    My root problem is that when using calls Dispose on a StreamWriter, it also disposes the BaseStream (same problem with Close). I have a workaround for this, but as you can see it involves copying the stream. Is there any way to do this without copying the stream? The purpose of this is to get the contents of a string (originally read from a database) into a stream, so the stream can be read by a third party component. NB I cannot change the third party component. public System.IO.Stream CreateStream(string value) { var baseStream = new System.IO.MemoryStream(); var baseCopy = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8)) { writer.Write(value); writer.Flush(); baseStream.WriteTo(baseCopy); } baseCopy.Seek(0, System.IO.SeekOrigin.Begin); return baseCopy; } Used as public void Noddy() { System.IO.Stream myStream = CreateStream("The contents of this string are unimportant"); My3rdPartyComponent.ReadFromStream(myStream); } Ideally I'm looking for an imaginery method called BreakAssociationWithBaseStream, e.g. public System.IO.Stream CreateStream_Alternate(string value) { var baseStream = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8)) { writer.Write(value); writer.Flush(); writer.BreakAssociationWithBaseStream(); } return baseStream; }

    Read the article

  • How to find that Mutex in C# is acquired?

    - by TN
    How can I find from mutex handle in C# that a mutex is acquired? When mutex.WaitOne(timeout) timeouts, it returns false. However, how can I find that from the mutex handle? (Maybe using p/invoke.) UPDATE: public class InterProcessLock : IDisposable { readonly Mutex mutex; public bool IsAcquired { get; private set; } public InterProcessLock(string name, TimeSpan timeout) { bool created; var security = new MutexSecurity(); security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow)); mutex = new Mutex(false, name, out created, security); IsAcquired = mutex.WaitOne(timeout); } #region IDisposable Members public void Dispose() { if (IsAcquired) mutex.ReleaseMutex(); } #endregion } Currently, I am using my own property IsAcquired to determine whether I should release a mutex. Not essential but clearer, would be not to use a secondary copy of the information represented by IsAcquired property, but rather to ask directly the mutex whether it is acquired by me. Since calling mutex.ReleaseMutex() throws an exception if it is not acquired by me. (By acquired state I mean that the mutex is in not-signaled state when I am owning the mutex.)

    Read the article

  • Read alphanumeric characters from csv file in C#

    - by Prasad
    I am using the following code to read my csv file: public DataTable ParseCSV(string path) { if (!File.Exists(path)) return null; string full = Path.GetFullPath(path); string file = Path.GetFileName(full); string dir = Path.GetDirectoryName(full); //create the "database" connection string string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=\"" + dir + "\\\";" + "Extended Properties=\"text;HDR=Yes;FMT=Delimited;IMEX=1\""; //create the database query string query = "SELECT * FROM " + file; //create a DataTable to hold the query results DataTable dTable = new DataTable(); //create an OleDbDataAdapter to execute the query OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString); //fill the DataTable dAdapter.Fill(dTable); dAdapter.Dispose(); return dTable; } But the above doesn't reads the alphanumeric value from the csv file. it reads only i either numeric or alpha. Whats the fix i need to make to read the alphanumeric values? Please suggest.

    Read the article

  • C#/.Net Error: MySql.Data Object reference not set to an instance of an object.

    - by Simon
    Hello, I get this exception on my Windows 7 64bit in application running in VS 2008 express. I am using Connector/Net 6.2.2.0: Message: Object reference not set to an instance of an object. Source: MySql.Data in MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId) Stack trace: in MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId) in MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) in MySql.Data.MySqlClient.MySqlDataReader.NextResult() in MySql.Data.MySqlClient.MySqlDataReader.Close() in MySql.Data.MySqlClient.MySqlConnection.Close() in MySql.Data.MySqlClient.MySqlConnection.Dispose(Boolean disposing) in System.ComponentModel.Component.Finalize() No inner exception. This exception is unhalted and the debugger dont point on any code line. It just say "Object reference not set to an instance of an object. MySql.Data" This error is really hard to repeat. On my Windows XP 32bit is all ok. Could it be error in 64bit Windows 7? Thank you very much for your answers. Regards, simon

    Read the article

  • How to solve concurrency problems in ASP.NET Windows-Workflow and ActiveRecord/NHibernate?

    - by Famous Nerd
    I have found that ActiveRecord uses the Session-Scope object within the ASP.NET application and that if the web-site is read-write we can have a tug-o-war between the Workflow's own Data-Access SessionScope and that of the ASP.NET site. I would really like to have the WindowsWorkflow Runtime use the same object session as the web-site however, they have different lifetimes. Sometimes, a web-request may save a very simple piece of data which would execute quickly however, if the web-site kicks off a workflow process.. how can that workflow make data-modifications while still allowing the Appliaction_EndRequest to dispose the ASP.NET SessionScope ... it's like ownership of the SessionScope should be shared between the workflow runtime and the ASP.NET website. Manual Workflow Scheduler may be the Savior... if a workflow is synchronous and merely uses CallExternalMethod to interact with the Host then we could constrain all the data-access to the host.. then the sessionScope can exist once. This however, won't solve the problem of a delay activity... if this delay fires, we could need to update data... in this case we'd need an isolated Session Scope and concurrency may arise. This however, differs from SharePoint workflows where it seems that the SharePoint workflow can save data from the web and the workflow and that concurrency is handled through other means. Can anyone offer any suggestions on how to allow the workflow to manage data and play nice with ASP.NET web sites?

    Read the article

  • SWT: problems with clicking button after using setEnabled() on Linux

    - by Laimoncijus
    Hi, I have a strange case with SWT and Button after using setEnabled() - seems if I disable and enable button at least once - I cannot properly click with mouse on it anymore... Already minify code to very basic: import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class TestButton { public TestButton() { Display display = new Display(); Shell shell = new Shell(display); GridLayout mainLayout = new GridLayout(); shell.setLayout(mainLayout); shell.setSize(100, 100); Button testButton = new Button(shell, SWT.PUSH); testButton.addSelectionListener(new TestClickListener()); testButton.setText("Click me!"); //testButton.setEnabled(false); //testButton.setEnabled(true); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } class TestClickListener implements SelectionListener { @Override public void widgetDefaultSelected(SelectionEvent e) { } @Override public void widgetSelected(SelectionEvent e) { System.out.println("Click!"); } } public static void main(String[] args) { new TestButton(); } } When I keep these 2 lines commented out - I can properly click on a button and always get "Click!" logged, but if I uncomment them - then I can't click on button properly with mouse anymore - button visually seems to be clicked, but nothing is logged... Am I doing something wrong here? Or maybe it's some kind of bug on Linux platform? Because on Mac running the same code I never experienced such problems... Thanks for any hint! P.S. Running code on Ubuntu 9.10, Gnome + Compiz, Sun Java 1.6.0.16

    Read the article

  • LookAndFeel not changing in Ubuntu

    - by Tom Brito
    Anyone knows Why the laf is not changing in the following code? (running in Ubuntu) import java.awt.Dialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; public class TEST extends JPanel { public TEST() { final LookAndFeelInfo[] lafArray = UIManager.getInstalledLookAndFeels(); String[] names = new String[lafArray.length]; for (int i = 0; i < names.length; i++) { names[i] = lafArray[i].getName(); } final JComboBox cb = new JComboBox(names); cb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { try { int index = cb.getSelectedIndex(); LookAndFeelInfo lafInfo = lafArray[index]; String lafClassName = lafInfo.getClassName(); System.out.println(lafClassName); UIManager.setLookAndFeel(lafClassName); } catch (Exception e) { e.printStackTrace(); } } }); add(cb); } public static void main(String[] args) throws Exception { System.out.println("start"); JDialog dialog = new JDialog(null, Dialog.ModalityType.APPLICATION_MODAL); dialog.setContentPane(new TEST()); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setVisible(true); dialog.dispose(); System.out.println("end"); } }

    Read the article

  • vb.net, How can I limit a textchanged event for a textbox to keyboard input only?

    - by Luay
    Hi everyone, Please allow me to explain what I have and what I am trying to achieve. I have a textbox (called txtb1) and a button under it (called btn_browse) on a winform in a vb.net project. When the user clicks the button a folder browser dialog appears. The user selects his desired folder and when he/she clicks 'ok' the dialog closes and the path of the folder selected appears in the textbox. I also want to store that value in a variable to be used somewhere else(the value will be copied to an xml file when the user clicks 'apply' on the form, but this has no effect nor is related to my problem). To achieve that I have the following code: Public myVar As String Private Sub btn_browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_browse.Click Dim f As New FolderBrowserDialog If f.ShowDialog() = DialogResult.OK Then txtb1.Text = f.SelectedPath End If myVar = txtb1.text f.Dispose() End Sub This part works with no problems. Now, what if the user either: 1- decides to enter the path manually rather than use the browse button. or, 2- after using the browse button and selecting the folder they decide to manually change the location In trying to solve this I added a textchanged event to the textbox as follows: Private Sub txtb1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtb1.TextChanged myVar = txtb1.Text End Sub However, this is not working. Apparently, and I don't know if this is relevant, when the user selects the desired folder using the browse button the textchanged event is also triggered. and when I click on the textbox (to give it focus) and press any keyboard key the application simply stops responding. So my questions are: am I going about this the right way? if my logic is flawed, could someone point me to how usually such a thing could be achieved? is it possible to limit the triggering events to only keyboard input as a way around this? I tried the keydown and keypress events but I am getting the freeze. I would be grateful for your help. Thanks

    Read the article

  • ADO.NET zombie transaction bug? How to ensure that commands will not be executed on implicit transac

    - by TN
    e.g. When deadlock occurs, following SQL commands are successfully executed, even if they have assigned SQL transaction that is after rollback. It seems, it is caused by a new implicit transaction that is created on SQL Server. Someone could expect that ADO.NET would throw an exception that the commands are being executed on a zombie transaction. However, such exception is not thrown. (I think this is a bug in ASP.NET.) Moreover, because of zombie transaction the final Dispose() silently ignores the rollback. Any ideas, how can I ensure that nobody can execute commands on implicit transaction? Or, how to check that transaction is zombie? I found that Commit() and Rollback() check for zombie transaction, however I can call them for a test:) I also found that also reading IsolationLevel will do the check, but I am not sure whether simple calling transaction.IsolationLevel.ToString(); will not be removed by a future optimizer. Or do you know any other safe way invoke a getter (without using reflection or IL emitting)?

    Read the article

  • Java 2D Resize

    - by jon077
    I have some old Java 2D code I want to reuse, but was wondering, is this the best way to get the highest quality images? public static BufferedImage getScaled(BufferedImage imgSrc, Dimension dim) { // This code ensures that all the pixels in the image are loaded. Image scaled = imgSrc.getScaledInstance( dim.width, dim.height, Image.SCALE_SMOOTH); // This code ensures that all the pixels in the image are loaded. Image temp = new ImageIcon(scaled).getImage(); // Create the buffered image. BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB); // Copy image to buffered image. Graphics g = bufferedImage.createGraphics(); // Clear background and paint the image. g.setColor(Color.white); g.fillRect(0, 0, temp.getWidth(null),temp.getHeight(null)); g.drawImage(temp, 0, 0, null); g.dispose(); // j2d's image scaling quality is rather poor, especially when // scaling down an image to a much smaller size. We'll post filter // our images using a trick found at // http://blogs.cocoondev.org/mpo/archives/003584.html // to increase the perceived quality.... float origArea = imgSrc.getWidth() * imgSrc.getHeight(); float newArea = dim.width * dim.height; if (newArea <= (origArea / 2.)) { bufferedImage = blurImg(bufferedImage); } return bufferedImage; } public static BufferedImage blurImg(BufferedImage src) { // soften factor - increase to increase blur strength float softenFactor = 0.010f; // convolution kernel (blur) float[] softenArray = { 0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0}; Kernel kernel = new Kernel(3, 3, softenArray); ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); return cOp.filter(src, null); }

    Read the article

  • NHibernate: how to handle entity-based validation using session-per-request pattern, without control

    - by Seth Petry-Johnson
    What is the best way to do entity-based validation (each entity class has an IsValid() method that validates its internal members) in ASP.NET MVC, with a "session-per-request" model, where the controller has zero (or limited) knowledge of the ISession? Here's the pattern I'm using: Get an entity by ID, using an IFooRepository that wraps the current NH session. This returns a connected entity instance. Load the entity with potentially invalid data, coming from the form post. Validate the entity by callings its IsValid() method. If valid, call IFooRepository.Save(entity). Otherwise, display error message. The session is currently opened when the request begins and flushed when the request ends. Since my entity is connected to a session, flushing the session attempts to save the changes even if the object is invalid. What's the best way to keep validation logic in the entity class, limit controller knowledge of NH, and avoid saving invalid changes at the end of a request? Option 1: Explicitly evict on validation failure, implicitly flush: if the validation fails, I could manually evict the invalid object in the action method. If successful, I do nothing and the session is automatically flushed. Con: error prone and counter-intuitive ("I didn't call .Save(), why are my invalid changes being saved anyways?") Option 2: Explicitly flush, do nothing by default: By default I can dispose of the session on request end, only flushing if the controller indicates success. I'd probably create a SaveChanges() method in my base controller that sets a flag indicating success, and then query this flag when closing the session at request end. Pro: More intuitive to troubleshoot if dev forgets this step [relative to option 1] Con: I have to call IRepository.Save(entity)' and SaveChanges(). Option 3: Always work with disconnected objects: I could modify my repositories to return disconnected/transient objects, and modify the Repo.Save() method to re-attach them. Pro: Most intuitive, given that controllers don't know about NH. Con: Does this defeat many of the benefits I'd get from NH?

    Read the article

  • How to store a public key in a machine-level RSA key container

    - by Andrew Kimball
    I'm having a problem using a machine level RSA key container when storing only the public key of a public/private key pair. The following code creates a public/private pair and extracts the public key from that pair. The pair and the public key are stored in separate key containers. The keys are then obtained from those key containers at which point they should be the same as the keys going into the containers. The code works when CspProviderFlags.UseDefaultKeyContainer is specified for CspParameters.Flags (i.e. the key read back out from the PublicKey container is the same), but when CspProviderFlags.UseMachineKeyStore is specified for CspParameters.Flags the key read back from PublicKey is different. Why is the behaviour different, and what do I need to do differently to retrieve the public key from a machine-level RSA key container? var publicPrivateRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicPrivateKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true, }; var publicRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true }; //Export the key. publicRsa.ImportParameters(publicPrivateRsa.ExportParameters(false)); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); //Dispose those two CSPs. using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } publicPrivateRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicPrivateKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); publicRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); }

    Read the article

  • How do I capture a WinForm window to a bitmap without the caret

    - by Steve Dunn
    I've got window on a WinForm that I want to get the bitmap representation of. For this, I use the following code (where codeEditor is the control I want a bitmap representation of): public Bitmap GetBitmap( ) { IntPtr srcDC = NativeMethods.GetDC( codeEditor.Handle ) ; var bitmap = new Bitmap( codeEditor.Width, codeEditor.Height ) ; Graphics graphics = Graphics.FromImage( bitmap ) ; var deviceContext = graphics.GetHdc( ) ; bool blitted = NativeMethods.BitBlt( deviceContext, 0, 0, bitmap.Width, bitmap.Height, srcDC, 0, 0, 0x00CC0020 /*SRCCOPY*/ ) ; if ( !blitted ) { throw new InvalidOperationException( @"The bitmap could not be generated." ) ; } int result = NativeMethods.ReleaseDC( codeEditor.Handle, srcDC ) ; if ( result == 0 ) { throw new InvalidOperationException( @"Cannot release bitmap resources." ) ; } graphics.ReleaseHdc( deviceContext ) ; graphics.Dispose( ) ; The trouble is, this captures the caret if it's flashing in the window at the time of capture. I tried calling the Win32 method HideCaret before capturing, but it didn't seem to have any effect.

    Read the article

  • Images from SQL Server JPG/PNG Image Column not being Type Converted to Bitmap in HttpHandlers (cons

    - by kanchirk
    Our Silverlight 3.0 Client consumes Images stored/retrieved on the File System thorough ASP.NET HttpHandlers successfully. We are trying to store and read back Images using a SQL Server 2008 Database. Please find the stripped down code pasted below with the Exception. "Bitmap is not Valid" //Store document to the database private void SaveImageToDatabaseKK(HttpContext context, string pImageFileName) { try { //ADO.NET Entity Framework ImageTable documentDB = new ImageTable(); int intLength = Convert.ToInt32(context.Request.InputStream.Length); //Move the file contents into the Byte array Byte[] arrContent = new Byte[intLength]; context.Request.InputStream.Read(arrContent, 0, intLength); //Insert record into the Document table documentDB.InsertDocument(pImageFileName, arrContent, intLength); } catch { } } =The method to Read Back the Row from the Table and Send it back is below.= private void RetrieveImageFromDatabaseTableKK(HttpContext context, string pImageName) { try { ImageTable documentDB = new ImageTable(); var docRow = documentDB.GetDocument(pImageName); //based on Imagename which is unique //DocData column in table is **Image** if (docRow!=null && docRow.DocData != null && docRow.DocData.Length > 0) { Byte[] bytImage = docRow.DocData; if (bytImage != null && bytImage.Length > 0) { Bitmap newBmp = ConvertToBitmap(context, bytImage ); if (newBmp != null) { newBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg); newBmp.Dispose(); } } } } catch (Exception exRI) { } } // Convert byte array to Bitmap (byte[] to Bitmap) protected Bitmap ConvertToBitmap(byte[] bmp) { if (bmp != null) { try { TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); Bitmap b = (Bitmap)tc.ConvertFrom(bmp); **//This is where the Exception Occurs.** return b; } catch (Exception) { } } return null; }

    Read the article

  • httpHandler - subfolder issue

    - by Patto
    Hi, I am trying to redirect my old typepad blog to my new blog (permanent 301 redirect) that runs with wordpress. The new blog will also be on a new server. the old Blog had the following structure: http://subdomain.domain.com/weblog/year/month/what-ever-article.html The new Blog looks like this: http://www.domain.com/Blog/year/month/what-ever-article.html I am using an http handler that I found online and tried to work with it: public class MyHttpModule :IHttpModule { public MyHttpModule() { // // TODO: Add constructor logic here // } #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { string oldURL = System.Web.HttpContext.Current.Request.Url.ToString(); string newURL = String.Empty; //oldURL = if (oldURL.ToString().ToLower().IndexOf("articles") >= 0 || System.Web.HttpContext.Current.Request.Url.ToString().ToLower().IndexOf("weblog") >= 0) { newURL = oldURL.Replace("subdomain.domain.com/weblog", "www.domain.com/Blog/index.php"); if (newURL.ToLower().Contains("subdomain")) { newURL = "http://www.domain.com/Blog"; } } else { newURL = "http://www.domain.com/Blog"; } System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.StatusCode = 301; System.Web.HttpContext.Current.Response.AddHeader("Location", newURL); System.Web.HttpContext.Current.Response.End(); } #endregion } To use this code, I put the handler into the web.config <httpModules> <add name="MyHttpModule" type="MyHttpModule, App_Code"/> </httpModules> The issue that I have is that when I want to redirect from the http://subdomain.domain.com/weblog/year/month/what-ever-article.html, I get an error that the folder would not exist. Is there any way to change my script or add an catch all to the web.config that forwards the URL to my script? When I use "http://subdomain.domain.com/weblog/year/month/what-ever-article.html" in oldURL string, then the redirect works just fine... so I must have some IIS or web.config settings wrong. Thanks in advance, Patrick

    Read the article

  • Automatic .NET code, nhibernate session, and LINQ datacontext clean-up?

    - by AverageJoe719
    Hi all, in my goal to adopt better coding practices I have a few questions in general about automatic handling of code. I have heard different answers both from online and talking with other developers/programmers at my work. I am not sure if I should have split them into 3 questions, but they all seem sort of related: 1) How does .NET handle instances of classes and other code things that take up memory? I recently found out about using the factory pattern for certain things like service classes so that they are only instantiated once in the entire application, but then I was told that '.NET handles a lot of that stuff automatically when mentioning it.' 2) How does Nhibernate's session handle automatic clean-up of un-used things? I've seen some say that it is great at handling things automatically and you should just use a session factory and that's it, no need to close it. But I have also read and seem many examples where people close the hibernate session. 3) How does LINQ's datacontext handle this? Most of the time I never .disposed my datacontext's and the app didn't see to take a performance hit (though I am not running anything super intensively), but it seems like most people recommend disposing of your datacontext after you are done with it. However, I have seen many many code examples where the dispose method is never called. Also in general I found it kind of annoying that you couldn't access even one-deep child related objects after disposing of the datacontext unless you explicity also grabbed them in the query. Thanks all. I am loving this site so far, I kind of get lost and spend hours just reading things on here. =)

    Read the article

  • What is the Difference between GC.GetTotalMemory(false) and GC.GetTotalMemory(true)

    - by somaraj
    Hi, Could some one tell me the difference between GC.GetTotalMemory(false) and GC.GetTotalMemory(true); I have a small program and when i compared the results the first loop gives an put put < loop count 0 Diff = 32 for GC.GetTotalMemory(true); and < loop count 0 Diff = 0 for GC.GetTotalMemory(false); but shouldnt it be the otherway ? Smilarly rest of the loops prints some numbers ,which are different for both case. what does this number indicate .why is it changing as the loop increase. struct Address { public string Streat; } class Details { public string Name ; public Address address = new Address(); } class emp :IDisposable { public Details objb = new Details(); bool disposed = false; #region IDisposable Members public void Dispose() { Disposing(true); } void Disposing(bool disposing) { if (!disposed) disposed = disposing; objb = null; GC.SuppressFinalize(this); } #endregion } class Program { static void Main(string[] args) { long size1 = GC.GetTotalMemory(false); emp empobj = null; for (int i = 0; i < 200;i++ ) { // using (empobj = new emp()) //------- (1) { empobj = new emp(); //------- (2) empobj.objb.Name = "ssssssssssssssssss"; empobj.objb.address.Streat = "asdfasdfasdfasdf"; } long size2 = GC.GetTotalMemory(false); Console.WriteLine( "loop count " +i + " Diff = " +(size2-size1)); } } } }

    Read the article

  • Memory usage in Flash / Flex / AS3

    - by ggambett
    I'm having some trouble with memory management in a flash app. Memory usage grows quite a bit, and I've tracked it down to the way I load assets. I embed several raster images in a class Embedded, like this [Embed(source="/home/gabriel/text_hard.jpg")] public static var ASSET_text_hard_DOT_jpg : Class; I then instance the assets this way var pClass : Class = Embedded[sResource] as Class; return new pClass() as Bitmap; At this point, memory usage goes up, which is perfectly normal. However, nulling all the references to the object doesn't free the memory. Based on this behavior, looks like the flash player is creating an instance of the class the first time I request it, but never ever releases it - not without references, calling System.gc(), doing the double LocalConnection trick, or calling dispose() on the BitmapData objects. Of course, this is very undesirable - memory usage would grow until everything in the SWFs is instanced, regardless of whether I stopped using some asset long ago. Is my analysis correct? Can anything be done to fix this?

    Read the article

  • Email not sent until application closes

    - by Tester101
    I have an application that uses SmtpClient to send E-Mail, but the E-Mails are not sent until the application closes. I have searched and searched to find a solution to the problem, but I am not able to find one. The system does have Symantec anti-virus installed, which could possibly be the problem. Does anybody have a solution to this problem? Here is the code I am using. public class EMail { private string server; public string Server {get{return this.server;}set{this.server = value;}} private string to; public string To {get{return this.to;}set{this.to = value;}} private string from; public string From {get{return this.from;}set{this.from = value;}} private string subject; public string Subject {get{return this.subject;}set{this.subject = value;}} private string body; public string Body {get{return this.body;}set{this.body = value;}} public EMail() {} public EMail(string _server, string _to, string _from, string _subject, string _body) { this.Server = _server; this.To = _to; this.From = _from; this.Subject = _subject; this.Body = _body; } public void Send() { System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(this.From, this.To, this.Subject, this.Body); message.IsBodyHtml = true; System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Server); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //I have tried this, but it still does not work. //client.ServicePoint.ConnectionLeaseTimeout = 0; try { client.Send(message); } catch(System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } message.Dispose(); } }

    Read the article

  • Understanding F# Asynchronous Programming

    - by Yin Zhu
    I kind of know the syntax of asynchronous programming in F#. E.g. let downloadUrl(url:string) = async { let req = HttpWebRequest.Create(url) // Run operation asynchronously let! resp = req.AsyncGetResponse() let stream = resp.GetResponseStream() // Dispose 'StreamReader' when completed use reader = new StreamReader(stream) // Run asynchronously and then return the result return! reader.AsyncReadToEnd() } In F# expert book (and many other sources), they say like let! var = expr simply means "perform the asynchronous operation expr and bind the result to var when the operation completes. Then continue by executing the rest of the computation body" I also know that a new thread is created when performing async operation. My original understanding was that there are two parallel threads after the async operation, one doing I/O and one continuing to execute the async body at the same time. But in this example, I am confused at let! resp = req.AsyncGetResponse() let stream = resp.GetResponseStream() What happens if resp has not started yet and the thread in the async body wants to GetResponseStream? Is this a possible error? So maybe my original understanding was wrong. The quoted sentences in the F# expert book actually means that "creating a new thread, hang the current thread up, when the new thread finishes, wake up the body thread and continue", but in this case I don't see we could save any time. In the original understanding, the time is saved when there are several independent IO operations in one async block so that they could be done at the same time without intervention with each other. But here, if I don't get the response, I cannot create the stream; only I have stream, I can start reading the stream. Where's the time gained?

    Read the article

  • Violation of PRIMARY KEY constraint 'PK_

    - by abhi
    hi am trying to write a code in which i need to perform a update but on primary keys how do i achieve it i have written the following code: kindly look at it let me know where m wrong Protected Sub rgKMSLoc_UpdateCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles rgKMSLoc.UpdateCommand Try KAYAReqConn.Open() If TypeOf e.Item Is GridEditableItem Then Dim strItemID As String = CType(e.Item.FindControl("hdnID"), HiddenField).Value Dim strrcmbLocation As String = CType(e.Item.FindControl("rcmbLocation"), RadComboBox).SelectedValue Dim strKubeLocation As String = CType(e.Item.FindControl("txtKubeLocation"), TextBox).Text Dim strCSVCode As String = CType(e.Item.FindControl("txtCSVCode"), TextBox).Text SQLCmd = New SqlCommand("SELECT * FROM MstKMSLocKubeLocMapping WHERE LocationID= '" & rcmbLocation.SelectedValue & "'", KAYAReqConn) Dim dr As SqlDataReader dr = SQLCmd.ExecuteReader If dr.HasRows Then lblMsgWarning.Text = "<font color=red>""User ID Already Exists" Exit Sub End If dr.Close() SQLCmd = New SqlCommand("UPDATE MstKMSLocKubeLocMapping SET LocationID=@Location,KubeLocation=@KubeLocation,CSVCode=@CSVCode WHERE LocationID = '" & strItemID & "'", KAYAReqConn) SQLCmd.Parameters.AddWithValue("@Location", Replace(strrcmbLocation, "'", "''")) SQLCmd.Parameters.AddWithValue("@KubeLocation", Replace(strKubeLocation, "'", "''")) SQLCmd.Parameters.AddWithValue("@CSVCode", Replace(strCSVCode, "'", "''")) SQLCmd.Parameters.AddWithValue("@Status", "A") SQLCmd.ExecuteNonQuery() lblMessageUpdate.Text = "<font color=blue>""Record Updated SuccessFully" SQLCmd.Dispose() rgKMSLoc.Rebind() End If Catch ex As Exception Response.Write(ex.ToString) Finally KAYAReqConn.Close() End Try End Sub this is my designer page' Location: ' / ' DataSourceID="dsrcmbLocation" DataTextField="Location" DataValueField="LocationID" Height="150px" Kube Location: ' Class="forTextBox" MaxLength="4" onkeypress="return filterInput(2,event);" CSV Code: ' Class="forTextBox" MaxLength="4" onkeypress="return filterInput(2,event);" <tr class="tableRow"> <td colspan="2" align="center" class="tableCell"> <asp:ImageButton ID="btnUpdate" runat="server" CommandName="Update" CausesValidation="true" ValidationGroup="Update" ImageUrl="~/Images/update.gif"></asp:ImageButton> <asp:ImageButton ID="btnCancel" runat="server" CausesValidation="false" CommandName="Cancel" ImageUrl="~/Images/No.gif"></asp:ImageButton> </td> </tr> </table> </FormTemplate> </EditFormSettings> Locationid is my primary key

    Read the article

< Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >