Search Results

Search found 34195 results on 1368 pages for 'try'.

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

  • Java exception handling in non sequential tasks (pattern/good practice)

    - by Hernán Eche
    There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...) But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc.. For that kind of tasks, I would like to know a java best practice or pattern for manage exceptions.. The java simple way is: getUFO { try { loadSoundDriver(); loadUsbDriver(); loadAlienDetectorDriver(); loadKeyboardDriver(); } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } But what about having an exception in one of the actions but wanting to try with the next ones?? I've thought this approach, but don't seem to be a good use for exceptions I don't know if it works, doesn't matter, it's really awful!! getUFO { Exception ex=null; try { try{ loadSoundDriver(); }catch (Exception e) { ex=e; } try{ loadUsbDriver(); }catch (Exception e) { ex=e; } try{ loadAlienDetectorDriver(); }catch (Exception e) { ex=e; } try{ loadKeyboardDriver() }catch (Exception e) { ex=e; } close the file; if(ex!=null) { throw ex; } } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } seems not complicated to find a better practice for doing that.. I still didn't thanks for any advice

    Read the article

  • Documentation style: how do you differentiate variable names from the rest of the text within a comm

    - by Alix
    Hi, This is a quite superfluous and uninteresting question, I'm afraid, but I always wonder about this. When you're commenting code with inline comments (as opposed to comments that will appear in the generated documentation) and the name of a variable appears in the comment, how do you differentiate it from normal text? E.g.: // Try to parse type. parsedType = tryParse(type); In the comment, "type" is the name of the variable. Do you mark it in any way to signify that it's a symbol and not just part of the comment's text? I've seen things like this: // Try to parse "type". // Try to parse 'type'. // Try to parse *type*. // Try to parse <type>. // Try to parse [type]. And also: // Try to parse variable type. (I don't think the last one is very helpful; it's a bit confusing; you could think "variable" is an adjective there) Do you have any preference? I find that I need to use some kind of marker; otherwise the comments are sometimes ambiguous, or at least force you to reread them when you realise a particular word in the comment was actually the name of a variable. (In comments that will appear in the documentation I use the appropriate tags for the generator, of course: @code, <code></code>, etc) Thanks!

    Read the article

  • VB.NET CInt(Long) behaving differently in 32- and 64-bit environments

    - by LocoDelAssembly
    Hello everybody, this is my first message here. Today I had a problem converting a Long (Int64) to an Integer (Int32). The problem is that my code was always working in 32-bit environments, but when I try THE SAME executable in a 64-bit computer it crashes with a System.OverflowException exception. I've prepared this test code in VS2008 in a new project with default settings: Module Module1 Sub Main() Dim alpha As Long = -1 Dim delta As Integer Try delta = CInt(alpha And UInteger.MaxValue) Console.WriteLine("CINT OK") delta = Convert.ToInt32(alpha And UInteger.MaxValue) Console.WriteLine("Convert.ToInt32 OK") Catch ex As Exception Console.WriteLine(ex.GetType().ToString()) Finally Console.ReadLine() End Try End Sub End Module On my 32-bit setups (Windows XP SP3 32-bit and Windows 7 32-bit) it prints "CINT OK", but in the 64-bit computer (Windows 7 64-bit) that I've tested THE SAME executable it prints the exception name only. Is this behavior documented? I tried to find a reference but failed miserably. For reference I leave the MSIL code too: .method public static void Main() cil managed { .entrypoint .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) // Code size 88 (0x58) .maxstack 2 .locals init ([0] int64 alpha, [1] int32 delta, [2] class [mscorlib]System.Exception ex) IL_0000: nop IL_0001: ldc.i4.m1 IL_0002: conv.i8 IL_0003: stloc.0 IL_0004: nop .try { .try { IL_0005: ldloc.0 IL_0006: ldc.i4.m1 IL_0007: conv.u8 IL_0008: and IL_0009: conv.ovf.i4 IL_000a: stloc.1 IL_000b: ldstr "CINT OK" IL_0010: call void [mscorlib]System.Console::WriteLine(string) IL_0015: nop IL_0016: ldloc.0 IL_0017: ldc.i4.m1 IL_0018: conv.u8 IL_0019: and IL_001a: call int32 [mscorlib]System.Convert::ToInt32(int64) IL_001f: stloc.1 IL_0020: ldstr "Convert.ToInt32 OK" IL_0025: call void [mscorlib]System.Console::WriteLine(string) IL_002a: nop IL_002b: leave.s IL_0055 } // end .try catch [mscorlib]System.Exception { IL_002d: dup IL_002e: call void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError(class [mscorlib]System.Exception) IL_0033: stloc.2 IL_0034: nop IL_0035: ldloc.2 IL_0036: callvirt instance class [mscorlib]System.Type [mscorlib]System.Exception::GetType() IL_003b: callvirt instance string [mscorlib]System.Type::ToString() IL_0040: call void [mscorlib]System.Console::WriteLine(string) IL_0045: nop IL_0046: call void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError() IL_004b: leave.s IL_0055 } // end handler } // end .try finally { IL_004d: nop IL_004e: call string [mscorlib]System.Console::ReadLine() IL_0053: pop IL_0054: endfinally } // end handler IL_0055: nop IL_0056: nop IL_0057: ret } // end of method Module1::Main I suspect that the instruction that is behaving differently is either conv.ovf.i4 or the ldc.i4.m1/conv.u8 pair. If you know what is going on here please let me know Thanks

    Read the article

  • How do I configure freeSSHd on Windows Server 2008 so I can log in using ssh?

    - by Daryl Spitzer
    I've installed freeSSHd on a Windows Server 2008 box (following the instructions in How to install an SSH Server in Windows Server 2008), including: created a user named "dspitzer" with NTLM authorization opened an exception for port 22 in the Windows Firewall But when I try to connect (from a Mac OS X 10.5.8 command-line), I get permission denied after entering the password: $ ssh 12.34.56.78 [email protected]'s password: Permission denied, please try again. [email protected]'s password: Permission denied, please try again. [email protected]'s password: Received disconnect from 12.34.56.78: 2: Too many attempts. I've also tried: $ ssh [email protected] [email protected]'s password: Permission denied, please try again. [email protected]'s password: Permission denied, please try again. [email protected]'s password: Received disconnect from 12.34.56.78: 2: Too many attempts. I've also tried changing the authorization to "Password stored as SHA1 hash" and entering a simple password, but I get the same problem. And I've tried a different user name ("Administrator") with no luck. I've confirmed that I am connecting to the server I'm configuring—if I stop freeSSHd and try to connect I get: $ ssh 12.34.56.78 ssh: connect to host 12.34.56.78 port 22: Operation timed out I get the exact same results from a Linux command-line. Any advice or troubleshooting tips? Update: I tried disabling the firewall (in response to geeklin's comment) and it made no difference. Update #2: I no longer have this machine (I've changed employers), so I have no way of verifying the answers. I guess all I can do is make this question "community wiki".

    Read the article

  • How do I configure freeSSHd on Windows Server 2008 so I can log in using ssh?

    - by Daryl Spitzer
    I've installed freeSSHd on a Windows Server 2008 box (following the instructions in How to install an SSH Server in Windows Server 2008), including: created a user named "dspitzer" with NTLM authorization opened an exception for port 22 in the Windows Firewall But when I try to connect (from a Mac OS X 10.5.8 command-line), I get permission denied after entering the password: $ ssh 12.34.56.78 [email protected]'s password: Permission denied, please try again. [email protected]'s password: Permission denied, please try again. [email protected]'s password: Received disconnect from 12.34.56.78: 2: Too many attempts. I've also tried: $ ssh [email protected] [email protected]'s password: Permission denied, please try again. [email protected]'s password: Permission denied, please try again. [email protected]'s password: Received disconnect from 12.34.56.78: 2: Too many attempts. I've also tried changing the authorization to "Password stored as SHA1 hash" and entering a simple password, but I get the same problem. And I've tried a different user name ("Administrator") with no luck. I've confirmed that I am connecting to the server I'm configuring—if I stop freeSSHd and try to connect I get: $ ssh 12.34.56.78 ssh: connect to host 12.34.56.78 port 22: Operation timed out I get the exact same results from a Linux command-line. Any advice or troubleshooting tips? Update: I tried disabling the firewall (in response to geeklin's comment) and it made no difference. Update #2: I no longer have this machine (I've changed employers), so I have no way of verifying the answers. I guess all I can do is make this question "community wiki".

    Read the article

  • Windows Virtual Machines will not run

    - by jlego
    I'm trying to setup a few virtual machines to use for testing websites in the various old versions of IE. I had Microsoft Virtual PC working on an older machine using XP mode and 2 other VHD's from Microsoft that allowed me to test in IE6-IE8. I've recently gotten a new work machine and am trying to set up the VMs again for testing, however nothing seems to be working. Both the old and the new system run Windows 7 64-bit Ultimate with AMD processors. I downloaded Virtual PC & XP mode from here http://www.microsoft.com/windows/virtual-pc/download.aspx and go through the installation process. XP mode is installed, but when I try to run it it goes through the initial setup process only to fail when it is almost complete with the error "Cannot Complete Setup". (After googling I see that this might be a conflict with my processor) I download other VHD's from here http://www.microsoft.com/windows/virtual-pc/download.aspx in order to get the other versions of IE and try to set those up in Virtual PC as well. I click on them to start the machine and both Windows 7 with IE8 and Windows Vista with IE7 just hang at a black screen. I try to use Virtual Box instead, and I get Windows XP with IE6 running, but I have no internet connection in the VM. I try all different settings and try to google the correct settings but nothing seems to work. When I load the VM, XP shows that its found new hardware but it needs the drivers. One of these pieces of hardware is the network adapter, but I can't connect to the internet to download the driver in the guest OS. VirtualBox tells me I need to install extensions in order for things to function properly. I go through the installation process in the guest OS and restart the VM, however now XP is asking for validation and I can't access the VM. I try installing the other 2 OS (Vista & 7) but I get a BSOD right after the startup screen appears and the VM restarts itself. I'm getting so frustrated trying to make this work, I would really appreciate any assistance on getting the VMs up and running or any alternatives for testing websites in Internet Explorer.

    Read the article

  • Allowing non-admin users to unstick the print spooler

    - by Reafidy
    I currently have an issue where the print que is getting stuck on a central print server (windows server 2008). Using the "Clear all documents" function does not clear it and gets stuck too. I need non-admin users to be able to clear the print cue from there work stations. I have tried using the following winforms program which I created and allows a user to stop the print spooler, delete printer files in the "C:\Windows\System32\spool\PRINTERS folder" and then start the print spooler but this functionality requires the program to be runs as an administrator, how can I allow my normal users to execute this program without giving them admin privileges? Or is there another way I can allow normal user to clear the print que on the server? Imports System.ServiceProcess Public Class Form1 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click ClearJammedPrinter() End Sub Public Sub ClearJammedPrinter() Dim tspTimeOut As TimeSpan = New TimeSpan(0, 0, 5) Dim controllerStatus As ServiceControllerStatus = ServiceController1.Status Try If ServiceController1.Status <> ServiceProcess.ServiceControllerStatus.Stopped Then ServiceController1.Stop() End If Try ServiceController1.WaitForStatus(ServiceProcess.ServiceControllerStatus.Stopped, tspTimeOut) Catch Throw New Exception("The controller could not be stopped") End Try Dim strSpoolerFolder As String = "C:\Windows\System32\spool\PRINTERS" Dim s As String For Each s In System.IO.Directory.GetFiles(strSpoolerFolder) System.IO.File.Delete(s) Next s Catch ex As Exception MsgBox(ex.Message) Finally Try Select Case controllerStatus Case ServiceControllerStatus.Running If ServiceController1.Status <> ServiceControllerStatus.Running Then ServiceController1.Start() Case ServiceControllerStatus.Stopped If ServiceController1.Status <> ServiceControllerStatus.Stopped Then ServiceController1.Stop() End Select ServiceController1.WaitForStatus(controllerStatus, tspTimeOut) Catch MsgBox(String.Format("{0}{1}", "The print spooler service could not be returned to its original setting and is currently: ", ServiceController1.Status)) End Try End Try End Sub End Class

    Read the article

  • Download And Install apk from a link.

    - by rayman
    Hi, I`am trying to download and install an apk from some link, but for some reason i get an exception. I have one method downloadfile() which downloading the file and a call to and installFile() method, which supposed to install it in the device. some code: public void downloadFile() { String fileName = "someApplication.apk"; MsgProxyLogger.debug(TAG, "TAG:Starting to download"); try { URL u = new URL( "http://10.122.233.22/test/someApplication.apk"); try { HttpURLConnection c = (HttpURLConnection) u.openConnection(); try { c.setRequestMethod("GET"); c.setDoOutput(true); try { c.connect(); FileOutputStream f = context.openFileOutput(fileName, context.MODE_WORLD_READABLE); try { InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; int totsize = 0; try { while ((len1 = in.read(buffer)) > 0) { totsize += len1; f.write(buffer, 0, len1);// .write(buffer); } } catch (IOException e) { e.printStackTrace(); } f.close(); MsgProxyLogger.debug(TAG, TAG + ":Saved file with name: " + fileName); InstallFile(fileName); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } catch (ProtocolException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } } and this is the install file method: private void InstallFile(String fileName) { MsgProxyLogger.debug(TAG, TAG + ":Installing file " + fileName); String src = String.format( "file:///data/data/com.test/files/", fileName); Uri mPackageURI = Uri.parse(src); PackageManager pm = context.getPackageManager(); int installFlags = 0; try { PackageInfo pi = pm.getPackageInfo("com.mirs.agentcore.msgproxy", PackageManager.GET_UNINSTALLED_PACKAGES); if (pi != null) { MsgProxyLogger.debug(TAG, TAG + ":replacing " + fileName); installFlags |= PackageManager.REPLACE_EXISTING_PACKAGE; } } catch (NameNotFoundException e) { } try { // PackageInstallObserver observer = new PackageInstallObserver(); pm.installPackage(mPackageURI); } catch (SecurityException e) { //!!!!!!!!!!!!!here i get an security exception!!!!!!!!!!! MsgProxyLogger.debug(TAG, TAG + ":not permission? " + fileName); } this is the exception details: "Neither user 10057 nor current process has android.permission.INSTALL_PACKAGES". and i have set in my main app that permission in the manifest. anyone has any idea? thanks, ray.

    Read the article

  • stored procedure exception handling in asp.net

    - by anay
    Do i need to use try catch in my stored procedure to know where exactly in my procedure error has occured or can i achieve the same if i useSqlConnection.BeginTransaction in my ASP.NET form or simple try catch may be...??? I tried implementing try catch in my stored procedure..i m using sql server 2005 but it does not know TRY and CATCH keywords or ERROR_MESSAGE() function...i also installed sql server 2005 service manager but still it does not work.. if an error is thrown using RAISERROR method will the exception will be shown in my ASP.NET form??

    Read the article

  • Mixing policy-based design with CRTP in C++

    - by Eitan
    I'm attempting to write a policy-based host class (i.e., a class that inherits from its template class), with a twist, where the policy class is also templated by the host class, so that it can access its types. One example where this might be useful is where a policy (used like a mixin, really), augments the host class with a polymorphic clone() method. Here's a minimal example of what I'm trying to do: template <template <class> class P> struct Host : public P<Host<P> > { typedef P<Host<P> > Base; typedef Host* HostPtr; Host(const Base& p) : Base(p) {} }; template <class H> struct Policy { typedef typename H::HostPtr Hptr; Hptr clone() const { return Hptr(new H((Hptr)this)); } }; Policy<Host<Policy> > p; Host<Policy> h(p); int main() { return 0; } This, unfortunately, fails to compile, in what seems to me like circular type dependency: try.cpp: In instantiation of ‘Host<Policy>’: try.cpp:10: instantiated from ‘Policy<Host<Policy> >’ try.cpp:16: instantiated from here try.cpp:2: error: invalid use of incomplete type ‘struct Policy<Host<Policy> >’ try.cpp:9: error: declaration of ‘struct Policy<Host<Policy> >’ try.cpp: In constructor ‘Host<P>::Host(const P<Host<P> >&) [with P = Policy]’: try.cpp:17: instantiated from here try.cpp:5: error: type ‘Policy<Host<Policy> >’ is not a direct base of ‘Host<Policy>’ If anyone can spot an obvious mistake, or has successfuly mixing CRTP in policies, I would appreciate any help.

    Read the article

  • Image rescale and write rescaled image file in blackberry

    - by Karthick
    I am using the following code to resize and save the file in to the blackberry device. After image scale I try to write image file into device. But it gives the same data. (Height and width of the image are same).I have to make rescaled image file.Can anyone help me ??? class ResizeImage extends MainScreen implements FieldChangeListener { private String path="file:///SDCard/BlackBerry/pictures/test.jpg"; private ButtonField btn; ResizeImage() { btn=new ButtonField("Write File"); btn.setChangeListener(this); add(btn); } public void fieldChanged(Field field, int context) { if (field == btn) { try { InputStream inputStream = null; //Get File Connection FileConnection fileConnection = (FileConnection) Connector.open(path); if (fileConnection.exists()) { inputStream = fileConnection.openInputStream(); //byte data[]=inputStream.toString().getBytes(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int j = 0; while((j=inputStream.read()) != -1) { baos.write(j); } byte data[] = baos.toByteArray(); inputStream.close(); fileConnection.close(); WriteFile("file:///SDCard/BlackBerry/pictures/org_Image.jpg",data); EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length); int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(80)); int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(80)); eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY); WriteFile("file:///SDCard/BlackBerry/pictures/resize.jpg",eImage.getData()); BitmapField bit=new BitmapField(eImage.getBitmap()); add(bit); } } catch(Exception e) { System.out.println("Exception is ==> "+e.getMessage()); } } } void WriteFile(String fileName,byte[] data) { FileConnection fconn = null; try { fconn = (FileConnection) Connector.open(fileName,Connector.READ_WRITE); } catch (IOException e) { System.out.print("Error opening file"); } if (fconn.exists()) try { fconn.delete(); } catch (IOException e) { System.out.print("Error deleting file"); } try { fconn.create(); } catch (IOException e) { System.out.print("Error creating file"); } OutputStream out = null; try { out = fconn.openOutputStream(); } catch (IOException e) { System.out.print("Error opening output stream"); } try { out.write(data); } catch (IOException e) { System.out.print("Error writing to output stream"); } try { fconn.close(); } catch (IOException e) { System.out.print("Error closing file"); } } }

    Read the article

  • Python how to execute generate code ?

    - by Natim
    Hello guys I have this code, and I would like to use the app parameter to generate the code instead of duplicating it. if app == 'map': try: from modulo.map.views import map return map(request, *args, **kwargs) except ImportError: pass elif app == 'schedule': try: from modulo.schedule.views import schedule_day return schedule_day(request, *args, **kwargs) except ImportError: pass elif app == 'sponsors': try: from modulo.sponsors.views import sponsors return sponsors(request, *args, **kwargs) except ImportError: pass elif app == 'streaming': try: from modulo.streaming.views import streaming return streaming(request, *args, **kwargs) except ImportError: pass Do you have any idea ? Thanks

    Read the article

  • Python: how to execute generated code ?

    - by Natim
    Hello guys I have this code, and I would like to use the app parameter to generate the code instead of duplicating it. if app == 'map': try: from modulo.map.views import map return map(request, *args, **kwargs) except ImportError: pass elif app == 'schedule': try: from modulo.schedule.views import schedule_day return schedule_day(request, *args, **kwargs) except ImportError: pass elif app == 'sponsors': try: from modulo.sponsors.views import sponsors return sponsors(request, *args, **kwargs) except ImportError: pass elif app == 'streaming': try: from modulo.streaming.views import streaming return streaming(request, *args, **kwargs) except ImportError: pass Do you have any idea ? Thanks

    Read the article

  • Trappings MySQL Warnings on Calls Wrapped in Classes -- Python

    - by chernevik
    I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes. I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. These seem to run queries properly, but the MySQL warnings they generate are not caught as exceptions in a try/else block. Why don't the try/else blocks catch the warnings? How would I revise the classes or method calls to catch the warnings? Also, I've looked through the prominent sources and can't find a discussion that helps me understand this. I'd appreciate any reference that explains this. Please see code below. Apologies for verbosity, I'm newbie. #!/usr/bin/python import MySQLdb import sys import copy sys.path.append('../../config') import credentials as c # local module with dbase connection credentials #============================================================================= # CLASSES #------------------------------------------------------------------------ class dbMySQL_Connection: def __init__(self, db_server, db_user, db_passwd): self.conn = MySQLdb.connect(db_server, db_user, db_passwd) def getCursor(self, dict_flag=True): self.dbMySQL_Cursor = dbMySQL_Cursor(self.conn, dict_flag) return self.dbMySQL_Cursor def runQuery(self, qryStr, dict_flag=True): qry_res = runQueryNoCursor(qryStr=qryStr, \ conn=self, \ dict_flag=dict_flag) return qry_res #------------------------------------------------------------------------ class dbMySQL_Cursor: def __init__(self, conn, dict_flag=True): if dict_flag: dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor) else: dbMySQL_Cursor = conn.cursor() self.dbMySQL_Cursor = dbMySQL_Cursor def closeCursor(self): self.dbMySQL_Cursor.close() #============================================================================= # QUERY FUNCTIONS #------------------------------------------------------------------------------ def runQueryNoCursor(qryStr, conn, dict_flag=True): dbMySQL_Cursor = conn.getCursor(dict_flag) qry_res =runQueryFnc(qryStr, dbMySQL_Cursor.dbMySQL_Cursor) dbMySQL_Cursor.closeCursor() return qry_res #------------------------------------------------------------------------------ def runQueryFnc(qryStr, dbMySQL_Cursor): qry_res = {} qry_res['rows'] = dbMySQL_Cursor.execute(qryStr) qry_res['result'] = copy.deepcopy(dbMySQL_Cursor.fetchall()) qry_res['messages'] = copy.deepcopy(dbMySQL_Cursor.messages) qry_res['query_str'] = qryStr return qry_res #============================================================================= # USAGES qry = 'DROP DATABASE IF EXISTS database_of_armaments' dbConn = dbMySQL_Connection(**c.creds) def dbConnRunQuery(): # Does not trap an exception; warning displayed to standard error. try: dbConn.runQuery(qry) except: print "dbConn.runQuery() caught an exception." def dbConnCursorExecute(): # Does not trap an exception; warning displayed to standard error. dbConn.getCursor() # try/except block does catches error without this try: dbConn.dbMySQL_Cursor.dbMySQL_Cursor.execute(qry) except Exception, e: print "dbConn.dbMySQL_Cursor.execute() caught an exception." print repr(e) def funcRunQueryNoCursor(): # Does not trap an exception; no warning displayed try: res = runQueryNoCursor(qry, dbConn) print 'Try worked. %s' % res except Exception, e: print "funcRunQueryNoCursor() caught an exception." print repr(e) #============================================================================= if __name__ == '__main__': print '\n' print 'EXAMPLE -- dbConnRunQuery()' dbConnRunQuery() print '\n' print 'EXAMPLE -- dbConnCursorExecute()' dbConnCursorExecute() print '\n' print 'EXAMPLE -- funcRunQueryNoCursor()' funcRunQueryNoCursor() print '\n'

    Read the article

  • An error occurred creating the form. See Exception.InnerException for details. The error is: Object

    - by Ben
    I get this error when attempting to debug my form, I cannot see where at all the error could be (also does not highlight where), anyone have any suggestions? An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object. Public Class Form1 Dim dateCrap As String = "Date:" Dim IPcrap As String = "Ip:" Dim pcCrap As String = "Computer:" Dim programCrap As String = "Program:" Dim textz As String = TextBox1.Text Dim sep() As String = {vbNewLine & vbNewLine} Dim sections() As String = Text.Split(sep, StringSplitOptions.None) Dim NewArray() As String = TextBox1.Text.Split(vbNewLine) Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click For i = 0 To sections.Count - 1 TextBox2.Text = sections(i) Dim text2 As String = TextBox2.Text Dim sep2() As String = {vbNewLine & vbNewLine} Dim sections2() As String = Text.Split(sep, StringSplitOptions.None) Dim FTPinfo() As String = TextBox2.Text.Split(vbNewLine) Dim clsRequest As System.Net.FtpWebRequest = _ DirectCast(System.Net.WebRequest.Create(sections2(0).Replace("Url/Host:", "")), System.Net.FtpWebRequest) clsRequest.Credentials = New System.Net.NetworkCredential(sections2(1).Replace("Login:", ""), (sections2(2).Replace("Password:", ""))) clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile ' read in file... Dim bFile() As Byte = System.IO.File.ReadAllBytes(txtShellDir.Text) ' upload file... Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream() clsStream.Write(bFile, 0, bFile.Length) clsStream.Close() clsStream.Dispose() Next End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click ListBox1.Items.Clear() Dim fdlg As OpenFileDialog = New OpenFileDialog() fdlg.Title = "Browse for the FTP List you wish to use." fdlg.InitialDirectory = Application.ExecutablePath fdlg.Filter = "All files (*.txt)|*.txt|txt files (*.txt)|*.txt" fdlg.FilterIndex = 2 fdlg.RestoreDirectory = True If fdlg.ShowDialog() = DialogResult.OK Then 'ListBox1.Items.AddRange(Split(My.Computer.FileSystem.ReadAllText(fdlg.FileName), vbNewLine)) TextBox1.Text = My.Computer.FileSystem.ReadAllText(fdlg.FileName) End If Dim tmp() As String = TextBox1.Text.Split(CChar(vbNewLine)) For Each line As String In tmp If line.Length > 1 Then TextBox1.AppendText(line & vbNewLine) End If Next TextBox1.Text = TextBox1.Text.Replace(" ", "") TextBox1.Text = TextBox1.Text.Replace("----------------------------------------------------------", vbNewLine) For Each item As String In NewArray ListBox1.Items.Add(item) Next Try For i = 0 To ListBox1.Items.Count - 1 If ListBox1.Items(i).Contains(dateCrap) Then ListBox1.Items.RemoveAt(i) End If Next Catch ex As Exception End Try Try For i = 0 To ListBox1.Items.Count - 1 If ListBox1.Items(i).Contains(IPcrap) Then ListBox1.Items.RemoveAt(i) End If Next Catch ex As Exception End Try Try For i = 0 To ListBox1.Items.Count - 1 If ListBox1.Items(i).Contains(pcCrap) Then ListBox1.Items.RemoveAt(i) End If Next Catch ex As Exception End Try Try For i = 0 To ListBox1.Items.Count - 1 If ListBox1.Items(i).Contains(programCrap) Then ListBox1.Items.RemoveAt(i) End If Next Catch ex As Exception End Try TextBox1.Text = "" For Each thing As Object In ListBox1.Items TextBox1.AppendText(thing.ToString & vbNewLine) Next End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) For i = 0 To ListBox1.SelectedItems.Count - 1 TextBox1.Text = TextBox1.Text & ListBox1.Items.Item(i).ToString() & vbNewLine Next End Sub End Class

    Read the article

  • How to make a VB exception handling for no value in a Textbox

    - by Twocold
    I want to catch an exception when user enter no value in a Textbox and try to process further by press a button, I know I can use "If else" statement to make it. but in terms of "Try and Catch" block, I dont know how. Here is the code sample. Dim NameString As String Try NameString = OperatorNameTextBox.Text Catch ex As ArgumentException MessageBox.Show("Enter a String Value") End Try

    Read the article

  • Wireless will not connect

    - by azz0r
    Hello, I have installed Ubuntu 10.10 on the same machine as my windows setup. However, it will not connect to my wireless network. It can see its there, it can attempt to connect, yet it will never connect. It will keep bringing up the password prompt everyso often. I have tried turning my security to WEP, I ended up turning it back to WPA2. It is set to AES (noted a few threads on google about that). Can you assist? I would love to dive into Ubuntu, but without the internet its pointless. --- lshw -C network --- *-network description: Ethernet interface product: RTL8111/8168B PCI Express Gigabit Ethernet controller vendor: Realtek Semiconductor Co., Ltd. physical id: 0 bus info: pci@0000:02:00.0 logical name: eth0 version: 02 serial: 00:1d:92:ea:cc:62 capacity: 1GB/s width: 64 bits clock: 33MHz capabilities: pm msi pciexpress msix vpd bus_master cap_list rom ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation configuration: autonegotiation=on broadcast=yes driver=r8168 driverversion=8.020.00-NAPI duplex=half latency=0 link=no multicast=yes port=twisted pair resources: irq:29 ioport:e800(size=256) memory:feaff000-feafffff memory:f8ff0000-f8ffffff(prefetchable) memory:feac0000-feadffff(prefetchable) *-network description: Wireless interface physical id: 1 logical name: wlan0 serial: 00:15:af:72:a4:38 capabilities: ethernet physical wireless configuration: broadcast=yes multicast=yes wireless=IEEE 802.11bgn --- iwconfig ---- lo no wireless extensions. eth0 no wireless extensions. wlan0 IEEE 802.11bgn ESSID:"Wuggawoo" Mode:Managed Frequency:2.437 GHz Access Point: Not-Associated Tx-Power=9 dBm Retry long limit:7 RTS thr:off Fragment thr:off Encryption key:off Power Management:on --- cat /etc/network/interfaces ---- auto lo iface lo inet loopback logs deamon.log --- Jan 19 04:17:09 ubuntu wpa_supplicant[1289]: Authentication with 94:44:52:0d:22:0d timed out. Jan 19 04:17:09 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: associating -> disconnected Jan 19 04:17:09 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: disconnected -> scanning Jan 19 04:17:11 ubuntu wpa_supplicant[1289]: WPS-AP-AVAILABLE Jan 19 04:17:11 ubuntu wpa_supplicant[1289]: Trying to associate with 94:44:52:0d:22:0d (SSID='Wuggawoo' freq=2437 MHz) Jan 19 04:17:11 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: scanning -> associating Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0/wireless): association took too long. Jan 19 04:17:12 ubuntu NetworkManager: <info> (wlan0): device state change: 5 -> 6 (reason 0) Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0/wireless): asking for new secrets Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled... Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started... Jan 19 04:17:12 ubuntu NetworkManager: <info> (wlan0): device state change: 6 -> 4 (reason 0) Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled... Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete. Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting... Jan 19 04:17:12 ubuntu NetworkManager: <info> (wlan0): device state change: 4 -> 5 (reason 0) Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0/wireless): connection 'Wuggawoo' has security, and secrets exist. No new secrets needed. Jan 19 04:17:12 ubuntu NetworkManager: <info> Config: added 'ssid' value 'Wuggawoo' Jan 19 04:17:12 ubuntu NetworkManager: <info> Config: added 'scan_ssid' value '1' Jan 19 04:17:12 ubuntu NetworkManager: <info> Config: added 'key_mgmt' value 'WPA-PSK' Jan 19 04:17:12 ubuntu NetworkManager: <info> Config: added 'psk' value '<omitted>' Jan 19 04:17:12 ubuntu NetworkManager: nm_setting_802_1x_get_pkcs11_engine_path: assertion `NM_IS_SETTING_802_1X (setting)' failed Jan 19 04:17:12 ubuntu NetworkManager: nm_setting_802_1x_get_pkcs11_module_path: assertion `NM_IS_SETTING_802_1X (setting)' failed Jan 19 04:17:12 ubuntu NetworkManager: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete. Jan 19 04:17:12 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: associating -> disconnected Jan 19 04:17:12 ubuntu NetworkManager: <info> Config: set interface ap_scan to 1 Jan 19 04:17:12 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: disconnected -> scanning Jan 19 04:17:13 ubuntu wpa_supplicant[1289]: WPS-AP-AVAILABLE Jan 19 04:17:13 ubuntu wpa_supplicant[1289]: Trying to associate with 94:44:52:0d:22:0d (SSID='Wuggawoo' freq=2437 MHz) Jan 19 04:17:13 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: scanning -> associating Jan 19 04:17:23 ubuntu wpa_supplicant[1289]: Authentication with 94:44:52:0d:22:0d timed out. Jan 19 04:17:23 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: associating -> disconnected Jan 19 04:17:23 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: disconnected -> scanning Jan 19 04:17:24 ubuntu AptDaemon: INFO: Initializing daemon Jan 19 04:17:25 ubuntu wpa_supplicant[1289]: WPS-AP-AVAILABLE Jan 19 04:17:25 ubuntu wpa_supplicant[1289]: Trying to associate with 94:44:52:0d:22:0d (SSID='Wuggawoo' freq=2437 MHz) Jan 19 04:17:25 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: scanning -> associating Jan 19 04:17:27 ubuntu NetworkManager: <info> wlan0: link timed out. --- kern.log --- Jan 19 04:18:11 ubuntu kernel: [ 142.420024] wlan0: direct probe to AP 94:44:52:0d:22:0d timed out Jan 19 04:18:13 ubuntu kernel: [ 144.333847] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 1) Jan 19 04:18:13 ubuntu kernel: [ 144.539996] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 2) Jan 19 04:18:13 ubuntu kernel: [ 144.750027] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 3) Jan 19 04:18:14 ubuntu kernel: [ 144.940022] wlan0: direct probe to AP 94:44:52:0d:22:0d timed out Jan 19 04:18:25 ubuntu kernel: [ 155.832995] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 1) Jan 19 04:18:25 ubuntu kernel: [ 156.030046] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 2) Jan 19 04:18:25 ubuntu kernel: [ 156.230039] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 3) Jan 19 04:18:25 ubuntu kernel: [ 156.430039] wlan0: direct probe to AP 94:44:52:0d:22:0d timed out --- syslog --- Jan 19 04:18:46 ubuntu wpa_supplicant[1289]: Authentication with 94:44:52:0d:22:0d timed out. Jan 19 04:18:46 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: associating -> disconnected Jan 19 04:18:46 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: disconnected -> scanning Jan 19 04:18:48 ubuntu wpa_supplicant[1289]: WPS-AP-AVAILABLE Jan 19 04:18:48 ubuntu wpa_supplicant[1289]: Trying to associate with 94:44:52:0d:22:0d (SSID='Wuggawoo' freq=2437 MHz) Jan 19 04:18:48 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: scanning -> associating Jan 19 04:18:48 ubuntu kernel: [ 178.833905] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 1) Jan 19 04:18:48 ubuntu kernel: [ 179.030035] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 2) Jan 19 04:18:48 ubuntu kernel: [ 179.230020] wlan0: direct probe to AP 94:44:52:0d:22:0d (try 3) Jan 19 04:18:48 ubuntu kernel: [ 179.433634] wlan0: direct probe to AP 94:44:52:0d:22:0d timed out lspci and lsusb lspci -- 00:00.0 Host bridge: Advanced Micro Devices [AMD] RS780 Host Bridge 00:02.0 PCI bridge: Advanced Micro Devices [AMD] RS780 PCI to PCI bridge (ext gfx port 0) 00:05.0 PCI bridge: Advanced Micro Devices [AMD] RS780 PCI to PCI bridge (PCIE port 1) 00:06.0 PCI bridge: Advanced Micro Devices [AMD] RS780 PCI to PCI bridge (PCIE port 2) 00:11.0 SATA controller: ATI Technologies Inc SB700/SB800 SATA Controller [AHCI mode] 00:12.0 USB Controller: ATI Technologies Inc SB700/SB800 USB OHCI0 Controller 00:12.1 USB Controller: ATI Technologies Inc SB700 USB OHCI1 Controller 00:12.2 USB Controller: ATI Technologies Inc SB700/SB800 USB EHCI Controller 00:13.0 USB Controller: ATI Technologies Inc SB700/SB800 USB OHCI0 Controller 00:13.1 USB Controller: ATI Technologies Inc SB700 USB OHCI1 Controller 00:13.2 USB Controller: ATI Technologies Inc SB700/SB800 USB EHCI Controller 00:14.0 SMBus: ATI Technologies Inc SBx00 SMBus Controller (rev 3a) 00:14.1 IDE interface: ATI Technologies Inc SB700/SB800 IDE Controller 00:14.2 Audio device: ATI Technologies Inc SBx00 Azalia (Intel HDA) 00:14.3 ISA bridge: ATI Technologies Inc SB700/SB800 LPC host controller 00:14.4 PCI bridge: ATI Technologies Inc SBx00 PCI to PCI Bridge 00:14.5 USB Controller: ATI Technologies Inc SB700/SB800 USB OHCI2 Controller 00:18.0 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] HyperTransport Configuration 00:18.1 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Address Map 00:18.2 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] DRAM Controller 00:18.3 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Miscellaneous Control 00:18.4 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Link Control 01:00.0 VGA compatible controller: nVidia Corporation G80 [GeForce 8800 GTS] (rev a2) 02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 02) 03:00.0 FireWire (IEEE 1394): JMicron Technology Corp. IEEE 1394 Host Controller -- lsusb -- Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 004 Device 003: ID 046d:c517 Logitech, Inc. LX710 Cordless Desktop Laser Bus 004 Device 002: ID 045e:0730 Microsoft Corp. Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 002 Device 003: ID 13d3:3247 IMC Networks 802.11 n/g/b Wireless LAN Adapter Bus 002 Device 002: ID 0718:0628 Imation Corp. Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 003: ID 046d:08c2 Logitech, Inc. QuickCam PTZ Bus 001 Device 002: ID 0424:2228 Standard Microsystems Corp. 9-in-2 Card Reader Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub With no security on my router I still can't connect, I get: Jan 19 15:58:01 ubuntu wpa_supplicant[1165]: Authentication with 94:44:52:0d:22:0d timed out. Jan 19 15:58:01 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: associating -> disconnected Jan 19 15:58:01 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: disconnected -> scanning Jan 19 15:58:02 ubuntu wpa_supplicant[1165]: WPS-AP-AVAILABLE Jan 19 15:58:02 ubuntu wpa_supplicant[1165]: Trying to associate with 94:44:52:0d:22:0d (SSID='Wuggawoo' freq=2437 MHz) Jan 19 15:58:02 ubuntu wpa_supplicant[1165]: Association request to the driver failed Jan 19 15:58:02 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: scanning -> associating Jan 19 15:58:05 ubuntu NetworkManager: <info> wlan0: link timed out. Jan 19 15:58:07 ubuntu wpa_supplicant[1165]: Authentication with 94:44:52:0d:22:0d timed out. Jan 19 15:58:07 ubuntu NetworkManager: <info> (wlan0): supplicant connection state: associating -> disconnected Jan 19 15:58:07 ubuntu NetworkManager: <info> (wlan0): supplicant connec

    Read the article

  • Python script is exiting with no output and I have no idea why

    - by Adam Tuttle
    I'm attempting to debug a Subversion post-commit hook that calls some python scripts. What I've been able to determine so far is that when I run post-commit.bat manually (I've created a wrapper for it to make it easier) everything succeeds, but when SVN runs it one particular step doesn't work. We're using CollabNet SVNServe, which I know from the documentation removes all environment variables. This had caused some problems earlier, but shouldn't be an issue now. Before Subversion calls a hook script, it removes all variables - including $PATH on Unix, and %PATH% on Windows - from the environment. Therefore, your script can only run another program if you spell out that program's absolute name. The relevant portion of post-commit.bat is: echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log set SITENAME=staging set SVNPATH=branches/staging/wwwroot/ "C:\Python3\python.exe" C:\svn-repos\company\hooks\svn2ftp.py ^ --svnUser="svnusername" ^ --svnPass="svnpassword" ^ --ftp-user=ftpuser ^ --ftp-password=ftppassword ^ --ftp-remote-dir=/ ^ --access-url=svn://10.0.100.6/company ^ --status-file="C:\svn-repos\company\hooks\svn2ftp-%SITENAME%.dat" ^ --project-directory=%SVNPATH% "staging.company.com" %1 %2 >> c:\svn-repos\company\hooks\svn2ftp.out.log echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log When I run post-commit.bat manually, for example: post-commit c:\svn-repos\company 12345, I see output like the following in svn2ftp.out.log: -------------------------- args1: c:\svn-repos\company args0: staging.company.com abspath: c:\svn-repos\company project_dir: branches/staging/wwwroot/ local_repos_path: c:\svn-repos\company getting youngest revision... done, up-to-date -------------------------- However, when I commit something to the repo and it runs automatically, the output is: -------------------------- -------------------------- svn2ftp.py is a bit long, so I apologize but here goes. I'll have some notes/disclaimers about its contents below it. #!/usr/bin/env python """Usage: svn2ftp.py [OPTION...] FTP-HOST REPOS-PATH Upload to FTP-HOST changes committed to the Subversion repository at REPOS-PATH. Uses svn diff --summarize to only propagate the changed files Options: -?, --help Show this help message. -u, --ftp-user=USER The username for the FTP server. Default: 'anonymous' -p, --ftp-password=P The password for the FTP server. Default: '@' -P, --ftp-port=X Port number for the FTP server. Default: 21 -r, --ftp-remote-dir=DIR The remote directory that is expected to resemble the repository project directory -a, --access-url=URL This is the URL that should be used when trying to SVN export files so that they can be uploaded to the FTP server -s, --status-file=PATH Required. This script needs to store the last successful revision that was transferred to the server. PATH is the location of this file. -d, --project-directory=DIR If the project you are interested in sending to the FTP server is not under the root of the repository (/), set this parameter. Example: -d 'project1/trunk/' This should NOT start with a '/'. 2008.5.2 CKS Fixed possible Windows-related bug with tempfile, where the script didn't have permission to write to the tempfile. Replaced this with a open()-created file created in the CWD. 2008.5.13 CKS Added error logging. Added exception for file-not-found errors when deleting files. 2008.5.14 CKS Change file open to 'rb' mode, to prevent Python's universal newline support from stripping CR characters, causing later comparisons between FTP and SVN to report changes. """ try: import sys, os import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='svn2ftp.debug.log', filemode='a' ) console = logging.StreamHandler() console.setLevel(logging.ERROR) logging.getLogger('').addHandler(console) import getopt, tempfile, smtplib, traceback, subprocess from io import StringIO import pysvn import ftplib import inspect except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) print(stack_trace) #end capture sys.exit(1) #defaults host = "" user = "anonymous" password = "@" port = 21 repo_path = "" local_repos_path = "" status_file = "" project_directory = "" remote_base_directory = "" toAddrs = "[email protected]" youngest_revision = "" def email(toAddrs, message, subject, fromAddr='[email protected]'): headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromAddr, toAddrs, subject) message = headers + message logging.info('sending email to %s...' % toAddrs) server = smtplib.SMTP('smtp.company.com') server.set_debuglevel(1) server.sendmail(fromAddr, toAddrs, message) server.quit() logging.info('email sent') def captureErrorMessage(e): sout = StringIO() traceback.print_exc(file=sout) errorMessage = '\n'+('*'*80)+('\n%s'%e)+('\n%s\n'%sout.getvalue())+('*'*80) return errorMessage def usage_and_exit(errmsg): """Print a usage message, plus an ERRMSG (if provided), then exit. If ERRMSG is provided, the usage message is printed to stderr and the script exits with a non-zero error code. Otherwise, the usage message goes to stdout, and the script exits with a zero errorcode.""" if errmsg is None: stream = sys.stdout else: stream = sys.stderr print(__doc__, file=stream) if errmsg: print("\nError: %s" % (errmsg), file=stream) sys.exit(2) sys.exit(0) def read_args(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision try: opts, args = getopt.gnu_getopt(sys.argv[1:], "?u:p:P:r:a:s:d:SU:SP:", ["help", "ftp-user=", "ftp-password=", "ftp-port=", "ftp-remote-dir=", "access-url=", "status-file=", "project-directory=", "svnUser=", "svnPass=" ]) except getopt.GetoptError as msg: usage_and_exit(msg) for opt, arg in opts: if opt in ("-?", "--help"): usage_and_exit() elif opt in ("-u", "--ftp-user"): user = arg elif opt in ("-p", "--ftp-password"): password = arg elif opt in ("-SU", "--svnUser"): svnUser = arg elif opt in ("-SP", "--svnPass"): svnPass = arg elif opt in ("-P", "--ftp-port"): try: port = int(arg) except ValueError as msg: usage_and_exit("Invalid value '%s' for --ftp-port." % (arg)) if port < 1 or port > 65535: usage_and_exit("Value for --ftp-port must be a positive integer less than 65536.") elif opt in ("-r", "--ftp-remote-dir"): remote_base_directory = arg elif opt in ("-a", "--access-url"): repo_path = arg elif opt in ("-s", "--status-file"): status_file = os.path.abspath(arg) elif opt in ("-d", "--project-directory"): project_directory = arg if len(args) != 3: print(str(args)) usage_and_exit("host and/or local_repos_path not specified (" + len(args) + ")") host = args[0] print("args1: " + args[1]) print("args0: " + args[0]) print("abspath: " + os.path.abspath(args[1])) local_repos_path = os.path.abspath(args[1]) print('project_dir:',project_directory) youngest_revision = int(args[2]) if status_file == "" : usage_and_exit("No status file specified") def main(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision read_args() #repository,fs_ptr #get youngest revision print("local_repos_path: " + local_repos_path) print('getting youngest revision...') #youngest_revision = fs.youngest_rev(fs_ptr) assert youngest_revision, "Unable to lookup youngest revision." last_sent_revision = get_last_revision() if youngest_revision == last_sent_revision: # no need to continue. we should be up to date. print('done, up-to-date') return if last_sent_revision or youngest_revision < 10: # Only compare revisions if the DAT file contains a valid # revision number. Otherwise we risk waiting forever while # we parse and uploading every revision in the repo in the case # where a repository is retroactively configured to sync with ftp. pysvn_client = pysvn.Client() pysvn_client.callback_get_login = get_login rev1 = pysvn.Revision(pysvn.opt_revision_kind.number, last_sent_revision) rev2 = pysvn.Revision(pysvn.opt_revision_kind.number, youngest_revision) summary = pysvn_client.diff_summarize(repo_path, rev1, repo_path, rev2, True, False) print('summary len:',len(summary)) if len(summary) > 0 : print('connecting to %s...' % host) ftp = FTPClient(host, user, password) print('connected to %s' % host) ftp.base_path = remote_base_directory print('set remote base directory to %s' % remote_base_directory) #iterate through all the differences between revisions for change in summary : #determine whether the path of the change is relevant to the path that is being sent, and modify the path as appropriate. print('change path:',change.path) ftp_relative_path = apply_basedir(change.path) print('ftp rel path:',ftp_relative_path) #only try to sync path if the path is in our project_directory if ftp_relative_path != "" : is_file = (change.node_kind == pysvn.node_kind.file) if str(change.summarize_kind) == "delete" : print("deleting: " + ftp_relative_path) try: ftp.delete_path("/" + ftp_relative_path, is_file) except ftplib.error_perm as e: if 'cannot find the' in str(e) or 'not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise elif str(change.summarize_kind) == "added" or str(change.summarize_kind) == "modified" : local_file = "" if is_file : local_file = svn_export_temp(pysvn_client, repo_path, rev2, change.path) print("uploading file: " + ftp_relative_path) ftp.upload_path("/" + ftp_relative_path, is_file, local_file) if is_file : os.remove(local_file) elif str(change.summarize_kind) == "normal" : print("skipping 'normal' element: " + ftp_relative_path) else : raise str("Unknown change summarize kind: " + str(change.summarize_kind) + ", path: " + ftp_relative_path) ftp.close() #write back the last revision that was synced print("writing last revision: " + str(youngest_revision)) set_last_revision(youngest_revision) # todo: undo def get_login(a,b,c,d): #arguments don't matter, we're always going to return the same thing try: return True, "svnUsername", "svnPassword", True except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) #end capture sys.exit(1) #functions for persisting the last successfully synced revision def get_last_revision(): if os.path.isfile(status_file) : f=open(status_file, 'r') line = f.readline() f.close() try: i = int(line) except ValueError: i = 0 else: i = 0 f = open(status_file, 'w') f.write(str(i)) f.close() return i def set_last_revision(rev) : f = open(status_file, 'w') f.write(str(rev)) f.close() #augmented ftp client class that can work off a base directory class FTPClient(ftplib.FTP) : def __init__(self, host, username, password) : self.base_path = "" self.current_path = "" ftplib.FTP.__init__(self, host, username, password) def cwd(self, path) : debug_path = path if self.current_path == "" : self.current_path = self.pwd() print("pwd: " + self.current_path) if not os.path.isabs(path) : debug_path = self.base_path + "<" + path path = os.path.join(self.current_path, path) elif self.base_path != "" : debug_path = self.base_path + ">" + path.lstrip("/") path = os.path.join(self.base_path, path.lstrip("/")) path = os.path.normpath(path) #by this point the path should be absolute. if path != self.current_path : print("change from " + self.current_path + " to " + debug_path) ftplib.FTP.cwd(self, path) self.current_path = path else : print("staying put : " + self.current_path) def cd_or_create(self, path) : assert os.path.isabs(path), "absolute path expected (" + path + ")" try: self.cwd(path) except ftplib.error_perm as e: for folder in path.split('/'): if folder == "" : self.cwd("/") continue try: self.cwd(folder) except: print("mkd: (" + path + "):" + folder) self.mkd(folder) self.cwd(folder) def upload_path(self, path, is_file, local_path) : if is_file: (path, filename) = os.path.split(path) self.cd_or_create(path) # Use read-binary to avoid universal newline support from stripping CR characters. f = open(local_path, 'rb') self.storbinary("STOR " + filename, f) f.close() else: self.cd_or_create(path) def delete_path(self, path, is_file) : (path, filename) = os.path.split(path) print("trying to delete: " + path + ", " + filename) self.cwd(path) try: if is_file : self.delete(filename) else: self.delete_path_recursive(filename) except ftplib.error_perm as e: if 'The system cannot find the' in str(e) or '550 File not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise def delete_path_recursive(self, path): if path == "/" : raise "WARNING: trying to delete '/'!" for node in self.nlst(path) : if node == path : #it's a file. delete and return self.delete(path) return if node != "." and node != ".." : self.delete_path_recursive(os.path.join(path, node)) try: self.rmd(path) except ftplib.error_perm as msg : sys.stderr.write("Error deleting directory " + os.path.join(self.current_path, path) + " : " + str(msg)) # apply the project_directory setting def apply_basedir(path) : #remove any leading stuff (in this case, "trunk/") and decide whether file should be propagated if not path.startswith(project_directory) : return "" return path.replace(project_directory, "", 1) def svn_export_temp(pysvn_client, base_path, rev, path) : # Causes access denied error. Couldn't deduce Windows-perm issue. # It's possible Python isn't garbage-collecting the open file-handle in time for pysvn to re-open it. # Regardless, just generating a simple filename seems to work. #(fd, dest_path) = tempfile.mkstemp() dest_path = tmpName = '%s.tmp' % __file__ exportPath = os.path.join(base_path, path).replace('\\','/') print('exporting %s to %s' % (exportPath, dest_path)) pysvn_client.export( exportPath, dest_path, force=False, revision=rev, native_eol=None, ignore_externals=False, recurse=True, peg_revision=rev ) return dest_path if __name__ == "__main__": logging.info('svnftp.start') try: main() logging.info('svnftp.done') except Exception as e: # capture the location of the error for debug purposes frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace[:-1]) print(stack_trace) # end capture error_text = '\nFATAL EXCEPTION!!!\n'+captureErrorMessage(e) subject = "ALERT: SVN2FTP Error" message = """An Error occurred while trying to FTP an SVN commit. repo_path = %(repo_path)s\n local_repos_path = %(local_repos_path)s\n project_directory = %(project_directory)s\n remote_base_directory = %(remote_base_directory)s\n error_text = %(error_text)s """ % globals() email(toAddrs, message, subject) logging.error(e) Notes/Disclaimers: I have basically no python training so I'm learning as I go and spending lots of time reading docs to figure stuff out. The body of get_login is in a try block because I was getting strange errors saying there was an unhandled exception in callback_get_login. Never figured out why, but it seems fine now. Let sleeping dogs lie, right? The username and password for get_login are currently hard-coded (but correct) just to eliminate variables and try to change as little as possible at once. (I added the svnuser and svnpass arguments to the existing argument parsing.) So that's where I am. I can't figure out why on earth it's not printing anything into svn2ftp.out.log. If you're wondering, the output for one of these failed attempts in svn2ftp.debug.log is: 2012-09-06 15:18:12,496 INFO svnftp.start 2012-09-06 15:18:12,496 INFO svnftp.done And it's no different on a successful run. So there's nothing useful being logged. I'm lost. I've gone way down the rabbit hole on this one, and don't know where to go from here. Any ideas?

    Read the article

  • Problem with hadoop start-dfs.sh

    - by user288501
    I installed and configured hadoop on my Ubuntu 14.04 server, virtualized inside of hyper-v, however I am getting an issue when i run start-dfs.sh root@sUbuntu01:/var/log# start-dfs.sh 14/06/04 15:27:08 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Starting namenodes on [OpenJDK 64-Bit Server VM warning: You have loaded library /usr/local/hadoop/lib/native/libhadoop.so.1.0.0 which might have disabled stack guard. The VM will try to fix the stack guard now. It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'. localhost] sed: -e expression #1, char 6: unknown option to `s' -c: Unknown cipher type 'cd' localhost: Ubuntu 14.04 LTS localhost: starting namenode, logging to /usr/local/hadoop/logs/hadoop-root-namenode-sUbuntu01.out noexecstack'.: ssh: Could not resolve hostname noexecstack'.: Name or service not known '-z: ssh: Could not resolve hostname '-z: Name or service not known 'execstack: ssh: Could not resolve hostname 'execstack: Name or service not known disabled: ssh: Could not resolve hostname disabled: Name or service not known with: ssh: Could not resolve hostname with: Name or service not known have: ssh: Could not resolve hostname have: Name or service not known VM: ssh: Could not resolve hostname vm: Name or service not known stack: ssh: Could not resolve hostname stack: Name or service not known guard: ssh: Could not resolve hostname guard: Name or service not known fix: ssh: Could not resolve hostname fix: Name or service not known VM: ssh: Could not resolve hostname vm: Name or service not known the: ssh: Could not resolve hostname the: Name or service not known to: ssh: Could not resolve hostname to: Name or service not known warning:: ssh: Could not resolve hostname warning:: Name or service not known it: ssh: Could not resolve hostname it: Name or service not known now.: ssh: Could not resolve hostname now.: Name or service not known library: ssh: Could not resolve hostname library: Name or service not known will: ssh: Could not resolve hostname will: Name or service not known link: ssh: Could not resolve hostname link: Name or service not known or: ssh: Could not resolve hostname or: Name or service not known It's: ssh: Could not resolve hostname it's: Name or service not known <libfile>',: ssh: Could not resolve hostname <libfile>',: Name or service not known which: ssh: connect to host which port 22: Connection timed out have: ssh: connect to host have port 22: Connection timed out you: ssh: connect to host you port 22: Connection timed out try: ssh: connect to host try port 22: Connection timed out the: ssh: connect to host the port 22: Connection timed out highly: ssh: connect to host highly port 22: Connection timed out might: ssh: connect to host might port 22: Connection timed out loaded: ssh: connect to host loaded port 22: Connection timed out You: ssh: connect to host you port 22: Connection timed out guard.: ssh: connect to host guard. port 22: Connection timed out library: ssh: connect to host library port 22: Connection timed out Server: ssh: connect to host server port 22: Connection timed out fix: ssh: connect to host fix port 22: Connection timed out The: ssh: connect to host the port 22: Connection timed out recommended: ssh: connect to host recommended port 22: Connection timed out that: ssh: connect to host that port 22: Connection timed out stack: ssh: connect to host stack port 22: Connection timed out OpenJDK: ssh: connect to host openjdk port 22: Connection timed out 64-Bit: ssh: connect to host 64-bit port 22: Connection timed out with: ssh: connect to host with port 22: Connection timed out localhost: Ubuntu 14.04 LTS localhost: starting datanode, logging to /usr/local/hadoop/logs/hadoop-root-datanode-sUbuntu01.out localhost: OpenJDK 64-Bit Server VM warning: You have loaded library /usr/local/hadoop/lib/native/libhadoop.so.1.0.0 which might have disabled stack guard. The VM will try to fix the stack guard now. localhost: It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'. Starting secondary namenodes [OpenJDK 64-Bit Server VM warning: You have loaded library /usr/local/hadoop/lib/native/libhadoop.so.1.0.0 which might have disabled stack guard. The VM will try to fix the stack guard now. It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'. 0.0.0.0] sed: -e expression #1, char 6: unknown option to `s' warning:: ssh: Could not resolve hostname warning:: Name or service not known -c: Unknown cipher type 'cd' It's: ssh: Could not resolve hostname it's: Name or service not known 'execstack: ssh: Could not resolve hostname 'execstack: Name or service not known '-z: ssh: Could not resolve hostname '-z: Name or service not known 0.0.0.0: Ubuntu 14.04 LTS 0.0.0.0: starting secondarynamenode, logging to /usr/local/hadoop/logs/hadoop-root-secondarynamenode-sUbuntu01.out 0.0.0.0: OpenJDK 64-Bit Server VM warning: You have loaded library /usr/local/hadoop/lib/native/libhadoop.so.1.0.0 which might have disabled stack guard. The VM will try to fix the stack guard now. 0.0.0.0: It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'. noexecstack'.: ssh: Could not resolve hostname noexecstack'.: Name or service not known <libfile>',: ssh: Could not resolve hostname <libfile>',: Name or service not known link: ssh: Could not resolve hostname link: No address associated with hostname it: ssh: Could not resolve hostname it: No address associated with hostname to: ssh: connect to host to port 22: Connection timed out or: ssh: connect to host or port 22: Connection timed out you: ssh: connect to host you port 22: Connection timed out guard.: ssh: connect to host guard. port 22: Connection timed out VM: ssh: connect to host vm port 22: Connection timed out stack: ssh: connect to host stack port 22: Connection timed out library: ssh: connect to host library port 22: Connection timed out Server: ssh: connect to host server port 22: Connection timed out might: ssh: connect to host might port 22: Connection timed out stack: ssh: connect to host stack port 22: Connection timed out You: ssh: connect to host you port 22: Connection timed out now.: ssh: connect to host now. port 22: Connection timed out disabled: ssh: connect to host disabled port 22: Connection timed out have: ssh: connect to host have port 22: Connection timed out will: ssh: connect to host will port 22: Connection timed out The: ssh: connect to host the port 22: Connection timed out have: ssh: connect to host have port 22: Connection timed out try: ssh: connect to host try port 22: Connection timed out the: ssh: connect to host the port 22: Connection timed out guard: ssh: connect to host guard port 22: Connection timed out the: ssh: connect to host the port 22: Connection timed out recommended: ssh: connect to host recommended port 22: Connection timed out with: ssh: connect to host with port 22: Connection timed out library: ssh: connect to host library port 22: Connection timed out 64-Bit: ssh: connect to host 64-bit port 22: Connection timed out fix: ssh: connect to host fix port 22: Connection timed out which: ssh: connect to host which port 22: Connection timed out VM: ssh: connect to host vm port 22: Connection timed out OpenJDK: ssh: connect to host openjdk port 22: Connection timed out fix: ssh: connect to host fix port 22: Connection timed out highly: ssh: connect to host highly port 22: Connection timed out that: ssh: connect to host that port 22: Connection timed out with: ssh: connect to host with port 22: Connection timed out loaded: ssh: connect to host loaded port 22: Connection timed out 14/06/04 15:36:02 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Any advice?

    Read the article

  • XMLHttpRequest error in IE, works without issue in Chrome/FF

    - by culov
    function addRequest(req) { try { request = new XMLHttpRequest(); } catch (e) { try{ request = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try { request = new ActiveXObject("Microsoft.XMLHttp"); } catch (e) { alert("XMLHttpRequest error: " + e); } } } request.open("GET", req, true); request.send(null); return request; } As you can see, it IE apparently fails all 3 ways in which I try to make the request. I've been doing plenty of searches to try and find what may be the issue, but by all accounts ive read, the code ive posted above should work. i havent used jquery for AJAX, but ive seen it recommended when others have had issues with httprequest objects. could i just replace the mess above with a couple lines of jquery and assume that it will take care of IE's ugliness? Thanks!

    Read the article

  • Optimizing a thread safe Java NIO / Serialization / FIFO Queue [migrated]

    - by trialcodr
    I've written a thread safe, persistent FIFO for Serializable items. The reason for reinventing the wheel is that we simply can't afford any third party dependencies in this project and want to keep this really simple. The problem is it isn't fast enough. Most of it is undoubtedly due to reading and writing directly to disk but I think we should be able to squeeze a bit more out of it anyway. Any ideas on how to improve the performance of the 'take'- and 'add'-methods? /** * <code>DiskQueue</code> Persistent, thread safe FIFO queue for * <code>Serializable</code> items. */ public class DiskQueue<ItemT extends Serializable> { public static final int EMPTY_OFFS = -1; public static final int LONG_SIZE = 8; public static final int HEADER_SIZE = LONG_SIZE * 2; private InputStream inputStream; private OutputStream outputStream; private RandomAccessFile file; private FileChannel channel; private long offs = EMPTY_OFFS; private long size = 0; public DiskQueue(String filename) { try { boolean fileExists = new File(filename).exists(); file = new RandomAccessFile(filename, "rwd"); if (fileExists) { size = file.readLong(); offs = file.readLong(); } else { file.writeLong(size); file.writeLong(offs); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } channel = file.getChannel(); inputStream = Channels.newInputStream(channel); outputStream = Channels.newOutputStream(channel); } /** * Add item to end of queue. */ public void add(ItemT item) { try { synchronized (this) { channel.position(channel.size()); ObjectOutputStream s = new ObjectOutputStream(outputStream); s.writeObject(item); s.flush(); size++; file.seek(0); file.writeLong(size); if (offs == EMPTY_OFFS) { offs = HEADER_SIZE; file.writeLong(offs); } notify(); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Clears overhead by moving the remaining items up and shortening the file. */ public synchronized void defrag() { if (offs > HEADER_SIZE && size > 0) { try { long totalBytes = channel.size() - offs; ByteBuffer buffer = ByteBuffer.allocateDirect((int) totalBytes); channel.position(offs); for (int bytes = 0; bytes < totalBytes;) { int res = channel.read(buffer); if (res == -1) { throw new IOException("Failed to read data into buffer"); } bytes += res; } channel.position(HEADER_SIZE); buffer.flip(); for (int bytes = 0; bytes < totalBytes;) { int res = channel.write(buffer); if (res == -1) { throw new IOException("Failed to write buffer to file"); } bytes += res; } offs = HEADER_SIZE; file.seek(LONG_SIZE); file.writeLong(offs); file.setLength(HEADER_SIZE + totalBytes); } catch (IOException e) { throw new RuntimeException(e); } } } /** * Returns the queue overhead in bytes. */ public synchronized long overhead() { return (offs == EMPTY_OFFS) ? 0 : offs - HEADER_SIZE; } /** * Returns the first item in the queue, blocks if queue is empty. */ public ItemT peek() throws InterruptedException { block(); synchronized (this) { if (offs != EMPTY_OFFS) { return readItem(); } } return peek(); } /** * Returns the number of remaining items in queue. */ public synchronized long size() { return size; } /** * Removes and returns the first item in the queue, blocks if queue is empty. */ public ItemT take() throws InterruptedException { block(); try { synchronized (this) { if (offs != EMPTY_OFFS) { ItemT result = readItem(); size--; offs = channel.position(); file.seek(0); if (offs == channel.size()) { truncate(); } file.writeLong(size); file.writeLong(offs); return result; } } return take(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Throw away all items and reset the file. */ public synchronized void truncate() { try { offs = EMPTY_OFFS; file.setLength(HEADER_SIZE); size = 0; } catch (IOException e) { throw new RuntimeException(e); } } /** * Block until an item is available. */ protected void block() throws InterruptedException { while (offs == EMPTY_OFFS) { try { synchronized (this) { wait(); file.seek(LONG_SIZE); offs = file.readLong(); } } catch (IOException e) { throw new RuntimeException(e); } } } /** * Read and return item. */ @SuppressWarnings("unchecked") protected ItemT readItem() { try { channel.position(offs); return (ItemT) new ObjectInputStream(inputStream).readObject(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }

    Read the article

  • How 404 error asp.net mvc 2 IIS 7?

    - by Dmitriy
    Hello! I tried to catch 404 errors like this... But when i try to load http://localhost:11415/wfwe/wefwe/ - all good work. When i try to load http://localhost:11415/order/ - fail (with error The RouteData must contain an item named 'action' with a non-empty string value.) When i try to load http://localhost:11415/Images/ - fail with error File does not exist My routes: routes.Add("Order", new LowercaseRoute("Order/{action}/{id}", new RouteValueDictionary( new { controller = "Order", action = "", id = UrlParameter.Optional }), new MvcRouteHandler())); routes.Add("NotFound", new LowercaseRoute("{*url}", new RouteValueDictionary( new { controller = "Pages", action = "Http404", }), new MvcRouteHandler())); Why route NotFound - don't catch all 404 error. And When i try to upload to my hosting and try 404 i get this error (NotFound route not work at all) 404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable. I work with this all day, but nothig... please help me

    Read the article

  • Fastest way to move records from a oracle DB into MS sql server after processing

    - by user347748
    Hi.. Ok this is the scenario...I have a table in Oracle that acts like a queue... A VB.net program reads the queue and calls a stored proc in MS SQL Server that processes and then inserts the message into another SQL server table and then deletes the record from the oracle table. We use a datareader to read the records from Oracle and then call the stored proc for each of the records. The program seems to be a little slow. The stored procedure itself isnt slow. The SP by itself when called in a loop can process about 2000 records in 20 seconds. BUt when called from the .Net program, the execution time is about 5 records per second. I have seen that most of the time consumed is in calling the stored procedure and waiting for it to return. Is there a better way of doing this? Here is a snippet of the actual code Function StartDataXfer() As Boolean Dim status As Boolean = False Try SqlConn.Open() OraConn.Open() c.ErrorLog(Now.ToString & "--Going to Get the messages from oracle", 1) If GetMsgsFromOracle() Then c.ErrorLog(Now.ToString & "--Got messages from oracle", 1) If ProcessMessages() Then c.ErrorLog(Now.ToString & "--Finished Processing all messages in the queue", 0) status = True Else c.ErrorLog(Now.ToString & "--Failed to Process all messages in the queue", 0) status = False End If Else status = True End If StartDataXfer = status Catch ex As Exception Finally SqlConn.Close() OraConn.Close() End Try End Function Private Function GetMsgsFromOracle() As Boolean Try OraDataAdapter = New OleDb.OleDbDataAdapter OraDataTable = New System.Data.DataTable OraSelCmd = New OleDb.OleDbCommand GetMsgsFromOracle = False With OraSelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = GetMsgSql End With OraDataAdapter.SelectCommand = OraSelCmd OraDataAdapter.Fill(OraDataTable) If OraDataTable.Rows.Count > 0 Then GetMsgsFromOracle = True End If Catch ex As Exception GetMsgsFromOracle = False End Try End Function Private Function ProcessMessages() As Boolean Try ProcessMessages = False PrepareSQLInsert() PrepOraDel() i = 0 Dim Method As Integer Dim OraDataRow As DataRow c.ErrorLog(Now.ToString & "--Going to call message sending procedure", 2) For Each OraDataRow In OraDataTable.Rows With OraDataRow Method = GetMethod(.Item(0)) SQLInsCmd.Parameters("RelLifeTime").Value = c.RelLifetime SQLInsCmd.Parameters("Param1").Value = Nothing SQLInsCmd.Parameters("ID").Value = GenerateTransactionID() ' Nothing SQLInsCmd.Parameters("UID").Value = Nothing SQLInsCmd.Parameters("Param").Value = Nothing SQLInsCmd.Parameters("Credit").Value = 0 SQLInsCmd.ExecuteNonQuery() 'check the return value If SQLInsCmd.Parameters("ReturnValue").Value = 1 And SQLInsCmd.Parameters("OutPutParam").Value = 0 Then 'success 'delete the input record from the source table once it is logged c.ErrorLog(Now.ToString & "--Moved record successfully", 2) OraDataAdapter.DeleteCommand.Parameters("P(0)").Value = OraDataRow.Item(6) OraDataAdapter.DeleteCommand.ExecuteNonQuery() c.ErrorLog(Now.ToString & "--Deleted record successfully", 2) OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Committed record successfully", 2) i = i + 1 Else 'failure c.ErrorLog(Now.ToString & "--Failed to exec: " & c.DestIns & "Status: " & SQLInsCmd.Parameters("OutPutParam").Value & " and TrackId: " & SQLInsCmd.Parameters("TrackID").Value.ToString, 0) End If If File.Exists("stop.txt") Then c.ErrorLog(Now.ToString & "--Stop File Found", 1) 'ProcessMessages = True 'Exit Function Exit For End If End With Next OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Updated Oracle Table", 1) c.ErrorLog(Now.ToString & "--Moved " & i & " records from Oracle to SQL Table", 1) ProcessMessages = True Catch ex As Exception ProcessMessages = False c.ErrorLog(Now.ToString & "--MoveMsgsToSQL: " & ex.Message, 0) Finally OraDataTable.Clear() OraDataTable.Dispose() OraDataAdapter.Dispose() OraDelCmd.Dispose() OraDelCmd = Nothing OraSelCmd = Nothing OraDataTable = Nothing OraDataAdapter = Nothing End Try End Function Public Function GenerateTransactionID() As Int64 Dim SeqNo As Int64 Dim qry As String Dim SqlTransCmd As New OleDb.OleDbCommand qry = " select seqno from StoreSeqNo" SqlTransCmd.CommandType = CommandType.Text SqlTransCmd.Connection = SqlConn SqlTransCmd.CommandText = qry SeqNo = SqlTransCmd.ExecuteScalar If SeqNo > 2147483647 Then qry = "update StoreSeqNo set seqno=1" SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = 1 Else qry = "update StoreSeqNo set seqno=" & SeqNo + 1 SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = SeqNo End If End Function Private Function PrepareSQLInsert() As Boolean 'function to prepare the insert statement for the insert into the SQL stmt using 'the sql procedure SMSProcessAndDispatch Try Dim dr As DataRow SQLInsCmd = New OleDb.OleDbCommand With SQLInsCmd .CommandType = CommandType.StoredProcedure .Connection = SqlConn .CommandText = SQLInsProc .Parameters.Add("ReturnValue", OleDb.OleDbType.Integer) .Parameters("ReturnValue").Direction = ParameterDirection.ReturnValue .Parameters.Add("OutPutParam", OleDb.OleDbType.Integer) .Parameters("OutPutParam").Direction = ParameterDirection.Output .Parameters.Add("TrackID", OleDb.OleDbType.VarChar, 70) .Parameters.Add("RelLifeTime", OleDb.OleDbType.TinyInt) .Parameters("RelLifeTime").Direction = ParameterDirection.Input .Parameters.Add("Param1", OleDb.OleDbType.VarChar, 160) .Parameters("Param1").Direction = ParameterDirection.Input .Parameters.Add("TransID", OleDb.OleDbType.VarChar, 70) .Parameters("TransID").Direction = ParameterDirection.Input .Parameters.Add("UID", OleDb.OleDbType.VarChar, 20) .Parameters("UID").Direction = ParameterDirection.Input .Parameters.Add("Param", OleDb.OleDbType.VarChar, 160) .Parameters("Param").Direction = ParameterDirection.Input .Parameters.Add("CheckCredit", OleDb.OleDbType.Integer) .Parameters("CheckCredit").Direction = ParameterDirection.Input .Prepare() End With Catch ex As Exception c.ErrorLog(Now.ToString & "--PrepareSQLInsert: " & ex.Message) End Try End Function Private Function PrepOraDel() As Boolean OraDelCmd = New OleDb.OleDbCommand Try PrepOraDel = False With OraDelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = DelSrcSQL .Parameters.Add("P(0)", OleDb.OleDbType.VarChar, 160) 'RowID .Parameters("P(0)").Direction = ParameterDirection.Input .Prepare() End With OraDataAdapter.DeleteCommand = OraDelCmd PrepOraDel = True Catch ex As Exception PrepOraDel = False End Try End Function WHat i would like to know is, if there is anyway to speed up this program? Any ideas/suggestions would be highly appreciated... Regardss, Chetan

    Read the article

  • Fastest way to move records from an Oracle database into SQL Server

    - by user347748
    Ok this is the scenario... I have a table in Oracle that acts like a queue... A VB.net program reads the queue and calls a stored proc in SQL Server that processes and then inserts the message into another SQL Server table and then deletes the record from the oracle table. We use a DataReader to read the records from Oracle and then call the stored proc for each of the records. The program seems to be a little slow. The stored procedure itself isn't slow. The SP by itself when called in a loop can process about 2000 records in 20 seconds. But when called from the .Net program, the execution time is about 5 records per second. I have seen that most of the time consumed is in calling the stored procedure and waiting for it to return. Is there a better way of doing this? Here is a snippet of the actual code Function StartDataXfer() As Boolean Dim status As Boolean = False Try SqlConn.Open() OraConn.Open() c.ErrorLog(Now.ToString & "--Going to Get the messages from oracle", 1) If GetMsgsFromOracle() Then c.ErrorLog(Now.ToString & "--Got messages from oracle", 1) If ProcessMessages() Then c.ErrorLog(Now.ToString & "--Finished Processing all messages in the queue", 0) status = True Else c.ErrorLog(Now.ToString & "--Failed to Process all messages in the queue", 0) status = False End If Else status = True End If StartDataXfer = status Catch ex As Exception Finally SqlConn.Close() OraConn.Close() End Try End Function Private Function GetMsgsFromOracle() As Boolean Try OraDataAdapter = New OleDb.OleDbDataAdapter OraDataTable = New System.Data.DataTable OraSelCmd = New OleDb.OleDbCommand GetMsgsFromOracle = False With OraSelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = GetMsgSql End With OraDataAdapter.SelectCommand = OraSelCmd OraDataAdapter.Fill(OraDataTable) If OraDataTable.Rows.Count > 0 Then GetMsgsFromOracle = True End If Catch ex As Exception GetMsgsFromOracle = False End Try End Function Private Function ProcessMessages() As Boolean Try ProcessMessages = False PrepareSQLInsert() PrepOraDel() i = 0 Dim Method As Integer Dim OraDataRow As DataRow c.ErrorLog(Now.ToString & "--Going to call message sending procedure", 2) For Each OraDataRow In OraDataTable.Rows With OraDataRow Method = GetMethod(.Item(0)) SQLInsCmd.Parameters("RelLifeTime").Value = c.RelLifetime SQLInsCmd.Parameters("Param1").Value = Nothing SQLInsCmd.Parameters("ID").Value = GenerateTransactionID() ' Nothing SQLInsCmd.Parameters("UID").Value = Nothing SQLInsCmd.Parameters("Param").Value = Nothing SQLInsCmd.Parameters("Credit").Value = 0 SQLInsCmd.ExecuteNonQuery() 'check the return value If SQLInsCmd.Parameters("ReturnValue").Value = 1 And SQLInsCmd.Parameters("OutPutParam").Value = 0 Then 'success 'delete the input record from the source table once it is logged c.ErrorLog(Now.ToString & "--Moved record successfully", 2) OraDataAdapter.DeleteCommand.Parameters("P(0)").Value = OraDataRow.Item(6) OraDataAdapter.DeleteCommand.ExecuteNonQuery() c.ErrorLog(Now.ToString & "--Deleted record successfully", 2) OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Committed record successfully", 2) i = i + 1 Else 'failure c.ErrorLog(Now.ToString & "--Failed to exec: " & c.DestIns & "Status: " & SQLInsCmd.Parameters("OutPutParam").Value & " and TrackId: " & SQLInsCmd.Parameters("TrackID").Value.ToString, 0) End If If File.Exists("stop.txt") Then c.ErrorLog(Now.ToString & "--Stop File Found", 1) 'ProcessMessages = True 'Exit Function Exit For End If End With Next OraDataAdapter.Update(OraDataTable) c.ErrorLog(Now.ToString & "--Updated Oracle Table", 1) c.ErrorLog(Now.ToString & "--Moved " & i & " records from Oracle to SQL Table", 1) ProcessMessages = True Catch ex As Exception ProcessMessages = False c.ErrorLog(Now.ToString & "--MoveMsgsToSQL: " & ex.Message, 0) Finally OraDataTable.Clear() OraDataTable.Dispose() OraDataAdapter.Dispose() OraDelCmd.Dispose() OraDelCmd = Nothing OraSelCmd = Nothing OraDataTable = Nothing OraDataAdapter = Nothing End Try End Function Public Function GenerateTransactionID() As Int64 Dim SeqNo As Int64 Dim qry As String Dim SqlTransCmd As New OleDb.OleDbCommand qry = " select seqno from StoreSeqNo" SqlTransCmd.CommandType = CommandType.Text SqlTransCmd.Connection = SqlConn SqlTransCmd.CommandText = qry SeqNo = SqlTransCmd.ExecuteScalar If SeqNo > 2147483647 Then qry = "update StoreSeqNo set seqno=1" SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = 1 Else qry = "update StoreSeqNo set seqno=" & SeqNo + 1 SqlTransCmd.CommandText = qry SqlTransCmd.ExecuteNonQuery() GenerateTransactionID = SeqNo End If End Function Private Function PrepareSQLInsert() As Boolean 'function to prepare the insert statement for the insert into the SQL stmt using 'the sql procedure SMSProcessAndDispatch Try Dim dr As DataRow SQLInsCmd = New OleDb.OleDbCommand With SQLInsCmd .CommandType = CommandType.StoredProcedure .Connection = SqlConn .CommandText = SQLInsProc .Parameters.Add("ReturnValue", OleDb.OleDbType.Integer) .Parameters("ReturnValue").Direction = ParameterDirection.ReturnValue .Parameters.Add("OutPutParam", OleDb.OleDbType.Integer) .Parameters("OutPutParam").Direction = ParameterDirection.Output .Parameters.Add("TrackID", OleDb.OleDbType.VarChar, 70) .Parameters.Add("RelLifeTime", OleDb.OleDbType.TinyInt) .Parameters("RelLifeTime").Direction = ParameterDirection.Input .Parameters.Add("Param1", OleDb.OleDbType.VarChar, 160) .Parameters("Param1").Direction = ParameterDirection.Input .Parameters.Add("TransID", OleDb.OleDbType.VarChar, 70) .Parameters("TransID").Direction = ParameterDirection.Input .Parameters.Add("UID", OleDb.OleDbType.VarChar, 20) .Parameters("UID").Direction = ParameterDirection.Input .Parameters.Add("Param", OleDb.OleDbType.VarChar, 160) .Parameters("Param").Direction = ParameterDirection.Input .Parameters.Add("CheckCredit", OleDb.OleDbType.Integer) .Parameters("CheckCredit").Direction = ParameterDirection.Input .Prepare() End With Catch ex As Exception c.ErrorLog(Now.ToString & "--PrepareSQLInsert: " & ex.Message) End Try End Function Private Function PrepOraDel() As Boolean OraDelCmd = New OleDb.OleDbCommand Try PrepOraDel = False With OraDelCmd .CommandType = CommandType.Text .Connection = OraConn .CommandText = DelSrcSQL .Parameters.Add("P(0)", OleDb.OleDbType.VarChar, 160) 'RowID .Parameters("P(0)").Direction = ParameterDirection.Input .Prepare() End With OraDataAdapter.DeleteCommand = OraDelCmd PrepOraDel = True Catch ex As Exception PrepOraDel = False End Try End Function WHat i would like to know is, if there is anyway to speed up this program? Any ideas/suggestions would be highly appreciated... Regardss, Chetan

    Read the article

  • Delphi Editbox causing unexplainable errors...

    - by NeoNMD
    On a form I have 8 edit boxes that I do the exact same thing with. They are arranged in 2 sets of 4, one is Upper and the other is Lower. I kept getting errors clearing all the edit boxes so I went through clearing them 1 by 1 and found that 1 of the edit boxes just didnt work and when I tried to run the program and change that exit box it caused the debugger to jump to a point in the code with the database (even though the edit boxes had nothing to do with the database and they arent in a procedure or stack with a database in it) and say the program has access violation there. So I then removed all mention of that edit box and the code worked perfectly again, so I deleted that edit box, copied and pasted another edit box and left all values the same, then went through my code and copied the code from the other sections and simply renamed it for the new Edit box and it STILL causes an error even though it is entirely new. I cannot figure it out so I ask you all, what the hell? The editbox in question is "Edit1" unit DefinitionCoreV2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SQLiteTable3, StdCtrls; type TDefinitionFrm = class(TForm) GrpCompetition: TGroupBox; CmbCompSele: TComboBox; BtnCompetitionAdd: TButton; BtnCompetitionUpdate: TButton; BtnCompetitionRevert: TButton; GrpCompetitionDetails: TGroupBox; LblCompetitionIDTitle: TLabel; EdtCompID: TEdit; LblCompetitionDescriptionTitle: TLabel; EdtCompDesc: TEdit; LblCompetitionNotesTitle: TLabel; EdtCompNote: TEdit; LblCompetitionLocationTitle: TLabel; EdtCompLoca: TEdit; BtnCompetitionDelete: TButton; GrpSection: TGroupBox; LblSectionID: TLabel; LblGender: TLabel; LblAge: TLabel; LblLevel: TLabel; LblWeight: TLabel; LblType: TLabel; LblHeight: TLabel; LblCompetitionID: TLabel; BtnSectionAdd: TButton; EdtSectionID: TEdit; CmbGender: TComboBox; BtnSectionUpdate: TButton; BtnSectionRevert: TButton; CmbAgeRange: TComboBox; CmbLevelRange: TComboBox; CmbType: TComboBox; CmbWeightRange: TComboBox; CmbHeightRange: TComboBox; EdtSectCompetitionID: TEdit; BtnSectionDelete: TButton; GrpSectionDetails: TGroupBox; EdtLowerAge: TEdit; EdtLowerWeight: TEdit; EdtLowerHeight: TEdit; EdtUpperAge: TEdit; EdtUpperLevel: TEdit; EdtUpperWeight: TEdit; EdtUpperHeight: TEdit; LblAgeRule: TLabel; LblLevelRule: TLabel; LblWeightRule: TLabel; LblHeightRule: TLabel; LblCompetitionSelect: TLabel; LblSectionSelect: TLabel; CmbSectSele: TComboBox; Edit1: TEdit; procedure FormCreate(Sender: TObject); procedure BtnCompetitionAddClick(Sender: TObject); procedure CmbCompSeleChange(Sender: TObject); procedure BtnCompetitionUpdateClick(Sender: TObject); procedure BtnCompetitionRevertClick(Sender: TObject); procedure BtnCompetitionDeleteClick(Sender: TObject); procedure CmbSectSeleChange(Sender: TObject); procedure BtnSectionAddClick(Sender: TObject); procedure BtnSectionUpdateClick(Sender: TObject); procedure BtnSectionRevertClick(Sender: TObject); procedure BtnSectionDeleteClick(Sender: TObject); procedure CmbAgeRangeChange(Sender: TObject); procedure CmbLevelRangeChange(Sender: TObject); procedure CmbWeightRangeChange(Sender: TObject); procedure CmbHeightRangeChange(Sender: TObject); private procedure UpdateCmbCompSele; procedure AddComp; procedure RevertComp; procedure AddSect; procedure RevertSect; procedure UpdateCmbSectSele; procedure ClearSect; { Private declarations } public { Public declarations } end; var DefinitionFrm: TDefinitionFrm; implementation {$R *.dfm} procedure TDefinitionFrm.UpdateCmbCompSele; var slDBpath: string; sldb : TSQLiteDatabase; sltb : TSQLiteTable; sCompTitle : string; bNext : boolean; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try sltb := slDb.GetTable('SELECT * FROM CompetitionTable'); try CmbCompSele.Items.Clear; Repeat begin sCompTitle:=sltb.FieldAsString(sltb.FieldIndex['CompetitionID'])+':'+sltb.FieldAsString(sltb.FieldIndex['Description']); CmbCompSele.Items.Add(sCompTitle); bNext := sltb.Next; end; Until sltb.EOF; finally sltb.Free; end; finally sldb.Free; end; end; procedure TDefinitionFrm.UpdateCmbSectSele; var slDBpath: string; sldb : TSQLiteDatabase; sltb : TSQLiteTable; sSQL : string; sSectTitle : string; bNext : boolean; bLast : boolean; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try sltb := slDb.GetTable('SELECT * FROM SectionTable WHERE CompetitionID = '+EdtCompID.text); If sltb.RowCount =0 then begin sltb := slDb.GetTable('SELECT * FROM SectionTable'); bLast:= sltb.MoveLast; sSQL := 'INSERT INTO SectionTable(SectionID,CompetitionID,Gender,Type) VALUES ('+IntToStr(sltb.FieldAsInteger(sltb.FieldIndex['SectionID'])+1)+','+EdtCompID.text+',1,1)'; sldb.ExecSQL(sSQL); sltb := slDb.GetTable('SELECT * FROM SectionTable WHERE CompetitionID = '+EdtCompID.text); end; try CmbSectSele.Items.Clear; Repeat begin sSectTitle:=sltb.FieldAsString(sltb.FieldIndex['SectionID'])+':'+sltb.FieldAsString(sltb.FieldIndex['Type'])+':'+sltb.FieldAsString(sltb.FieldIndex['Gender'])+':'+sltb.FieldAsString(sltb.FieldIndex['Age'])+':'+sltb.FieldAsString(sltb.FieldIndex['Level'])+':'+sltb.FieldAsString(sltb.FieldIndex['Weight'])+':'+sltb.FieldAsString(sltb.FieldIndex['Height']); CmbSectSele.Items.Add(sSectTitle); //CmbType.Items.Strings[sltb.FieldAsInteger(sltb.FieldIndex['Type'])] Works but has logic errors bNext := sltb.Next; end; Until sltb.EOF; finally sltb.Free; end; finally sldb.Free; end; end; procedure TDefinitionFrm.AddComp; var slDBpath: string; sSQL : string; sldb : TSQLiteDatabase; sltb : TSQLiteTable; bLast : boolean; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try sltb := slDb.GetTable('SELECT * FROM CompetitionTable'); try bLast:= sltb.MoveLast; sSQL := 'INSERT INTO CompetitionTable(CompetitionID,Description) VALUES ('+IntToStr(sltb.FieldAsInteger(sltb.FieldIndex['CompetitionID'])+1)+',"New Competition")'; sldb.ExecSQL(sSQL); finally sltb.Free; end; finally sldb.Free; end; UpdateCmbCompSele; end; procedure TDefinitionFrm.AddSect; var slDBpath: string; sSQL : string; sldb : TSQLiteDatabase; sltb : TSQLiteTable; bLast : boolean; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try sltb := slDb.GetTable('SELECT * FROM SectionTable'); try bLast:= sltb.MoveLast; sSQL := 'INSERT INTO SectionTable(SectionID,CompetitionID,Gender,Type) VALUES ('+IntToStr(sltb.FieldAsInteger(sltb.FieldIndex['SectionID'])+1)+','+EdtCompID.text+',1,1)'; sldb.ExecSQL(sSQL); finally sltb.Free; end; finally sldb.Free; end; UpdateCmbSectSele; end; procedure TDefinitionFrm.RevertComp; var slDBpath: string; sldb : TSQLiteDatabase; sltb : TSQLiteTable; iID : integer; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try If CmbCompSele.Text <> '' then begin iID := StrToInt(Copy(CmbCompSele.Text,0,Pos(':',CmbCompSele.Text)-1)); sltb := slDb.GetTable('SELECT * FROM CompetitionTable WHERE CompetitionID='+IntToStr(iID))//ItemIndex starts at 0, CompID at 1 end else sltb := slDb.GetTable('SELECT * FROM CompetitionTable WHERE CompetitionID=1'); try EdtCompID.Text:=sltb.FieldAsString(sltb.FieldIndex['CompetitionID']); EdtCompLoca.Text:=sltb.FieldAsString(sltb.FieldIndex['Location']); EdtCompDesc.Text:=sltb.FieldAsString(sltb.FieldIndex['Description']); EdtCompNote.Text:=sltb.FieldAsString(sltb.FieldIndex['Notes']); finally sltb.Free; end; finally sldb.Free; end; end; procedure TDefinitionFrm.RevertSect; var slDBpath: string; sldb : TSQLiteDatabase; sltb : TSQLiteTable; iID : integer; sTemp : string; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try If CmbCompSele.Text <> '' then begin iID := StrToInt(Copy(CmbSectSele.Text,0,Pos(':',CmbSectSele.Text)-1)); sltb := slDb.GetTable('SELECT * FROM SectionTable WHERE SectionID='+IntToStr(iID));//ItemIndex starts at 0, CompID at 1 end else sltb := slDb.GetTable('SELECT * FROM SectionTable WHERE CompetitionID='+EdtCompID.Text); try EdtSectionID.Text:=sltb.FieldAsString(sltb.FieldIndex['SectionID']); EdtSectCompetitionID.Text:=sltb.FieldAsString(sltb.FieldIndex['CompetitionID']); Case sltb.FieldAsInteger(sltb.FieldIndex['Type']) of 1 : CmbType.ItemIndex:=0; 2 : CmbType.ItemIndex:=0; 3 : CmbType.ItemIndex:=1; 4 : CmbType.ItemIndex:=1; end; Case sltb.FieldAsInteger(sltb.FieldIndex['Gender']) of 1 : CmbGender.ItemIndex:=0; 2 : CmbGender.ItemIndex:=1; 3 : CmbGender.ItemIndex:=2; end; sTemp := sltb.FieldAsString(sltb.FieldIndex['Age']); if sTemp <> '' then begin //Decode end else begin LblAgeRule.Hide; EdtLowerAge.Text :=''; EdtLowerAge.Hide; EdtUpperAge.Text :=''; EdtUpperAge.Hide; end; sTemp := sltb.FieldAsString(sltb.FieldIndex['Level']); if sTemp <> '' then begin //Decode end else begin LblLevelRule.Hide; Edit1.Text :=''; Edit1.Hide; EdtUpperLevel.Text :=''; EdtUpperLevel.Hide; end; sTemp := sltb.FieldAsString(sltb.FieldIndex['Weight']); if sTemp <> '' then begin //Decode end else begin LblWeightRule.Hide; EdtLowerWeight.Text :=''; EdtLowerWeight.Hide; EdtUpperWeight.Text :=''; EdtUpperWeight.Hide; end; sTemp := sltb.FieldAsString(sltb.FieldIndex['Height']); if sTemp <> '' then begin //Decode end else begin LblHeightRule.Hide; EdtLowerHeight.Text :=''; EdtLowerHeight.Hide; EdtUpperHeight.Text :=''; EdtUpperHeight.Hide; end; finally sltb.Free; end; finally sldb.Free; end; end; procedure TDefinitionFrm.BtnCompetitionAddClick(Sender: TObject); begin AddComp end; procedure TDefinitionFrm.ClearSect; begin CmbSectSele.Clear; EdtSectionID.Text:=''; EdtSectCompetitionID.Text:=''; CmbType.Clear; CmbGender.Clear; CmbAgeRange.Clear; EdtLowerAge.Text:=''; EdtUpperAge.Text:=''; CmbLevelRange.Clear; Edit1.Text:=''; EdtUpperLevel.Text:=''; CmbWeightRange.Clear; EdtLowerWeight.Text:=''; EdtUpperWeight.Text:=''; CmbHeightRange.Clear; EdtLowerHeight.Text:=''; EdtUpperHeight.Text:=''; end; procedure TDefinitionFrm.CmbCompSeleChange(Sender: TObject); begin If CmbCompSele.ItemIndex <> -1 then begin RevertComp; GrpSection.Enabled:=True; CmbSectSele.Clear; ClearSect; UpdateCmbSectSele; end; end; procedure TDefinitionFrm.BtnCompetitionUpdateClick(Sender: TObject); var slDBpath: string; sSQL : string; sldb : TSQLiteDatabase; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try sSQL:= 'UPDATE CompetitionTable SET Description="'+EdtCompDesc.Text+'",Location="'+EdtCompLoca.Text+'",Notes="'+EdtCompNote.Text+'" WHERE CompetitionID ="'+EdtCompID.Text+'";'; sldb.ExecSQL(sSQL); finally sldb.Free; end; end; procedure TDefinitionFrm.BtnCompetitionRevertClick(Sender: TObject); begin RevertComp; end; procedure TDefinitionFrm.BtnCompetitionDeleteClick(Sender: TObject); var slDBpath: string; sSQL : string; sldb : TSQLiteDatabase; iID : integer; begin If CmbCompSele.Text <> '' then begin If (CmbCompSele.Text[1] ='1') and (CmbCompSele.Text[2] =':') then begin MessageDlg('Deleting the last record is a very bad idea :/',mtInformation,[mbOK],0); end else begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try iID := StrToInt(Copy(CmbCompSele.Text,0,Pos(':',CmbCompSele.Text)-1)); sSQL:= 'DELETE FROM SectionTable WHERE CompetitionID='+IntToStr(iID)+';'; sldb.ExecSQL(sSQL); sSQL:= 'DELETE FROM CompetitionTable WHERE CompetitionID='+IntToStr(iID)+';'; sldb.ExecSQL(sSQL); finally sldb.Free; end; CmbCompSele.ItemIndex:=0; UpdateCmbCompSele; RevertComp; CmbCompSele.Text:='Select Competition'; end; end; end; procedure TDefinitionFrm.FormCreate(Sender: TObject); begin UpdateCmbCompSele; end; procedure TDefinitionFrm.CmbSectSeleChange(Sender: TObject); begin RevertSect; end; procedure TDefinitionFrm.BtnSectionAddClick(Sender: TObject); begin AddSect; end; procedure TDefinitionFrm.BtnSectionUpdateClick(Sender: TObject); //change fields values var slDBpath: string; sSQL : string; sldb : TSQLiteDatabase; iTypeCode : integer; iGenderCode : integer; sAgeStr, sLevelStr, sWeightStr, sHeightStr : string; begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try If CmbType.Text='Fighting' then iTypeCode := 1 else iTypeCode := 3; If CmbGender.Text='Male' then iGenderCode := 1 else if CmbGender.Text='Female' then iGenderCode := 2 else iGenderCode := 3; Case CmbAgeRange.ItemIndex of 0:sAgeStr := 'o-'+EdtLowerAge.Text; 1:sAgeStr := 'u-'+EdtLowerAge.Text; 2:sAgeStr := EdtLowerAge.Text+'-'+EdtUpperAge.Text; end; Case CmbLevelRange.ItemIndex of 0:sLevelStr := 'o-'+Edit1.Text; 1:sLevelStr := 'u-'+Edit1.Text; 2:sLevelStr := Edit1.Text+'-'+EdtUpperLevel.Text; end; Case CmbWeightRange.ItemIndex of 0:sWeightStr := 'o-'+EdtLowerWeight.Text; 1:sWeightStr := 'u-'+EdtLowerWeight.Text; 2:sWeightStr := EdtLowerWeight.Text+'-'+EdtUpperWeight.Text; end; Case CmbHeightRange.ItemIndex of 0:sHeightStr := 'o-'+EdtLowerHeight.Text; 1:sHeightStr := 'u-'+EdtLowerHeight.Text; 2:sHeightStr := EdtLowerHeight.Text+'-'+EdtUpperHeight.Text; end; sSQL:= 'UPDATE SectionTable SET Type="'+IntToStr(iTypeCode)+'",Gender="'+IntToStr(iGenderCode)+'" WHERE SectionID ="'+EdtSectionID.Text+'";'; sldb.ExecSQL(sSQL); finally sldb.Free; end; end; procedure TDefinitionFrm.BtnSectionRevertClick(Sender: TObject); begin RevertSect; end; procedure TDefinitionFrm.BtnSectionDeleteClick(Sender: TObject); var slDBpath: string; sSQL : string; sldb : TSQLiteDatabase; begin If CmbSectSele.Text[1] ='1' then begin MessageDlg('Deleting the last record is a very bad idea :/',mtInformation,[mbOK],0); end else begin slDBPath := ExtractFilepath(application.exename)+ 'Competitions.db'; if not FileExists(slDBPath) then begin MessageDlg('Competitions.db does not exist.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try sSQL:= 'DELETE FROM SectionTable WHERE SectionID='+CmbSectSele.Text[1]+';'; sldb.ExecSQL(sSQL); finally sldb.Free; end; CmbSectSele.ItemIndex:=0; UpdateCmbSectSele; RevertSect; CmbSectSele.Text:='Select Competition'; end; end; procedure TDefinitionFrm.CmbAgeRangeChange(Sender: TObject); begin Case CmbAgeRange.ItemIndex of 0: begin EdtLowerAge.Show; LblAgeRule.Caption:='Over and including'; LblAgeRule.Show; EdtUpperAge.Hide; end; 1: begin EdtLowerAge.Show; LblAgeRule.Caption:='Under and including'; LblAgeRule.Show; EdtUpperAge.Hide; end; 2: begin EdtLowerAge.Show; LblAgeRule.Caption:='LblAgeRule'; LblAgeRule.Hide; EdtUpperAge.Show; end; end; end; procedure TDefinitionFrm.CmbLevelRangeChange(Sender: TObject); begin Case CmbLevelRange.ItemIndex of 0: begin Edit1.Show; LblLevelRule.Caption:='Over and including'; LblLevelRule.Show; EdtUpperLevel.Hide; end; 1: begin Edit1.Show; LblLevelRule.Caption:='Under and including'; LblLevelRule.Show; EdtUpperLevel.Hide; end; 2: begin Edit1.Show; LblLevelRule.Caption:='LblLevelRule'; LblLevelRule.Hide; EdtUpperLevel.Show; end; end; end; procedure TDefinitionFrm.CmbWeightRangeChange(Sender: TObject); begin Case CmbWeightRange.ItemIndex of 0: begin EdtLowerWeight.Show; LblWeightRule.Caption:='Over and including'; LblWeightRule.Show; EdtUpperWeight.Hide; end; 1: begin EdtLowerWeight.Show; LblWeightRule.Caption:='Under and including'; LblWeightRule.Show; EdtUpperWeight.Hide; end; 2: begin EdtLowerWeight.Show; LblWeightRule.Caption:='LblWeightRule'; LblWeightRule.Hide; EdtUpperWeight.Show; end; end; end; procedure TDefinitionFrm.CmbHeightRangeChange(Sender: TObject); begin Case CmbHeightRange.ItemIndex of 0: begin EdtLowerHeight.Show; LblHeightRule.Caption:='Over and including'; LblHeightRule.Show; EdtUpperHeight.Hide; end; 1: begin EdtLowerHeight.Show; LblHeightRule.Caption:='Under and including'; LblHeightRule.Show; EdtUpperHeight.Hide; end; 2: begin EdtLowerHeight.Show; LblHeightRule.Caption:='LblHeightRule'; LblHeightRule.Hide; EdtUpperHeight.Show; end; end; end; end.

    Read the article

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