Search Results

Search found 2946 results on 118 pages for 'ex umbris'.

Page 6/118 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • How to load the SQL data into several ComboBox easily, am i doing the correctly or is there another way

    - by Dominic Deepan.d
    I have a Combobox to fill the data for City, State and PinCode these combobox is dopdown list and the user will pick it. and it loads once the form opens. Here is the CODE: /// CODE TO BRING A DATA FROM SQL INTO THE FORM DROP LIST /// To fill the sates from States Table cn = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True"); cmd= new SqlCommand("select * from TblState",cn); cn.Open(); SqlDataReader dr; try { dr = cmd.ExecuteReader(); while (dr.Read()) { SelectState.Items.Add(dr["State"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { cn.Close(); } //To fill the Cities from City Table cn1 = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True"); cmd1 = new SqlCommand("SELECT * FROM TblCity", cn); cn.Open(); SqlDataReader ds; try { ds = cmd1.ExecuteReader(); while (ds.Read()) { SelectCity.Items.Add(ds["City"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { cn1.Close(); } // To fill the Data in the Pincode from the City Table cn2 = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True"); cmd2 = new SqlCommand("SELECT (Pincode) FROM TblCity ", cn2); cn2.Open(); SqlDataReader dm; try { dm = cmd2.ExecuteReader(); while (dm.Read()) { SelectPinCode.Items.Add(dm["Pincode"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { cn2.Close(); } its kinda Big, i am doing the same steps for all the combo-box, but is there a way i can merge it in a simple way.

    Read the article

  • Utility that helps in file locking - expert tips wanted

    - by maix
    I've written a subclass of file that a) provides methods to conveniently lock it (using fcntl, so it only supports unix, which is however OK for me atm) and b) when reading or writing asserts that the file is appropriately locked. Now I'm not an expert at such stuff (I've just read one paper [de] about it) and would appreciate some feedback: Is it secure, are there race conditions, are there other things that could be done better … Here is the code: from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN, LOCK_NB class LockedFile(file): """ A wrapper around `file` providing locking. Requires a shared lock to read and a exclusive lock to write. Main differences: * Additional methods: lock_ex, lock_sh, unlock * Refuse to read when not locked, refuse to write when not locked exclusivly. * mode cannot be `w` since then the file would be truncated before it could be locked. You have to lock the file yourself, it won't be done for you implicitly. Only you know what lock you need. Example usage:: def get_config(): f = LockedFile(CONFIG_FILENAME, 'r') f.lock_sh() config = parse_ini(f.read()) f.close() def set_config(key, value): f = LockedFile(CONFIG_FILENAME, 'r+') f.lock_ex() config = parse_ini(f.read()) config[key] = value f.truncate() f.write(make_ini(config)) f.close() """ def __init__(self, name, mode='r', *args, **kwargs): if 'w' in mode: raise ValueError('Cannot open file in `w` mode') super(LockedFile, self).__init__(name, mode, *args, **kwargs) self.locked = None def lock_sh(self, **kwargs): """ Acquire a shared lock on the file. If the file is already locked exclusively, do nothing. :returns: Lock status from before the call (one of 'sh', 'ex', None). :param nonblocking: Don't wait for the lock to be available. """ if self.locked == 'ex': return # would implicitly remove the exclusive lock return self._lock(LOCK_SH, **kwargs) def lock_ex(self, **kwargs): """ Acquire an exclusive lock on the file. :returns: Lock status from before the call (one of 'sh', 'ex', None). :param nonblocking: Don't wait for the lock to be available. """ return self._lock(LOCK_EX, **kwargs) def unlock(self): """ Release all locks on the file. Flushes if there was an exclusive lock. :returns: Lock status from before the call (one of 'sh', 'ex', None). """ if self.locked == 'ex': self.flush() return self._lock(LOCK_UN) def _lock(self, mode, nonblocking=False): flock(self, mode | bool(nonblocking) * LOCK_NB) before = self.locked self.locked = {LOCK_SH: 'sh', LOCK_EX: 'ex', LOCK_UN: None}[mode] return before def _assert_read_lock(self): assert self.locked, "File is not locked" def _assert_write_lock(self): assert self.locked == 'ex', "File is not locked exclusively" def read(self, *args): self._assert_read_lock() return super(LockedFile, self).read(*args) def readline(self, *args): self._assert_read_lock() return super(LockedFile, self).readline(*args) def readlines(self, *args): self._assert_read_lock() return super(LockedFile, self).readlines(*args) def xreadlines(self, *args): self._assert_read_lock() return super(LockedFile, self).xreadlines(*args) def __iter__(self): self._assert_read_lock() return super(LockedFile, self).__iter__() def next(self): self._assert_read_lock() return super(LockedFile, self).next() def write(self, *args): self._assert_write_lock() return super(LockedFile, self).write(*args) def writelines(self, *args): self._assert_write_lock() return super(LockedFile, self).writelines(*args) def flush(self): self._assert_write_lock() return super(LockedFile, self).flush() def truncate(self, *args): self._assert_write_lock() return super(LockedFile, self).truncate(*args) def close(self): self.unlock() return super(LockedFile, self).close() (the example in the docstring is also my current use case for this) Thanks for having read until down here, and possibly even answering :)

    Read the article

  • windows PATH not working for network drive

    - by Brendan Abel
    I'm using an autorun.bat to append some directory paths to the Windows PATH variable so that I can use a few tools and bat scripts within cmd.exe I'm running into a problem where the above isn't working on a network drive. Ex. Using a program called mycmd.exe Ex.1 (this works) C:\folder\mycmd.exe SET PATH=%PATH%;C:\folder Ex. 2 (doesn't work) H:\folder\mycmd.exe SET PATH=%PATH%;H:\folder

    Read the article

  • Getting the number of frames from a video in Android

    - by Jay Patel
    I want to get the number of frames from a video. I'm using the following code: package com.vidualtest; import java.io.File; import java.io.FileDescriptor; import android.app.Activity; import android.graphics.Bitmap; import android.media.MediaMetadataRetriever; import android.os.Bundle; import android.os.Environment; import android.widget.ImageView; public class VidualTestActivity extends Activity { /** Called when the activity is first created. */ File file; ImageView img; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); img = (ImageView) findViewById(R.id.img); File sdcard = Environment.getExternalStorageDirectory(); file = new File(sdcard, "myvid.mp4"); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(file.getAbsolutePath()); img.setImageBitmap(retriever.getFrameAtTime(10000,MediaMetadataRetriever.OPTION_CLOSEST)); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } catch (RuntimeException ex) { ex.printStackTrace(); } finally { try { retriever.release(); } catch (RuntimeException ex) { } } } } In getFrameAtTime() I'm passing different static time values like 10000, 20000, etc. in milliseconds, but still I'm getting the same frame from the video. My goal is to get different frames with a different time interval.

    Read the article

  • nginx block URI request but allow internal directory

    - by Mike Anders
    I'm new to nginx from apache. I'm trying to simply block the URIs: /_mydir/* = / (redirect) But, I want to rewrite: /ex/(.*)$ = /_mydir/$1 I have tried: location /ex/ { rewrite ^/ex/(.*)$ /_mydir/$1 last; } location /_mydir { rewrite ^/_mydir/(.*)$ http://$http_host/ redirect; } But what always happens is once I block the '/_mydir' directory the rewrite is also blocked. I have also tried: location /_mydir/ { internal; } This also ends up blocking the rewrite. All help is greatly appreciated, thanks. UPDATE: I fixed this problem using: rewrite ^/ex/(.*)$ /_mydir/$1 break;

    Read the article

  • python: what are efficient techniques to deal with deeply nested data in a flexible manner?

    - by AlexandreS
    My question is not about a specific code snippet but more general, so please bear with me: How should I organize the data I'm analyzing, and which tools should I use to manage it? I'm using python and numpy to analyse data. Because the python documentation indicates that dictionaries are very optimized in python, and also due to the fact that the data itself is very structured, I stored it in a deeply nested dictionary. Here is a skeleton of the dictionary: the position in the hierarchy defines the nature of the element, and each new line defines the contents of a key in the precedent level: [AS091209M02] [AS091209M01] [AS090901M06] ... [100113] [100211] [100128] [100121] [R16] [R17] [R03] [R15] [R05] [R04] [R07] ... [1263399103] ... [ImageSize] [FilePath] [Trials] [Depth] [Frames] [Responses] ... [N01] [N04] ... [Sequential] [Randomized] [Ch1] [Ch2] Edit: To explain a bit better my data set: [individual] ex: [AS091209M02] [imaging session (date string)] ex: [100113] [Region imaged] ex: [R16] [timestamp of file] ex [1263399103] [properties of file] ex: [Responses] [regions of interest in image ] ex [N01] [format of data] ex [Sequential] [channel of acquisition: this key indexes an array of values] ex [Ch1] The type of operations I perform is for instance to compute properties of the arrays (listed under Ch1, Ch2), pick up arrays to make a new collection, for instance analyze responses of N01 from region 16 (R16) of a given individual at different time points, etc. This structure works well for me and is very fast, as promised. I can analyze the full data set pretty quickly (and the dictionary is far too small to fill up my computer's ram : half a gig). My problem comes from the cumbersome manner in which I need to program the operations of the dictionary. I often have stretches of code that go like this: for mk in dic.keys(): for rgk in dic[mk].keys(): for nk in dic[mk][rgk].keys(): for ik in dic[mk][rgk][nk].keys(): for ek in dic[mk][rgk][nk][ik].keys(): #do something which is ugly, cumbersome, non reusable, and brittle (need to recode it for any variant of the dictionary). I tried using recursive functions, but apart from the simplest applications, I ran into some very nasty bugs and bizarre behaviors that caused a big waste of time (it does not help that I don't manage to debug with pdb in ipython when I'm dealing with deeply nested recursive functions). In the end the only recursive function I use regularly is the following: def dicExplorer(dic, depth = -1, stp = 0): '''prints the hierarchy of a dictionary. if depth not specified, will explore all the dictionary ''' if depth - stp == 0: return try : list_keys = dic.keys() except AttributeError: return stp += 1 for key in list_keys: else: print '+%s> [\'%s\']' %(stp * '---', key) dicExplorer(dic[key], depth, stp) I know I'm doing this wrong, because my code is long, noodly and non-reusable. I need to either use better techniques to flexibly manipulate the dictionaries, or to put the data in some database format (sqlite?). My problem is that since I'm (badly) self-taught in regards to programming, I lack practical experience and background knowledge to appreciate the options available. I'm ready to learn new tools (SQL, object oriented programming), whatever it takes to get the job done, but I am reluctant to invest my time and efforts into something that will be a dead end for my needs. So what are your suggestions to tackle this issue, and be able to code my tools in a more brief, flexible and re-usable manner?

    Read the article

  • How do I solve this indexOutOfBoundsException in my server send/receive thread?

    - by Stefan Schouten
    I am creating a multiplayer game in Java with a server and multiple clients. Everything runs perfectly, until I press the Kick-button in the server to kick a client. Error at receive thread of server, after kicking the first person who joined out of three: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) > at networktest.Server$3.run(Server.java:186) at java.lang.Thread.run(Thread.java:722) The pointed line is the ois = new ObjectInputStream where I send datatype. The server kicks the first person perfectly, but removes the second one in the list too, with an error of java.lang.ClassCastException. server receive: private static Thread receive = new Thread() { @Override public void run() { ObjectInputStream ois; while (true) { for (int i = 0; i < list_sockets.size(); i++) { try { ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); int receive_state = (Integer) ois.readObject(); // receive state ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); byte datatype = (byte) ois.readObject(); // receive datatype if(datatype == 2){ ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); ChatLine chatLine = (ChatLine) ois.readObject(); // receive ChatLine } else if (datatype == 0){ ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); DataPackage dp = (DataPackage) ois.readObject(); // receive dp list_data.set(i, dp); } if (receive_state == 1) // Client Disconnected by User { disconnectClient(i); i--; } } catch (Exception ex) // Client Disconnected (Client Didn't Notify Server About Disconnecting) { System.err.println("Error @ receive:"); ex.printStackTrace(); disconnectClient(i); i--; } } try { this.sleep(3); } catch (InterruptedException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } } }; user send: Thread send = new Thread() { public void run() { ObjectOutputStream oos; byte datatype = 0; while (connected){ if (socket != null){ try { DataPackage dp = new DataPackage(); dp.x = Client.player.x; dp.y = Client.player.y; dp.username = username; dp.charType = charType; dp.walking = (byte)Client.player.walking; if (Client.outputChatLine.line != null) datatype = 2; else { datatype = 0; } oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(Integer.valueOf(Client.this.state)); // send state oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(Byte.valueOf(datatype)); // send datatype if (datatype == 2) { oos.reset(); oos.writeObject(Client.outputChatLine); Client.outputChatLine = new ChatLine(); } else { oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(dp); } if (Client.this.state == 1) { connected = false; socket = null; JOptionPane.showMessageDialog(null, "Client Disconnected", "Info", 1); System.exit(0); } } catch (Exception ex){} } try { this.sleep(2); } catch (InterruptedException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } } }; disconnect client method: public static void disconnectClient(int index) { try { list_clients_model.removeElementAt(index); list_client_states.remove(index); list_data.remove(index); list_sockets.remove(index); } catch (Exception ex) {} } Does anyone know how to solve this?

    Read the article

  • Permission based Authorization vs. Role based Authorization - Best Practices - 11g

    - by Prakash Yamuna
    In previous blog posts here and here I have alluded to the support in OWSM for Permission based authorization and Role based authorization support. Recently I was having a conversation with an internal team in Oracle looking to use OWSM for their Web Services security needs and one of the topics was around - When to use permission based authorization vs. role based authorization? As in most scenarios the answer is it depends! There are trade-offs involved in using the two approaches and you need to understand the trade-offs and you need to understand which trade-offs are better for your scenario. Role based Authorization: Simple to use. Just create a new custom OWSM policy and specify the role in the policy (using EM Fusion Middleware Control). Inconsistent if you have multiple type of resources in an application (ex: EJBs, Web Apps, Web Services) - ex: the model for securing EJBs with roles or the model for securing Web App roles - is inconsistent. Since the model is inconsistent, tooling is also fairly inconsistent. Achieving this use-case using JDeveloper is slightly complex - since JDeveloper does not directly support creating OWSM custom policies. Permission based Authorization: More complex. You need to attach both an OWSM policy and create OPSS Permission authorization policies. (Note: OWSM leverages OPSS Permission based Authorization support). More appropriate if you have multiple type of resources in an application (ex: EJBs, Web Apps, Web Services) and want a consistent authorization model. Consistent Tooling for managing authorization across different resources (ex: EM Fusion Middleware Control). Better Lifecycle support in terms of T2P, etc. Achieving this use-case using JDeveloper is slightly complex - since JDeveloper does not directly support creating/editing OPSS Permission based authorization policies.

    Read the article

  • How do you setup Postfix/Dovecot/MySQL to not look for local accounts?

    - by thiesdiggity
    I am having an issue with one of my Postfix/Dovecot mail servers and I'm unsure how to fix the problem. I will try to explain it in detail, here it goes: I have an Ubuntu server setup using Virtual hosting with Postfix, Dovecot and MySQL. We have one domain setup as a virtual domain, for this example I am going to use mail.example.com. Under that domain we have one email address. I have another server (MS Exchange) setup using another one of my sub-domains, ex.example.com. The problem is that when I SMTP into the account on mail.example.com and try to send an email to an account on ex.example.com, I get the email returned back to us with an "unknown host" error. Now, I know that the mail.example.com server can resolve the ex.example.com domain because I can ping/dig while SSH'd into it. I can also log into Postfix via Telnet and send an email to an ex.example.com mailbox. I'm guessing that it has something to do with Postfix/Dovecot looking locally for the domain in the virtual domain list because of the tld domain (example.com)? If that's the case, how do I get Postfix/Dovecot to only look locally for the entire URL (mail.example.com) and if it doesn't find it, send it to the correct server by looking up the MX/A records (which I know exist and are setup correctly)? I have been working on this all day and any guidance would be GREATLY appreciated! Thanks for your time!

    Read the article

  • jQuery 1.4.4 - issue with attr('selected', null)

    - by Renso
    Issue: The code below worked before under version jQuery 1.4.2 but when I upgraded to version 1.4.4 it no longer worked as expected - it did not unselect the list box item, only setting "selectd" worked:         _handleClick: function(elem) {             var self = this; var initElem = this.element;             var checked = $(elem).attr('checked');             var myId = elem.attr('id').replace(initElem.attr('id') + '_chk_', '');             initElem.children('option[value=' + myId + ']').attr('selected', function() {                 if (checked) {                     return 'selected';                 } else { return null; }             });             if ($.isFunction(self.options.onItemSelected)) {                 try {                     self.options.onItemSelected(elem, initElem.children('option').get());                 } catch (ex) {                     if (self.options.allowDebug)                         alert('select function failed: ' + ex.Description);                 }             }         }, Solution: Under jQuery 1.4.4 you need to explicitly remove the attribute as in "removeAttr('selected'):         _handleClick: function(elem) {             var self = this; var initElem = this.element;             var checked = $(elem).is(':checked');             var myId = elem.attr('id').replace(initElem.attr('id') + '_chk_', '');             if (checked) {                 initElem.children('option[value=' + myId + ']').attr('selected', 'selected');             } else {                 initElem.children('option[value=' + myId + ']').removeAttr('selected');             }             if ($.isFunction(self.options.onItemSelected)) {                 try {                     self.options.onItemSelected(elem, initElem.children('option').get());                 } catch (ex) {                     if (self.options.allowDebug)                         alert('select function failed: ' + ex.Description);                 }             }         },

    Read the article

  • Searching for Windows User SID's in C#

    - by Ubiquitous Che
    Context Context first - issues I'm trying to resolve are below. One of our clients has asked as to quote how long it would take for us to improve one of our applications. This application currently provides basic user authentication in the form of username/password combinations. This client would like the ability for their employees to log-in using the details of whatever Windows User account is currently logged in at the time of running the application. It's not a deal-breaker if I tell them know - but the client might be willing to pay the costs of development to add this feature to the application. It's worth looking into. Based on my hunting around, it seems like storing the user login details against Domain\Username will be problematic if those details are changed. But Windows User SID's aren't supposed to change at all. I've got the impression that it would be best to record Windows Users by SID - feel free to relieve me of that if I'm wrong. I've been having a fiddle with some Windows API calls. From within C#, grabbing the current user's SID is easy enough. I can already take any user's SID and process it using LookupAccountSid to get username and domain for display purposes. For the interested, my code for this is at the end of this post. That's just the tip of the iceberg, however. The two issues below are completely outside my experience. Not only do I not know how to implement them - I don't even known how to find out how to implement them, or what the pitfalls are on various systems. Any help getting myself aimed in the right direction would be very much appreciated. Issue 1) Getting hold of the local user at runtime is meaningless if that user hasn't been granted access to the application. We will need to add a new section to our application's 'administrator console' for adding Windows Users (or groups) and assigning within-app permissions against those users. Something like an 'Add Windows User Login' button that will raise a pop-up window that will allow the user to search for available Windows User accounts on the network (not just the local machine) to be added to the list of available application logins. If there's already a component in .NET or Windows that I can shanghai into doing this for me, it would make me a very happy man. Issue 2) I also want to know how to take a given Windows User SID and check it against a given Windows User Group (probably taken from a database). I'm not sure how to get started with this one either, though I expect it to be easier than the issue above. For the Interested [STAThread] static void Main(string[] args) { MessageBox.Show(WindowsUserManager.GetAccountNameFromSID(WindowsIdentity.GetCurrent().User.Value)); MessageBox.Show(WindowsUserManager.GetAccountNameFromSID("S-1-5-21-57989841-842925246-1957994488-1003")); } public static class WindowsUserManager { public static string GetAccountNameFromSID(string SID) { try { StringBuilder name = new StringBuilder(); uint cchName = (uint)name.Capacity; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; WindowsUserManager.SID_NAME_USE sidUse; int err = (int)ESystemError.ERROR_SUCCESS; if (!WindowsUserManager.LookupAccountSid(null, SID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = Marshal.GetLastWin32Error(); if (err == (int)ESystemError.ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = WindowsUserManager.LookupAccountSid(null, SID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse) ? (int)ESystemError.ERROR_SUCCESS : Marshal.GetLastWin32Error(); } } if (err != (int)ESystemError.ERROR_SUCCESS) throw new ApplicationException(String.Format("Could not retrieve acount name from SID. {0}", SystemExceptionManager.GetDescription(err))); return String.Format(@"{0}\{1}", referencedDomainName.ToString(), name.ToString()); } catch (Exception ex) { if (ex is ApplicationException) throw ex; throw new ApplicationException("Could not retrieve acount name from SID", ex); } } private enum SID_NAME_USE { SidTypeUser = 1, SidTypeGroup, SidTypeDomain, SidTypeAlias, SidTypeWellKnownGroup, SidTypeDeletedAccount, SidTypeInvalid, SidTypeUnknown, SidTypeComputer } [DllImport("advapi32.dll", EntryPoint = "GetLengthSid", CharSet = CharSet.Auto)] private static extern int GetLengthSid(IntPtr pSID); [DllImport("advapi32.dll", SetLastError = true)] private static extern bool ConvertStringSidToSid( string StringSid, out IntPtr ptrSid); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool LookupAccountSid( string lpSystemName, [MarshalAs(UnmanagedType.LPArray)] byte[] Sid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse); private static bool LookupAccountSid( string lpSystemName, string stringSid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse) { byte[] SID = null; IntPtr SID_ptr = IntPtr.Zero; try { WindowsUserManager.ConvertStringSidToSid(stringSid, out SID_ptr); int err = SID_ptr == IntPtr.Zero ? Marshal.GetLastWin32Error() : (int)ESystemError.ERROR_SUCCESS; if (SID_ptr == IntPtr.Zero || err != (int)ESystemError.ERROR_SUCCESS) throw new ApplicationException(String.Format("'{0}' could not be converted to a SID byte array. {1}", stringSid, SystemExceptionManager.GetDescription(err))); int size = (int)GetLengthSid(SID_ptr); SID = new byte[size]; Marshal.Copy(SID_ptr, SID, 0, size); } catch (Exception ex) { if (ex is ApplicationException) throw ex; throw new ApplicationException(String.Format("'{0}' could not be converted to a SID byte array. {1}.", stringSid, ex.Message), ex); } finally { // Always want to release the SID_ptr (if it exists) to avoid memory leaks. if (SID_ptr != IntPtr.Zero) Marshal.FreeHGlobal(SID_ptr); } return WindowsUserManager.LookupAccountSid(lpSystemName, SID, lpName, ref cchName, ReferencedDomainName, ref cchReferencedDomainName, out peUse); } }

    Read the article

  • What is the exception in java code? [closed]

    - by Karandeep Singh
    This java code is for reverse the string but it returning concat null with returned string. import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class Practice { public static void main(String[] args) { String str = ""; try { str = reverse("Singh"); } catch (Exception ex) { Logger.getLogger(Practice.class.getName()).log(Level.SEVERE, null, ex); System.out.print(ex.getMessage()); }finally{ System.out.println(str); } } public static String reverse(String str) throws Exception{ String temp = null; if(str.length()<=0){ throw new Exception("empty"); }else{ for(int i=str.length()-1;i>=0;i--){ temp+=str.charAt(i); } } return temp.trim(); } } Output: nullhgniS

    Read the article

  • c# display DB table structure

    - by user3529643
    I have a question. My code is the following : public partial class Form1 : Form { public OleDbConnection datCon; public string MyDataFile; public ArrayList tblArray; public ArrayList fldArray; public Form1() { InitializeComponent(); lvData.Clear(); lvData.View = View.Details; lvData.LabelEdit = false; lvData.FullRowSelect = true; lvData.GridLines = true; } private void DataConnection() { MyDataFile = Application.StartupPath + @"\studenti.mdb"; string MyCon = @"provider=microsoft.jet.oledb.4.0;data source=" + MyDataFile; try { datCon = new OleDbConnection(MyCon); } catch (Exception ex) { MessageBox.Show(ex.Message); } FillTreeView(); } private void GetTables(OleDbConnection cnn) { try { cnn.Open(); DataTable schTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }); tblArray = new ArrayList(); foreach (DataRow datrow in schTable.Rows) { tblArray.Add(datrow["TABLE_NAME"].ToString()); } cnn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void GetFields(OleDbConnection cnn, string tabNode) { string tabName; try { tabName = tabNode; cnn.Open(); DataTable schTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, tabName }); fldArray = new ArrayList(); foreach (DataRow datRow in schTable.Rows) { fldArray.Add(datRow["COLUMN_NAME"].ToString()); } cnn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void FillTreeView() { tvData.Nodes.Clear(); tvData.Nodes.Add("Database"); tvData.Nodes[0].Tag = "RootDB"; GetTables(datCon); // add table node for (int i = 0; i < tblArray.Count; i++) { tvData.Nodes[0].Nodes.Add(tblArray[i].ToString()); tvData.Nodes[0].Nodes[i].Tag = "Tables"; } // add field node for (int i = 0; i < tblArray.Count; i++) { GetFields(datCon, tblArray[i].ToString()); for (int j = 0; j < fldArray.Count; j++) { tvData.Nodes[0].Nodes[i].Nodes.Add(fldArray[j].ToString()); tvData.Nodes[0].Nodes[i].Nodes[j].Tag = "Fields"; } } this.tvData.ContextMenuStrip = contextMenuStrip1; contextMenuStrip1.ItemClicked +=contextMenuStrip1_ItemClicked; } public void FillListView(OleDbConnection cnn, string tabName) { OleDbCommand cmdRead; OleDbDataReader datReader; string strField; lblTableName.Text = tabName; strField = "SELECT * FROM [" + tabName + "]"; // Initi cmdRead obiect cmdRead = new OleDbCommand(strField, cnn); cnn.Open(); datReader = cmdRead.ExecuteReader(); // fill ListView while (datReader.Read()) { ListViewItem objListItem = new ListViewItem(datReader.GetValue(0).ToString()); for (int c = 1; c < datReader.FieldCount; c++) { objListItem.SubItems.Add(datReader.GetValue(c).ToString()); } lvData.Items.Add(objListItem); } datReader.Close(); cnn.Close(); } private void ViewToolStripMenuItem_Click(object sender, EventArgs e) { DataConnection(); } public void tvData_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e) { string tabName; int fldCount; if (e.Node.Tag.ToString() == "Tables") { fldCount = e.Node.GetNodeCount(false); //column headers. int n = lvData.Width; double wid = n / fldCount; // width columnn for (int c = 0; c < fldCount; c++) { lvData.Columns.Add(e.Node.Nodes[c].Text, (int)wid, HorizontalAlignment.Left); } // gett table name tabName = e.Node.Text; FillListView(datCon, tabName); } } public void button1_Click(object sender, EventArgs e) { //TO DO?? } } I have a treeview populated with tables (nodes) from my database, and a listview which is populated with the data from my tables when I click on a table. As you can see I have a button1 on my form. When I click it I want it to display to me the structure of the table I selected in my treeview (a treeview node). Not too many details, just the name of the columns in my table, type of columns, primary keys. I've tried to follow many tutorials but I can t seem to manage it.

    Read the article

  • Code Contracts: Unit testing contracted code

    - by DigiMortal
    Code contracts and unit tests are not replacements for each other. They both have different purpose and different nature. It does not matter if you are using code contracts or not – you still have to write tests for your code. In this posting I will show you how to unit test code with contracts. In my previous posting about code contracts I showed how to avoid ContractExceptions that are defined in code contracts runtime and that are not accessible for us in design time. This was one step further to make my randomizer testable. In this posting I will complete the mission. Problems with current code This is my current code. public class Randomizer {     public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           var rnd = new Random();         return rnd.Next(min, max);     } } As you can see this code has some problems: randomizer class is static and cannot be instantiated. We cannot move this class between components if we need to, GetRandomFromRangeContracted() is not fully testable because we cannot currently affect random number generator output and therefore we cannot test post-contract. Now let’s solve these problems. Making randomizer testable As a first thing I made Randomizer to be class that must be instantiated. This is simple thing to do. Now let’s solve the problem with Random class. To make Randomizer testable I define IRandomGenerator interface and RandomGenerator class. The public constructor of Randomizer accepts IRandomGenerator as argument. public interface IRandomGenerator {     int Next(int min, int max); }   public class RandomGenerator : IRandomGenerator {     private Random _random = new Random();       public int Next(int min, int max)     {         return _random.Next(min, max);     } } And here is our Randomizer after total make-over. public class Randomizer {     private IRandomGenerator _generator;       private Randomizer()     {         _generator = new RandomGenerator();     }       public Randomizer(IRandomGenerator generator)     {         _generator = generator;     }       public int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return _generator.Next(min, max);     } } It seems to be inconvenient to instantiate Randomizer now but you can always use DI/IoC containers and break compiled dependencies between the components of your system. Writing tests for randomizer IRandomGenerator solved problem with testing post-condition. Now it is time to write tests for Randomizer class. Writing tests for contracted code is not easy. The main problem is still ContractException that we are not able to access. Still it is the main exception we get as soon as contracts fail. Although pre-conditions are able to throw exceptions with type we want we cannot do much when post-conditions will fail. We have to use Contract.ContractFailed event and this event is called for every contract failure. This way we find ourselves in situation where supporting well input interface makes it impossible to support output interface well and vice versa. ContractFailed is nasty hack and it works pretty weird way. Although documentation sais that ContractFailed is good choice for testing contracts it is still pretty painful. As a last chance I got tests working almost normally when I wrapped them up. Can you remember similar solution from the times of Visual Studio 2008 unit tests? Cannot understand how Microsoft was able to mess up testing again. [TestClass] public class RandomizerTest {     private Mock<IRandomGenerator> _randomMock;     private Randomizer _randomizer;     private string _lastContractError;       public TestContext TestContext { get; set; }       public RandomizerTest()     {         Contract.ContractFailed += (sender, e) =>         {             e.SetHandled();             e.SetUnwind();               throw new Exception(e.FailureKind + ": " + e.Message);         };     }       [TestInitialize()]     public void RandomizerTestInitialize()     {         _randomMock = new Mock<IRandomGenerator>();         _randomizer = new Randomizer(_randomMock.Object);         _lastContractError = string.Empty;     }       #region InputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_not_less_than_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(100, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_equal_to_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(10, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     public void GetRandomFromRangeContracted_should_work_when_min_is_less_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 50;           _randomMock.Setup(r => r.Next(minValue, maxValue))             .Returns(returnValue)             .Verifiable();           var result = _randomizer.GetRandomFromRangeContracted(minValue, maxValue);           _randomMock.Verify();         Assert.AreEqual<int>(returnValue, result);     }     #endregion       #region OutputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_less_than_min()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 7;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_more_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 102;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }     #endregion        } Although these tests are pretty awful and contain hacks we are at least able now to make sure that our code works as expected. Here is the test list after running these tests. Conclusion Code contracts are very new stuff in Visual Studio world and as young technology it has some problems – like all other new bits and bytes in the world. As you saw then making our contracted code testable is easy only to the point when pre-conditions are considered. When we start dealing with post-conditions we will end up with hacked tests. I hope that future versions of code contracts will solve error handling issues the way that testing of contracted code will be easier than it is right now.

    Read the article

  • Using the latest (stable release) of Oracle Developer Tools for Visual Studio 11.1.0.7.20.

    - by mbcrump
    +  = Simple and safe Data connections.   This guide is for someone wanting to use the latest ODP.NET quickly without reading the official documentation. This guide will get you up and running in about 15 minutes. I have reviewed my referral link to my simple Setting up ODP.net with Win7 x64 and noticed most people were searching for one of the following terms: “how to use odp.net with vs” “setup connection odp.net” “query db using odp and vs” While my article provided links and a sample tnsnames.ora file, it really didn’t tell you how to use it. I’m hoping that this brief tutorial will help. So before we get started, you will need the following: Download the following: www.oracle.com/technology/software/tech/dotnet/utilsoft.html from oracle and install it. It is the first one on the page. Visual Studio 2008 or 2010. It should be noted that The System.Data.OracleClient namespace is the OLD .NET Framework Data Provider for Oracle. It should not be used anymore as it has been depreciated. The latest version which is what we are using is Oracle.DataAccess.Client. First things first, Add a reference to the Oracle.DataAccess.Client after you install ODP.NET   Copy and paste the following C# code into your project and replace the relevant info including the query string and you should be able to return data. I have commented several lines of code to assist in understanding what it is doing.   Lambda Expression. using System; using System.Data; using Oracle.DataAccess.Client;   namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {           try         {             //Setup DataSource             string oradb = "Data Source=(DESCRIPTION ="                                    + "(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521)))"                                    + "(CONNECT_DATA = (SERVICE_NAME = SERVICENAME))) ;"                                    + "Persist Security Info=True;User ID=USER;Password=PASSWORD;";                        //Open Connection to Oracle - this could be moved outside the try.             OracleConnection conn = new OracleConnection(oradb);             conn.Open();               //Create cmd and use parameters to prevent SQL injection attacks.             OracleCommand cmd = new OracleCommand();             cmd.Connection = conn;               cmd.CommandText = "select username from table where username = :username";               OracleParameter p1 = new OracleParameter("username", OracleDbType.Varchar2);             p1.Value = username;             cmd.Parameters.Add(p1);               cmd.CommandType = CommandType.Text;               OracleDataReader dr = cmd.ExecuteReader();             dr.Read();               //Contains the value of the datarow             Console.WriteLine(dr["username"].ToString());               //Disposes of objects.             dr.Dispose();             cmd.Dispose();             conn.Dispose();         }           catch (OracleException ex) // Catches only Oracle errors         {             switch (ex.Number)             {                 case 1:                     Console.WriteLine("Error attempting to insert duplicate data.");                     break;                 case 12545:                     Console.WriteLine("The database is unavailable.");                     break;                 default:                     Console.WriteLine(ex.Message.ToString());                     break;             }         }           catch (Exception ex) // Catches any error not previously caught         {                   Console.WriteLine("Unidentified Error: " + ex.Message.ToString());              }         }       }           } At this point, you should have a working Program that returns data from an oracle database. If you are still having trouble then drop me a line and I will be happy to assist. As of this writing, oracle has announced the latest beta release of ODP.NET 11.2.0.1.1 Beta.  This release includes .NET Framework 4 and .NET Framework 4 Client Profile support. You may want to hold off on this version for a while as its BETA, and I wouldn’t want any production code using any BETA software.

    Read the article

  • OSGI & Apache Commons-DBCP Classloading Issue

    - by Saul
    I inherited some code that is using the Apache commons-dbcp Connection pools in an OSGi bundle. This code works fine with Eclipse/Equinox OSGi version 3.4.3 (R34x_v20081215), commons-dbcp 1.2.2 and the postgres jdbc3 8.3.603 bundles from springsource.org. I wanted to modernize, maybe this was my first mistake! When I use the new version of Felix or Equinox OSGI Cores with the new postgresql JDBC3 or JDBC4 bundles along with the latest version of commons-dbcp (1.4.1), I am getting a classloading issue. I have done numerous searches and found that the commons-dbcp code should have a fix DBCP-214, but it still seems to fail. I have tried to put the org.postgresql on the commons-dbcp MANIFEST.MF import-package line, but that did not work either. I wrote a simple test in an activator that first does a basic class.forName() and DriverManager.getConnection(), this works fine, but when I add in BasicDataSource() and setup the connection with BasicDataSource.getConnection(), I get the ClassNotFoundException. See the code example below. Thanks in Advance for any help, suggestions, ... Sau! // This one fails with an exception public void dsTest() { BasicDataSource bds = new BasicDataSource(); ClassLoader cl; try { logger.debug("ContextClassLoader: {}", Thread.currentThread().getContextClassLoader().toString()); cl = this.getClass().getClassLoader(); logger.debug("ClassLoader: {}", cl); if (bds.getDriverClassLoader() != null) { logger.debug(bds.getDriverClassLoader().toString()); } // The failure is the same with and with the setDriverClassLoader() line bds.setDriverClassLoader(cl); bds.setDriverClassName("org.postgresql.Driver"); bds.setUrl("jdbc:postgresql://127.0.0.1/dbname"); bds.setUsername("user"); bds.setPassword("pword"); Class.forName("org.postgresql.Driver").newInstance(); conn = bds.getConnection(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM table"); conn.close(); logger.debug("Closed DataSource Test"); } catch (Exception ex) { ex.printStackTrace(); logger.debug("Exception: {} ", ex.getMessage()); } } // This one works public void managerTest() { ClassLoader cl; try { cl = this.getClass().getClassLoader(); logger.debug("ClassLoader: {}", cl); Class.forName("org.postgresql.Driver").newInstance(); String url = "jdbc:postgresql://127.0.0.1/dbname"; conn = DriverManager.getConnection(url, "user", "pword"); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM table"); conn.close(); logger.debug("Closed Manger Test"); } catch (Exception ex) { ex.printStackTrace(); logger.debug("Exception: {} ", ex.getMessage()); } }

    Read the article

  • How to Create Site using Sharepoint web services?

    - by Pari
    Hi All, I am tring to create site on sharepoint programatically using Sharepoint Web Services.(C#). I tried Admin.asmx service (CreateSite method). But it's showing error: "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Web.Services.dll". I tried with all possible parameters. Curremtly referring Below Links: http://www.oliebol.org/blog/Lists/Posts/Post.aspx?ID=6 http://msdn.microsoft.com/en-us/library/administration.admin.createsite.aspx My Code: Admin admService = new Admin(); admService.Credentials = new NetworkCredential(username,password,domain); admService.Url = "http://mychserver/_vti_adm/admin.asmx"; admService.PreAuthenticate = true; try { String SitePath = "http://myserver/SiteDirectory/SharepointSampleSite"; admService.CreateSite(SitePath,"First Site", "Sample Site", 1033, "STS#0", "Domain\\username",username,userid, "", ""); } catch (System.Web.Services.Protocols.SoapException ex) { MessageBox.Show("Message:\n" + ex.Message + "\nDetail:\n" +ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace); } Thanx,

    Read the article

  • Binding Data to DataGridView in VB.Net

    - by Peter
    Hi, I have a bit of code which loads data from a stored procedure in MS SQL Server and then loads the data to a datagridview, which works fine. What i want is for the code that connects / loads the data to sit in my Database Class and then everything associated with the datagridview to be stored in my Form but i am having problems passing the contents of the bindingsource over to the Form from the Database Class. Form1 Public Class Form1 Dim myDatabaseObj As New Class1() Dim bindingSource1 As New BindingSource() Dim connectString As New SqlConnection Dim objDataAdapter As New SqlDataAdapter Dim table As New DataTable() Dim tabletest As New DataTable() Private Sub loadCompanyList() Try Me.dgv_CompanyList.DataSource = Me.bindingSource1 getCompanyList() Catch ex As NullReferenceException End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load loadCompanyList() End Sub End Class Database Class When i try place the getCompanyList() in a class and then create a new object that references the Form() it does not seem to return any value from the table to the MyForm.BindingSource1.Datasource meaning my datagridview displays not data. ..... Private Sub getCompanyList() Try Dim myForm as new Form() connect_Transaction_Database() objDataAdapter.SelectCommand = New SqlCommand() objDataAdapter.SelectCommand.Connection = connectString objDataAdapter.SelectCommand.CommandText = "sp_GetCompanyList" objDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure Dim commandBuilder As New SqlCommandBuilder(Me.objDataAdapter) Dim table As New DataTable() table.Locale = System.Globalization.CultureInfo.InvariantCulture Me.objDataAdapter.Fill(table) **MyForm.bindingSource1.DataSource = table** Catch ex As DataException MsgBox(ex.Message) Catch ex As NullReferenceException MsgBox(ex.Message) End Try disconnect_Transaction_Database() End Sub If anyone could help. Thank you. Peter

    Read the article

  • when executing Powershell Script from Ruby "Can't convert true into String" error

    - by Ozie Harb
    I am trying to execute a powershell script from Ruby, I have entered the below command: scriptPath = system('powershell \"C:\\Scripts\\DB_Setup.ps1\"') The ruby Script is handling exceptions when an error is raised to stop the script as below command: rescue => ex message = "\nscript on server '#{`hostname`.strip()}' terminated unexpectedly:\n\nMessage: '#{ex.message}" raise ex Output Error: script on server 'TestDB1' terminated unexpectedly: Message: 'can't convert true into String' Thanks

    Read the article

  • MessageQueue.BeginReceive() null ref error - c#

    - by ltech
    Have a windows service that listens to a msmq. In the OnStart method is have this protected override void OnStart(string[] args) { try { _queue = new MessageQueue(_qPath);//this part works as i had logging before and afer this call //Add MSMQ Event _queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);//this part works as i had logging before and afer this call _queue.BeginReceive();//This is where it is failing - get a null reference exception ; } catch(Exception ex) { EventLogger.LogEvent(EventSource, EventLogType, "OnStart" + _lineFeed + ex.InnerException.ToString() + _lineFeed + ex.Message.ToString()); } } where private MessageQueue _queue = null;

    Read the article

  • Extracting URIs from RDF web page in Java using Jena Library

    - by Prannoy Mittal
    I have written following code for extratcting URIs from a web page with content type application/rdf-xml for Linked Data application. public static void test(String url) { try { Model read = ModelFactory.createDefaultModel().read(url); System.out.println("to go"); StmtIterator si; si = read.listStatements(); System.out.println("to go"); while(si.hasNext()) { Statement s=si.nextStatement(); Resource r=s.getSubject(); Property p=s.getPredicate(); RDFNode o=s.getObject(); System.out.println(r.getURI()); System.out.println(p.getURI()); System.out.println(o.asResource().getURI()); } } catch(JenaException | NoSuchElementException c) { } } But above code is not extracting all URIs. It provides only few of the URIs. Please guide me where i Went wrong?? hey Rafeel For Eq: for XML File : <?xml version="1.0"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:ex="http://example.org/stuff/1.0/"> <rdf:Description rdf:about="http://www.w3.org/TR/rdf-syntax-grammar" dc:title="RDF/XML Syntax Specification (Revised)"> <ex:editor> <rdf:Description ex:fullName="Dave Beckett"> <ex:homePage rdf:resource="http://purl.org/net/dajobe/" /> </rdf:Description> </ex:editor> </rdf:Description> </rdf:RDF> The output is : Subject URI is http://www.w3.org/TR/rdf-syntax-grammar Predicate URI is http://example.org/stuff/1.0/editor Object URI is null Subject URI is http://www.w3.org/TR/rdf-syntax-grammar Predicate URI is http://purl.org/dc/elements/1.1/title Website is read

    Read the article

  • o display an image

    - by Vimal Basdeo
    I want to display an image from the web to a panel in another Jframe at the click of a button but whenever I click the button first the image loads and during this time the current form potentially freezes and once the image has loaded the form is displayed with the image.. How can I avoid the situation where my form freezes since it is very irritating My codes :: My current class private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) { try { sendMessage("Query,map,$,start,211,Arsenal,!"); System.out.println(receiveMessage()); } catch (UnknownHostException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send); this.setVisible(false); this.dispose(); nextform.setVisible(true); // TODO add your handling code here: } My next class that displays the image public class client_trackedbus extends javax.swing.JFrame { client_planform planform=null; DatagramSocket connection=null; DatagramPacket packet_receive=null; DatagramPacket packet_send=null; JLabel label=null; /** Creates new form client_trackedbus */ public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) { initComponents(); this.planform=planform; this.connection=connection; this.packet_receive=packet_receive; this.packet_send=packet_send; try { displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel()); } catch (MalformedURLException ex) { Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex); } } private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{ URL imageurl=new URL(url); Image image=(Toolkit.getDefaultToolkit().createImage(imageurl)); ImageIcon icon = new ImageIcon(image); label.setIcon(icon); panel.add(label); // System.out.println(panel.getSize().width); this.getContentPane().add(panel); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btn_Exit = new javax.swing.JButton(); btn_Plan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Public Transport Journey Planner"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 368, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 172, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); jLabel1.setText("Your tracked bus"); btn_Exit.setText("Exit"); btn_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ExitActionPerformed(evt); } }); btn_Plan.setText("Plan journey"); btn_Plan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_PlanActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(104, 104, 104) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(65, 65, 65) .addComponent(btn_Plan) .addGap(65, 65, 65) .addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_Exit) .addComponent(btn_Plan)) .addContainerGap(12, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Exitform(); } private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.setVisible(false); this.dispose(); this.planform.setVisible(true); } private void Exitform(){ this.setVisible(false); this.dispose(); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new client_trackedbus().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btn_Exit; private javax.swing.JButton btn_Plan; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration }

    Read the article

  • how to predict which section have to put in critical section in threading

    - by Lalit Dhake
    Hi , I am using the console application i used multi threading in the same. I just want to know which section have to put inside critical section my code is : .------------------------------------------------------------------------------. public class SendBusReachSMS { public void SchedularEntryPoint() { try { List<ActiveBusAndItsPathInfo> ActiveBusAndItsPathInfoList = BusinessLayer.GetActiveBusAndItsPathInfoList(); if (ActiveBusAndItsPathInfoList != null) { //SMSThreadEntryPoint smsentrypoint = new SMSThreadEntryPoint(); while (true) { foreach (ActiveBusAndItsPathInfo ActiveBusAndItsPathInfoObj in ActiveBusAndItsPathInfoList) { if (ActiveBusAndItsPathInfoObj.isSMSThreadActive == false) { DateTime CurrentTime = System.DateTime.Now; DateTime Bustime = Convert.ToDateTime(ActiveBusAndItsPathInfoObj.busObj.Timing); TimeSpan tsa = Bustime - CurrentTime; if (tsa.TotalMinutes > 0 && tsa.TotalMinutes < 5) { ThreadStart starter = delegate { SMSThreadEntryPointFunction(ActiveBusAndItsPathInfoObj); }; Thread t = new Thread(starter); t.Start(); t.Join(); } } } } } } catch (Exception ex) { Console.WriteLine("==========================================="); Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException); Console.WriteLine("==========================================="); } } public void SMSThreadEntryPointFunction(ActiveBusAndItsPathInfo objActiveBusAndItsPathInfo) { try { //mutThrd.WaitOne(); String consoleString = "Thread for " + objActiveBusAndItsPathInfo.busObj.Number + "\t" + " on path " + "\t" + objActiveBusAndItsPathInfo.pathObj.PathId; Console.WriteLine(consoleString); TrackingInfo trackingObj = new TrackingInfo(); string strTempBusTime = objActiveBusAndItsPathInfo.busObj.Timing; while (true) { trackingObj = BusinessLayer.get_TrackingInfoForSendingSMS(objActiveBusAndItsPathInfo.busObj.Number); if (trackingObj.latitude != 0.0 && trackingObj.longitude != 0.0) { //calculate distance double distanceOfCurrentToDestination = 4.45; TimeSpan CurrentTime = System.DateTime.Now.TimeOfDay; TimeSpan timeLimit = objActiveBusAndItsPathInfo.sessionInTime - CurrentTime; if ((distanceOfCurrentToDestination <= 5) && (timeLimit.TotalMinutes <= 5)) { Console.WriteLine("Message sent to bus number's parents: " + objActiveBusAndItsPathInfo.busObj.Number); break; } } } // mutThrd.ReleaseMutex(); } catch (Exception ex) { //throw; Console.WriteLine("==========================================="); Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException); Console.WriteLine("==========================================="); } } } Please help me in multithreading. new topic for me in .net

    Read the article

  • Hibernate save() and transaction rollback

    - by Marco
    Hi, In Hibernate when i save() an object in a transaction, and then i rollback it, the saved object still remains in the DB. It's strange because this issue doesn't happen with the update() or delete() method, just with save(). Here is the code i'm using: DbEntity dbEntity = getDbEntity(); HibernateUtil.beginTransaction(); Session session = HibernateUtil.getCurrentSession(); session.save(dbEntity); HibernateUtil.rollbackTransaction(); And here is the HibernateUtil class (just the involved functions, i guarantee the getSessionFactory() method works well - there is an Interceptor handler, but it doesn't matter now): private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>(); private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>(); /** * Retrieves the current Session local to the thread. * <p/> * If no Session is open, opens a new Session for the running thread. * * @return Session */ public static Session getCurrentSession() throws HibernateException { Session s = (Session) threadSession.get(); try { if (s == null) { log.debug("Opening new Session for this thread."); if (getInterceptor() != null) { log.debug("Using interceptor: " + getInterceptor().getClass()); s = getSessionFactory().openSession(getInterceptor()); } else { s = getSessionFactory().openSession(); } threadSession.set(s); } } catch (HibernateException ex) { throw new HibernateException(ex); } return s; } /** * Start a new database transaction. */ public static void beginTransaction() throws HibernateException { Transaction tx = (Transaction) threadTransaction.get(); try { if (tx == null) { log.debug("Starting new database transaction in this thread."); tx = getCurrentSession().beginTransaction(); threadTransaction.set(tx); } } catch (HibernateException ex) { throw new HibernateException(ex); } } /** * Rollback the database transaction. */ public static void rollbackTransaction() throws HibernateException { Transaction tx = (Transaction) threadTransaction.get(); try { threadTransaction.set(null); if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { log.debug("Tyring to rollback database transaction of this thread."); tx.rollback(); } } catch (HibernateException ex) { throw new HibernateException(ex); } finally { closeSession(); } } Thanks

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >