Search Results

Search found 13011 results on 521 pages for 'catch block'.

Page 162/521 | < Previous Page | 158 159 160 161 162 163 164 165 166 167 168 169  | Next Page >

  • Handling duplicate insertion

    - by Francis
    So I've got this piece of code which, logically should work but Entity Framework is behaving unexpectedly. Here: foreach (SomeClass someobject in allObjects) { Supplier supplier = new Supplier(); supplier.primary_key = someobject.id; supplier.name = someobject.displayname; try { sm.Add(supplier); ro.Created++; } catch (Exception ex) { ro.Error++; } } Here's what I have in sm.Add() public Supplier Add(Supplier supplier) { try { _ctx.AddToSupplier(supplier); _ctx.SaveChanges(); return supplier; } catch (Exception ex) { throw; } } I can have records in allObjects that have the same id. My piece of code needs to support this and just move on to the next and try to insert it, which I think should work. If this happens, an exception is throw, saying that records with dupe PKs cannot be inserted (of course). The exception mentions the value of the PK, for example 1000. All is well, a new supplier is passed to sm.Add() containing a PK that's never been used before. (1001) Weirdly though, when doing SaveChanges(), EF will whine about not being able to insert records with dupe PKs. The exception still mentions 1000 even though supplier contains 10001 in primary_key. I feel this is me not using _ctx properly. Do I need to call something else to sync it ?

    Read the article

  • Assembly-wide / root-level styles in WPF class library

    - by WarpedBoard
    I have a C# (2008/.NET 3.5) class library assembly that supports WPF (based on http://dotupdate.wordpress.com/2007/12/05/how-to-add-a-wpf-control-library-template-to-visual-c-express-2008/). I've created several windows, and am now attempting to create a common style set for them. However, as it's a class library (instead of a WPF app), I don't have an app.xaml (and its contained Application & corresponding Application.Resources) in which to store these styles for global access. So: How can I create a top-level set of style definitions that'll be seen by all xaml files in the assembly, given that I do not have app.xaml (see above)? And/or is it possible to add a working app.xaml to a class library? FYI, I did try creating a ResourceDictionary in a ResourceDictionary.xaml file, and include it in each window within a "Window.Resources" block. That turned out to solve the styling of Buttons, etc... but not for the enclosing Window. I can put 'Style="{StaticResource MyWindowStyle}"' in the Window's opening block, and it compiles and shows up in the VS Design window fine, but during actual runtime I get a parse exception (MyWindowStyle could not be found; I'm guessing Visual Studio sees the dictionary included after the line in question, but the CRL does things more sequentially and therefore hasn't loaded the ResourceDictionary yet).

    Read the article

  • delete vs execSQL commands android

    - by erik
    so i have a databas, SQLiteDatabase db I am writing a couple private methods in my manager class that will be called by a public method: public void updateData (MakeabilityModel newData){ SQLiteDatabase db = this.getWritableDatabase(); db.beginTransaction(); try { reWriteSVTable(db, list); db.setTransactionSuccessful(); } catch (Exception e){ //TODO through rollback message? e.printStackTrace(); } finally { db.endTransaction(); } } //Private Methods private void clearTable(SQLiteDatabase db, String table){ db.delete(table, null, null); } private void reWriteSVTable(SQLiteDatabase db, List<MakeabilityLens> lenses){ clearTable(db, singleVision); ContentValues cv; for(int i=0; i<lenses.size(); i++){ cv = new ContentValues(); cv.put(colScreenID, hsID); cv.put(colIconID, id); cv.put(colRank, hsTotal); db.insert(isLookUp, colID, cv); } } My question is this.. i want to be able to throw sql exceptions back to the public method so that if there is an exception, it will kill the transaction and rollback ALL data.. it appears that using delete() and insert() methods are cleaner than execSQL() but don't throw sqlExceptions. execSQL() on the other hand does? do i need to uses execSQL and how do i insure that hsould it throws an exception in any of the private methods that it will catch it and roll it back in the private method

    Read the article

  • How to adjust font size with Cufon?

    - by user77413
    I am using a condensed font in Cufon. When the page loads, my menu is too wide and wraps. Then Cufon replaces the font and it looks fine. To reduce the visual distraction, I want to set the font size smaller and then have Cufon change the font size when it displays. Currently the font size is set by the div containing the menu. Here is the CSS for the menu container: .header_menu_block { display: block; margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; margin-top: 3px; /*margin-left: 238px; ie 6 can't handle, see margin block below*/ float: left; text-align: left; font-weight: normal; font-size: 14px; color: #FFFFFF; height: 41px; width: 991px; } The Cufon replacement code looks like this: <script type="text/javascript"> Cufon.replace('.header_menu_block_col_menu ', { color: '#ffffff', hover: {color: '#204966'} } ); </script> I've tried setting the CSS font size to 12px and then using the following Cufon code, but it does not work: <script type="text/javascript"> Cufon.replace('.header_menu_block_col_menu ', { color: '#ffffff', hover: {color: '#204966'}, font-size:'14px' } ); </script> Does anyone know how to do this?

    Read the article

  • jQuery replacement for javascript confirm

    - by dcp
    Let's say I want to prompt the user before allowing them to save a record. So let's assume I have the following button defined in the markup: <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click"></asp:Button> To force a prompt with normal javascript, I could wire the OnClick event for my save button to be something like this (I could do this in Page_Load): btnSave.Attributes.Add("onclick", "return confirm('are you sure you want to save?');"); The confirm call will block until the user actually presses on of the Yes/No buttons, which is the behavior I want. For the jquery dialog that is the equivalent, I tried something like this (see below). But the problem is that unlike javascript confirm(), it's going to get all the way through this function (displayYesNoAlert) and then proceed into my btnSave_OnClick method on the C# side. I need a way to make it "block", until the user presses the Yes or No button, and then return true or false so the btnSave_OnClick will be called or not called depending on the user's answer. Currently, I just gave up and went with javascript's confirm, I just wondered if there was a way to do it. function displayYesNoAlert(msg, closeFunction) { dialogResult = false; // create the dialog if it hasn't been instantiated if (!$("#dialog-modal").dialog('isOpen') !== true) { // add a div to the DOM that will store our message $("<div id=\"dialog-modal\" style='text-align: left;' title='Alert!'>").appendTo("body"); $("#dialog-modal").html(msg).dialog({ resizable: true, modal: true, position: [300, 200], buttons: { 'Yes': function () { dialogResult = true; $(this).dialog("close"); }, 'No': function () { dialogResult = false; $(this).dialog("close"); } }, close: function () { if (closeFunction !== undefined) { closeFunction(); } } }); } $("#dialog-modal").html(msg).dialog('open'); }

    Read the article

  • Send Special Keys to Gtk.VteTerminal

    - by Ubersoldat
    Hi I have this OSS Project called Monocaffe connections manager which uses the Gtk.VteTerminal widget from PyGTK. A nice feature is that it allows the users to send commands to different servers' consoles (cluster mode) using a Gtk.TextView for the input. The way I send key strokes to each Gtk.VteTerminal is by using the feed_child method. For common keys there's no problem: I simply feed what the TextView receives to all the terminals, but when doing so with special keys I get into a little trouble. For "Return" I catch the event and feed the terminal a '\n'. For back-space is the same, catch the event and feed a '\b'. def cluster_backspace(self, widget): return self.cluster_send_key('\b') The problem comes with other keys like Tab, Arrows, Esc which I don't know how to feed as str to the terminal to recognize them. In the case of Esc is a real pain, because the users can edit the same file on different servers using vi, but cannot escape insert mode. Anyway, I'm not looking for a complete solution, just ideas since I've ran out of them. Thanks.

    Read the article

  • Multithreading A Function in VB.Net

    - by Ben
    I am trying to multi thread my application so as it is visible while it is executing the process, this is what I have so far: Private Sub SendPOST(ByVal URL As String) Try Dim DataBytes As Byte() = Encoding.ASCII.GetBytes("") Dim Request As HttpWebRequest = TryCast(WebRequest.Create(URL.Trim & "/webdav/"), HttpWebRequest) Request.Method = "POST" Request.ContentType = "application/x-www-form-urlencoded" Request.ContentLength = DataBytes.Length Request.Timeout = 1000 Request.ReadWriteTimeout = 1000 Dim PostData As Stream = Request.GetRequestStream() PostData.Write(DataBytes, 0, DataBytes.Length) Dim Response As WebResponse = Request.GetResponse() Dim ResponseStream As Stream = Response.GetResponseStream() Dim StreamReader As New IO.StreamReader(ResponseStream) Dim Text As String = StreamReader.ReadToEnd() PostData.Close() Catch ex As Exception If ex.ToString.Contains("401") Then TextBox2.Text = TextBox2.Text & URL & "/webdav/" & vbNewLine End If End Try End Sub Public Sub G0() Dim siteSplit() As String = TextBox1.Text.Split(vbNewLine) For i = 0 To siteSplit.Count - 1 Try If siteSplit(i).Contains("http://") Then SendPOST(siteSplit(i).Trim) Else SendPOST("http://" & siteSplit(i).Trim) End If Catch ex As Exception End Try Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim t As Thread t = New Thread(AddressOf Me.G0) t.Start() End Sub However, the 'G0' sub code is not being executed at all, and I need to multi thread the 'SendPOST' as that is what slows the application.

    Read the article

  • font-size/font-family has no effect

    - by kman
    This is a related issue to my previous question. I have modified the code suggested for preface headings to modify the p tags underneath the headings. <xsl:template match="topic[title='Preface']/body/section/p"> <fo:block xsl:use-attribute-sets="preface.p"> <xsl:apply-imports/> </fo:block> </xsl:template> <xsl:attribute-set name="preface.p"> <xsl:attribute name="font-family">Helvetica</xsl:attribute> <xsl:attribute name="color">red</xsl:attribute> <xsl:attribute name="font-size">8pt</xsl:attribute> </xsl:attribute-set> The color changes the desired text - and only the desired text, so I know it is grabbing the correct nodes. However, the font family and size have no effect. Does anyone know of anything I can check that might be over-riding the code?

    Read the article

  • How to mock a String using mockito?

    - by Alceu Costa
    I need to simulate a test scenario in which I call the getBytes() method of a String object and I get an UnsupportedEncodingException. I have tried to achieve that using the following code: String nonEncodedString = mock(String.class); when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error.")); The problem is that when I run my test case I get a MockitoException that says that I can't mock a java.lang.String class. Is there a way to mock a String object using mockito or, alternatively, a way to make my String object throw an UnsupportedEncodingException when I call the getBytes method? Here are more details to illustrate the problem: This is the class that I want to test: public final class A{ public static String f(String str){ try{ return new String(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // This is the catch block that I want to exercise. ... } } } This is my testing class (I'm using JUnit 4 and mockito): public class TestA { @Test(expected=UnsupportedEncodingException.class) public void test(){ String aString = mock(String.class); when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error.")); A.f(aString); } }

    Read the article

  • AS3 ExternalInterface works in IE but not Firefox

    - by user567602
    Hi all, I am trying to execute an AS3 function from my javascript using the ExternalInterface. Seems to work fine in IE, but firefox is always returning javascript error method undefined. I have been Googling this for ages and eliminated the following possibilities: 1) Some people say you need to have an embed tag inside your object tag, so added one - no luck. 2) Many people say that you need to make sure that your flash is loaded before calling the javascript. Well my call is after pressing a link on the page. I am always using the flash application first and only pressing the link at the end. 3) Then I thought that maybe it is a security problem so added the following: try { ExternalInterface.addCallback("test", testing); trace("added callback"); } catch (error:SecurityError) { trace("Security Error:"+error.message); } catch (error:Error) { trace("Error:"+error.message); } But it prints out "added callback" :( Anyone else have any ideas what else could I possible try? I am running the latest Firefox and FlashPlayer 10. Regards, Olli

    Read the article

  • Why does my Android App crash when loading image from gallery the 2nd time?

    - by Sebastian
    Hi folks, I've written an app, thats loading images either using the android gallery app or by taking a photo using the cam. When I now load an image using the gallery, everything is fine. When the code is being executed a second time (for loading another image), the application crashes. try { Uri data = intent.getData(); ContentResolver cr = this.getContentResolver(); Bitmap mBitmap = null; mBitmap = Media.getBitmap(cr, data); imageView.setImageBitmap(mBitmap); } catch(Exception e){ showToast(this, "Failed loading image from gallery"); return; } The code crashes at the line mBimap = Media.getBitmap(cr, data);. Everything is initialized, there are no null values etc. The strange thing is: no exception is thrown, I don't get into the catch block to determine whats going wrong. Does anyone have an idea about this? Am I not allowed to "re-use" the content resolver? Do I have to free it after the first usage or something like this?

    Read the article

  • How to get rid of exceptions thrown by the .NET Framework

    - by Hans Løken
    In a recent project I'm using a lot of databinding and xml-serialization. I'm using C#/VS2008 and have downloaded symbol information for the .NET framework to help me when debugging. The app I'm working on has a global "catch all" exception handler to present a more presentable messages to users if there happens to be any uncaught exceptions being thrown. My problem is when I turn on Exceptions-Thrown to be able to debug exceptions before they are caught by the "catch all". It seems to me that the framework throws a lot of exceptions that are not immediately caught (for example in ReflectPropertyDescriptor) so that the exception I'm actually trying to debug gets lost in the noise. Is there any way to get rid of exceptions caused by the framework but keep the ones from my own code? Update: after more research and actually trying to get rid of the exceptions that get thrown by the framework (many which turn out to be known issues in the framework, example: http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor) I finally found a solution that works for me, which is turning on "Just my code" in Tools Options Debugging General Enable Just My Code in VS2008.

    Read the article

  • how do I get a new line, after using float:left?

    - by codeman73
    What I am trying to do is have rows of images, 6 images in each row. Some of these images need to have another image floating on top of them (flush with the lower-right corner). I was able to get that to work from this thread: http://stackoverflow.com/questions/48474/how-do-i-position-one-image-on-top-of-another-in-html However, now I'm unable to get the new row after the 6th image. Neither <BR> or <P> create a new line. They simply push the next image down several pixels, but the image is still in the same line. It seems like the float style is interfering with the <BR> and/or <P>. I tried using different styles for the image that starts a new row, like float:none and display:block, but neither worked. The odd thing is that the new line starts after the 7th image. Here's what I'm using so far: <style type="text/css"> .containerdiv { float: left; position: relative; } .containerdivNewLine { float: none; display: block; position: relative; } .cornerimage { position: absolute; bottom: 0; right: 0; } </style> <div class="containerdiv"> <img border="0" height="188" src="myImg" width="133" /> <img class="cornerimage" height="140" src="imageOnTop" width="105" /> </div> For the 7th image, when I'm trying to start a new row, I'm simply replacing the 'containerdiv' class with 'containerdivNewLine'.

    Read the article

  • How to parse time stamps with Unicode characters in Java or Perl?

    - by ram
    I'm trying to make my code as generic as possible. I'm trying to parse install time of a product installation. I will have two files in the product, one that has time stamp I need to parse and other file tells the language of the installation. This is how I'm parsing the timestamp public class ts { public static void main (String[] args){ String installTime = "2009/11/26 \u4e0b\u5348 04:40:54"; //This timestamp I got from the first file. Those unicode charecters are some Chinese charecters...AM/PM I guess //Locale = new Locale();//don't set the language yet SimpleDateFormat df = (SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.DEFAULT); Date instTime = null; try { instTime = df.parse(installTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(instTime.toString()); } } The output I get is Parsing Failed java.text.ParseException: Unparseable date: "2009/11/26 \u4e0b\u5348 04:40:54" at java.text.DateFormat.parse(Unknown Source) at ts.main(ts.java:39) Exception in thread "main" java.lang.NullPointerException at ts.main(ts.java:45) It throws exception and at the end when I print it, it shows some proper date... wrong though. I would really appreciate if you could clarify me on these doubts How to parse timestamps that have unicode characters if this is not the proper way? If parsing is failed, how could instTime able to hold some date, wrong though? I know its some chinese,Korean time stamps so I set the locale to zh and ko as follows.. even then same error comes again Locale = new Locale("ko"); Locale = new Locale("ja"); Locale = new Locale("zh"); How can I do the same thing in Perl? I can't use Date::Manip package; Is there any other way?

    Read the article

  • Dynamic loading a class in java with a different package name

    - by C. Ross
    Is it possible to load a class in Java and 'fake' the package name/canonical name of a class? I tried doing this, the obvious way, but I get a "class name doesn't match" message in a ClassDefNotFoundException. The reason I'm doing this is I'm trying to load an API that was written in the default package so that I can use it directly without using reflection. The code will compile against the class in a folder structure representing the package and a package name import. ie: ./com/DefaultPackageClass.class // ... import com.DefaultPackageClass; import java.util.Vector; // ... My current code is as follows: public Class loadClass(String name) throws ClassNotFoundException { if(!CLASS_NAME.equals(name)) return super.loadClass(name); try { URL myUrl = new URL(fileUrl); URLConnection connection = myUrl.openConnection(); InputStream input = connection.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int data = input.read(); while(data != -1){ buffer.write(data); data = input.read(); } input.close(); byte[] classData = buffer.toByteArray(); return defineClass(CLASS_NAME, classData, 0, classData.length); } catch (MalformedURLException e) { throw new UndeclaredThrowableException(e); } catch (IOException e) { throw new UndeclaredThrowableException(e); } }

    Read the article

  • How do I grep for entire, possibly wrapped, lines of code?

    - by NXT
    When searching code for strings, I constantly run into the problem that I get meaningless, context-less results. For example, if a function call is split across 3 lines, and I search for the name of a parameter, I get the parameter on a line by itself and not the name of the function. For example, in a file containing ... someFunctionCall ("test", MY_CONSTANT, (some *really) - long / expression); grepping for MY_CONSTANT would return a line that looked like this: MY_CONSTANT, Likewise, in a comment block: ///////////////////////////////////////// // FIXMESOON, do..while is the wrong choice here, because // it makes the wrong thing happen ///////////////////////////////////////// Grepping for FIXMESOON gives the very frustrating answer: // FIXMESOON, do..while is the wrong choice here, because When there are thousands of hits, single line results are a little meaningless. What I would like to do is have grep be aware of the start and stop points of source code lines, something as simple as having it consider ";" as the line separator would be a good start. Bonus points if you can make it return the entire comment block if the hit is inside a comment. I know you can't do this with grep alone. I also am aware of the option to have grep return a certain number of lines of content. Any suggestions on how to accomplish under Linux? FYI my preferred languages are C and Perl. I'm sure I could write something, but I know that somebody must have already done this. Thanks!

    Read the article

  • C/C++ macro/template blackmagic to generate unique name.

    - by anon
    Macros are fine. Templates are fine. Pretty much whatever it works is fine. The example is OpenGL; but the technique is C++ specific and relies on no knowledge of OpenGL. Precise problem: I want an expression E; where I do not have to specify a unique name; such that a constructor is called where E is defined, and a destructor is called where the block E is in ends. For example, consider: class GlTranslate { GLTranslate(float x, float y, float z); { glPushMatrix(); glTranslatef(x, y, z); } ~GlTranslate() { glPopMatrix(); } }; Manual solution: { GlTranslate foo(1.0, 0.0, 0.0); // I had ti give it a name ..... } // auto popmatrix Now, I have this not only for glTranslate, but lots of other PushAttrib/PopAttrib calls too. I would prefer not to have to come up with a unique name for each var. Is there some trick involving macros templates ... or something else that will automatically create a variable who's constructor is called at point of definition; and destructor called at end of block? Thanks!

    Read the article

  • NullPointerException with Servlet

    - by RonaDona
    I am calling a Servlet using its URL address. This is the URL I am typing http://localhost:7001/ryan/olympics?action=selectCatalog&id=1 This is the Servlet's URL for sure; if I change the address I get page not found This is the code for the Servlet. public class Servlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { private static final long serialVersionUID = 1L; public Servlet() { super(); } public void init(ServletConfig config) throws ServletException { System.out.println("*** initializing controller servlet."); super.init(config); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (action.equals("selectCatalog")) { String categoryId = request.getParameter("id"); ProductModelDAO dao4 = new ProductModelDAOImpl("jpac"); if (categoryId != null && !categoryId.trim().equals("")) { CategoryDAO dao1 = new CategoryDAOImpl("jpac"); try { Category category = dao1.getCategoryName(categoryId); request.setAttribute("category", category); } catch (Exception e) { e.printStackTrace(); } } try { @SuppressWarnings("unchecked") List<Product> products = dao4 .getProductsByCategory(categoryId); request.setAttribute("products", products); } catch (Exception e) { e.printStackTrace(); } url = "SelectCatalog.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(url); requestDispatcher.forward(request, response); I get the NullPointerException pointing to the RequestDispatcher's line. Any help?

    Read the article

  • HOw to make image stay inside the div box on scrolling

    - by Mirage
    I have the image position fixed inside div and code is gven below #content{ margin-top:100px; width:900px; color:#009; border:1px solid red; overflow:hidden; display:block; } img { float:left; position:fixed; top:140px; padding:50px; } #text{ display:block; border:1px solid green; width:500px; height:1200px; float:right; overflow:scroll; } #footer{ clear:both; width:600px; height:300px; border:2x solid blue; color:#939; } HTML is <div id="content" > <img src="bar.jpg" width="46" height="639" /> <div id="text"> ggggggggggggggggggfgdfgdfgdgdfgdgdfgdf </div> </div> <div id="footer"> Footer text </div> </body> Now when i scroll down then image comes out of the content div box. IS there any way so that even if i scroll the image bar should stay inside the div box. The screen shot shows my problem First Screen is ok without scrolling But when i scroll the text full then it covers my footer as well

    Read the article

  • fetching gps location in blackberry

    - by SWATI
    in my application i try to fetch users location but it always 0.0 for both latitude and longitude.I have seen blackberry forum but couldn't find what am i doing wrong??? code : package com.MyChamberApp; import javax.microedition.location.Criteria; import javax.microedition.location.Location; import javax.microedition.location.LocationListener; import javax.microedition.location.LocationProvider; public class GPS_Location { static double longi; static double lati; public GPS_Location() { } public void location() { new LocationTracker(); } class LocationTracker { private LocationProvider provider; Criteria cr; public LocationTracker() { resetGPS(); } public void resetGPS() { try { cr = new Criteria(); cr.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH); cr.setPreferredResponseTime(120000); cr.setCostAllowed(true); provider = LocationProvider.getInstance(cr); provider.getLocation(120); if (provider != null) { provider.setLocationListener(new MyLocationListener(), 1,1,1); } } catch (Exception e) {} } public void run(){} private class MyLocationListener implements LocationListener { public void providerStateChanged(LocationProvider provider,int newState) { if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE) { provider.reset(); resetGPS(); } if (newState == LocationProvider.OUT_OF_SERVICE) { provider.reset(); resetGPS(); } } public void locationUpdated(LocationProvider provider,Location location) { if (location != null && location.isValid()) { try { lati = location.getQualifiedCoordinates().getLatitude(); longi = location.getQualifiedCoordinates().getLongitude(); } catch (Exception e) {} } } } } } i have tried this code on curve8300,bold9000 It works well on simulator but does not fetches value on device till i manually do not refresh my gps. thanks in advance!!!!!!!!!!!!!!!!

    Read the article

  • Why does using the Asynchronous Programming Model in .Net not lead to StackOverflow exceptions?

    - by uriDium
    For example, we call BeginReceive and have the callback method that BeginReceive executes when it has completed. If that callback method once again calls BeginReceive in my mind it would be very similar to recursion. How is that this does not cause a stackoverflow exception. Example code from MSDN: private static void Receive(Socket client) { try { // Create the state object. StateObject state = new StateObject(); state.workSocket = client; // Begin receiving the data from the remote device. client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void ReceiveCallback( IAsyncResult ar ) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject) ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); // Get the rest of the data. client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state); } else { // All the data has arrived; put it in response. if (state.sb.Length > 1) { response = state.sb.ToString(); } // Signal that all bytes have been received. receiveDone.Set(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }

    Read the article

  • Python : How to close a UDP socket while is waiting for data in recv ?

    - by alexroat
    Hello, let's consider this code in python: import socket import threading import sys import select class UDPServer: def __init__(self): self.s=None self.t=None def start(self,port=8888): if not self.s: self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.bind(("",port)) self.t=threading.Thread(target=self.run) self.t.start() def stop(self): if self.s: self.s.close() self.t.join() self.t=None def run(self): while True: try: #receive data data,addr=self.s.recvfrom(1024) self.onPacket(addr,data) except: break self.s=None def onPacket(self,addr,data): print addr,data us=UDPServer() while True: sys.stdout.write("UDP server> ") cmd=sys.stdin.readline() if cmd=="start\n": print "starting server..." us.start(8888) print "done" elif cmd=="stop\n": print "stopping server..." us.stop() print "done" elif cmd=="quit\n": print "Quitting ..." us.stop() break; print "bye bye" It runs an interactive shell with which I can start and stop an UDP server. The server is implemented through a class which launches a thread in which there's a infinite loop of recv/*onPacket* callback inside a try/except block which should detect the error and the exits from the loop. What I expect is that when I type "stop" on the shell the socket is closed and an exception is raised by the recvfrom function because of the invalidation of the file descriptor. Instead, it seems that recvfrom still to block the thread waiting for data even after the close call. Why this strange behavior ? I've always used this patter to implements an UDP server in C++ and JAVA and it always worked. I've tried also with a "select" passing a list with the socket to the xread argument, in order to get an event of file descriptor disruption from select instead that from recvfrom, but select seems to be "insensible" to the close too. I need to have a unique code which maintain the same behavior on Linux and Windows with python 2.5 - 2.6. Thanks.

    Read the article

  • MouseListener fired without checking JCheckBox

    - by Morinar
    This one is pretty crazy: I've got an AppSight recording (for those not familiar, it's a recording of what they did including keyboard/mouse input + network traffic, etc) of a customer reproducing a bug. Basically, we've got a series of items listed on the screen with JCheckBox-es down the left side. We've got a MouseListener set for the JPanel that looks something like this: private MouseAdapter createMouseListener() { return new MouseAdapter(){ public void mousePressed( MouseEvent e ) { if( e.getComponent() instanceof JCheckBox ) { // Do stuff } } }; } Based on the recording, it appears very strongly that they click just above one of the checkboxes. After that, it's my belief that this listener fired and the "Do stuff" block happened. However, it did NOT check the box. The user then saw that the box was unchecked, so they clicked on it. This caused the "Do stuff" block to fire again, thus undoing what it had done the first time. This time, the box was checked. Therefore, the user thinks that the box is checked, and it looks like it is, but our client thinks that the box is unchecked as it was clicked twice. Is this possible at all? For the life of me, I can't reproduce it or see how it could be possible, but based on the recording and the data the client sent to the server, I can't see any other logical explanation. Any help, thoughts, and or ideas would be much appreciated.

    Read the article

  • Logging in "Java Library Code" libs for Android applications

    - by K. Claszen
    I follow the advice to implement Android device (not application!) independent library code for my Android Apps in a seperate "Java Library Code" project. This makes testing easier for me as I can use the standard maven project layout, Spring test support and Continuous Build systems the way I am used to. I do not want to mix this inside my Android App project although this might be possible. I now wonder how to implement logging in this library. As this library will be used on the Android device I would like to go with android.util.Log. I added the followind dependency to my project to get the missing Android packages/classes and dependencies: <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency> But this library just contains stub method (similar to the android.jar inside the android-sdk), thus using android.util.Log results in java.lang.RuntimeException: Stub! when running my unit tests. How do I implement logging which works on the Android device but does not fail outside (I do not expect it to work, but it must not fail)? Thanks for any advice Klaus For now I am going with the workaround to catch the exception outside android but hope there is a better solution. try { Log.d("me", "hello"); } catch (RuntimeException re) { // ignore failure outside android }

    Read the article

  • Is it possible to split HTML using DOMDocument?

    - by Lynn Adrianna
    Using DOMDocument, is it possible to split a block of HTML by text wrapped in tags and those that are not, while maintaining the order? Sorry, if this doesn't make sense. My example should make it clear. Let's say I have the following block of HTML: text1<b style="color:pink">text2</b>text3<b>text4</b> <b style="font-weight:bold">text5</b> Is it possible create an array as such: array( [0] => text1 [1] => <b style="color:pink">text2</b> [2] => text3 [3] => <b>text4</b> [4] => [5] => <b style="font-weight:bold">text5</b> ) Below is my current working solution, which uses a regular expression, to split the HTML. $tokens = preg_split('/(<b\b[^>]*>.*?<\/b>)/i', $html, null, PREG_SPLIT_DELIM_CAPTURE); However, I always read that it is a bad idea to parse HTML using regular expressions, so was just wondering if there is a better way.

    Read the article

< Previous Page | 158 159 160 161 162 163 164 165 166 167 168 169  | Next Page >