Search Results

Search found 2978 results on 120 pages for 'ex parrot'.

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

  • OpenSSL force client to use specific protocol

    - by Ex Umbris
    When subversion attempts to connect to an https URL, the underlying protocol library (openssl) attempts to start the secure protocol negotiation at the most basic level, plain SSL. Unfortunately, I have to connect to a server that requires SSL3 or TLS1, and refuses to respond to SSL or SSL2. I’ve done some troubleshooting using s_client and confirmed that if I let s_client start with the default protocol the server never responds to the CLIENT HELLO: $ openssl s_client -connect server.domain.com:443 CONNECTED(00000003) write:errno=104 --- no peer certificate available --- No client certificate CA names sent --- SSL handshake has read 0 bytes and written 320 bytes --- New, (NONE), Cipher is (NONE) Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE --- Watching this in Wireshark I see: Client Server -------syn----------> <------ack----------- ---CLIENT HELLO-----> <------ack----------- [60 second pause] <------rst----------- If I tell s_client to use ssl2 the server immediately closes the connection. Only ssl3 and tls1 work. Is there any way to configure openssl to skip SSL and SSL2, and start the negotiation with TLS or SSL3? I've found the OpenSSL config file, but that seems to control only certificate generation.

    Read the article

  • PAM with KRB5 to Active Directory - How to prevent update of AD password?

    - by Ex Umbris
    I have a working Fedora 9 system that's set up to authenticate users via PAM - krb5 - Active Directory. I'm migrating this to Fedora 14, and everything works, but it's working too well :-) On Fedora 9, if a Linux user updated their password, it did not propagate to their Active Directory account. On Fedora 14, it is changing their A/D password. The problem is I don't want A/D to be updated. Here's my password-auth-ac: auth required pam_env.so auth sufficient pam_unix.so nullok try_first_pass auth requisite pam_succeed_if.so uid >= 500 quiet auth sufficient pam_krb5.so use_first_pass auth required pam_deny.so account required pam_unix.so account sufficient pam_localuser.so account sufficient pam_succeed_if.so uid < 500 quiet account [default=bad success=ok user_unknown=ignore] pam_krb5.so account required pam_permit.so password requisite pam_cracklib.so try_first_pass retry=3 type= password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok password sufficient pam_krb5.so use_authtok password required pam_deny.so session optional pam_keyinit.so revoke session required pam_limits.so -session optional pam_systemd.so session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid session required pam_unix.so session optional pam_krb5.so I tried removing the line password sufficient pam_krb5.so use_authtok But then when attempting to change the Linux password, if they provide their A/D password for the authentication prompt, they get the error: passwd: Authentication token manipulation error What I want to achieve is: Allow authentication with either the A/D or Linux password (the Linux password is a fall-back for certain sysadmin users in case A/D is unavailable for some reason). This is working now. Allow users to change their Linux passwords without affecting their A/D passwords. Is this possible?

    Read the article

  • I have a collection of dead consumer grade routers, should I buy a real one?

    - by Ex Networking Guy
    Am I crazy for considering purchasing a Cisco 2621 for the house? I am familiar enough with IOS to set up a simple gateway router, I don't really need the experience. At this point, I'm a developer so my days of crawling through CO's and under desks are long past me. But I am really sick of crappy consumer grade networking gear. Maybe I have lousy luck and this stack of WRTG54s is just because I have lousy power, or whatever.

    Read the article

  • Fake ISAPI Handler to serve static files with extention that are rewritted by url rewriter

    - by developerit
    Introduction I often map html extention to the asp.net dll in order to use url rewritter with .html extentions. Recently, in the new version of www.nouvelair.ca, we renamed all urls to end with .html. This works great, but failed when we used FCK Editor. Static html files would not get serve because we mapped the html extension to the .NET Framework. We can we do to to use .html extension with our rewritter but still want to use IIS behavior with static html files. Analysis I thought that this could be resolve with a simple HTTP handler. We would map urls of static files in our rewriter to this handler that would read the static file and serve it, just as IIS would do. Implementation This is how I coded the class. Note that this may not be bullet proof. I only tested it once and I am sure that the logic behind IIS is more complicated that this. If you find errors or think of possible improvements, let me know. Imports System.Web Imports System.Web.Services ' Author: Nicolas Brassard ' For: Solutions Nitriques inc. http://www.nitriques.com ' Date Created: April 18, 2009 ' Last Modified: April 18, 2009 ' License: CPOL (http://www.codeproject.com/info/cpol10.aspx) ' Files: ISAPIDotNetHandler.ashx ' ISAPIDotNetHandler.ashx.vb ' Class: ISAPIDotNetHandler ' Description: Fake ISAPI handler to serve static files. ' Usefull when you want to serve static file that has a rewrited extention. ' Example: It often map html extention to the asp.net dll in order to use url rewritter with .html. ' If you want to still serve static html file, add a rewritter rule to redirect html files to this handler Public Class ISAPIDotNetHandler Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest ' Since we are doing the job IIS normally does with html files, ' we set the content type to match html. ' You may want to customize this with your own logic, if you want to serve ' txt or xml or any other text file context.Response.ContentType = "text/html" ' We begin a try here. Any error that occurs will result in a 404 Page Not Found error. ' We replicate the behavior of IIS when it doesn't find the correspoding file. Try ' Declare a local variable containing the value of the query string Dim uri As String = context.Request("fileUri") ' If the value in the query string is null, ' throw an error to generate a 404 If String.IsNullOrEmpty(uri) Then Throw New ApplicationException("No fileUri") End If ' If the value in the query string doesn't end with .html, then block the acces ' This is a HUGE security hole since it could permit full read access to .aspx, .config, etc. If Not uri.ToLower.EndsWith(".html") Then ' throw an error to generate a 404 Throw New ApplicationException("Extention not allowed") End If ' Map the file on the server. ' If the file doesn't exists on the server, it will throw an exception and generate a 404. Dim fullPath As String = context.Server.MapPath(uri) ' Read the actual file Dim stream As IO.StreamReader = FileIO.FileSystem.OpenTextFileReader(fullPath) ' Write the file into the response context.Response.Output.Write(stream.ReadToEnd) ' Close and Dipose the stream stream.Close() stream.Dispose() stream = Nothing Catch ex As Exception ' Set the Status Code of the response context.Response.StatusCode = 404 'Page not found ' For testing and bebugging only ! This may cause a security leak ' context.Response.Output.Write(ex.Message) Finally ' In all cases, flush and end the response context.Response.Flush() context.Response.End() End Try End Sub ' Automaticly generated by Visual Studio ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class Conclusion As you see, with our static files map to this handler using query string (ex.: /ISAPIDotNetHandler.ashx?fileUri=index.html) you will have the same behavior as if you ask for the uri /index.html. Finally, test this only in IIS with the html extension map to aspnet_isapi.dll. Url rewritting will work in Casini (Internal Web Server shipped with Visual Studio) but it’s not the same as with IIS since EVERY request is handle by .NET. Versions First release

    Read the article

  • generic DAO in java

    - by akshay
    I am trying to develop generic DAO in java.I have tried the following.Is this a good way to implement generic dao?I dont want to use hibernate.I am trying to make it as generic as possible so that i dont have to repeate the same code again and again. public abstract class AbstractDAO<T> { protected ResultSet findbyId(String tablename, Integer id){ ResultSet rs= null; try { // the following lins in not working; pStmt = cn.prepareStatement("SELECT * FROM "+ tablename+ "WHERE id = ?"); pStmt.setInt(1, id); rs = pStmt.executeQuery(); } catch (SQLException ex) { System.out.println("ERROR in findbyid " +ex.getMessage() +ex.getCause()); ex.printStackTrace(); }finally{ return rs; } } } Now i have public class UserDAO extends AbstractDAO<User>{ public List<User> findbyid(int id){ Resultset rs =findbyid("USERS",id) //USERS is tablename in db List<Users> users = convertToList(rs); return users; } private List<User> convertToList(ResultSet rs) { List<User> userList= new ArrayList(); User user= new User();; try { while (rs.next()) { user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setFname(rs.getString("fname")); user.setLname(rs.getString("lname")); user.setUsertype(rs.getInt("usertype")); user.setPasswd(rs.getString("passwd")); userList.add(user); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return userList; } }

    Read the article

  • MSTest Test Context Exception Handling

    - by Flip
    Is there a way that I can get to the exception that was handled by the MSTest framework using the TestContext or some other method on a base test class? If an unhandled exception occurs in one of my tests, I'd like to spin through all the items in the exception.Data dictionary and display them to the test result to help me figure out why the test failed (we usually add data to the exception to help us debug in the production env, so I'd like to do the same for testing). Note: I am not testing that an exception was SUPPOSED TO HAPPEN (I have other tests for that), I am testing a valid case, I just need to see the exception data. Here is a code example of what I'm talking about. [TestMethod] public void IsFinanceDeadlineDateValid() { var target = new BusinessObject(); SetupBusinessObject(target); //How can I capture this in the text context so I can display all the data //in the exception in the test result... var expected = 100; try { Assert.AreEqual(expected, target.PerformSomeCalculationThatMayDivideByZero()); } catch (Exception ex) { ex.Data.Add("SomethingImportant", "I want to see this in the test result, as its important"); ex.Data.Add("Expected", expected); throw ex; } } I understand there are issues around why I probably shouldn't have such an encapsulating method, but we also have sub tests to test all the functionality of PerformSomeCalculation... However, if the test fails, 99% of the time, I rerun it passes, so I can't debug anything without this information. I would also like to do this on a GLOBAL level, so that if any test fails, I get the information in the test results, as opposed to doing it for each individual test. Here is the code that would put the exception info in the test results. public void AddDataFromExceptionToResults(Exception ex) { StringBuilder whereAmI = new StringBuilder(); var holdException = ex; while (holdException != null) { Console.WriteLine(whereAmI.ToString() + "--" + holdException.Message); foreach (var item in holdException.Data.Keys) { Console.WriteLine(whereAmI.ToString() + "--Data--" + item + ":" + holdException.Data[item]); } holdException = holdException.InnerException; } }

    Read the article

  • What purpose does “using” serve when used the following way

    - by user287745
    What purpose does “using” serve when used the following way:- ONE EXAMPLE IS THIS, (AN ANSWERER- @richj - USED THIS CODE TO SOLVE A PROBLEM THANKS) private Method(SqlConnection connection) { using (SqlTransaction transaction = connection.BeginTransaction()) { try { // Use the connection here .... transaction.Commit(); } catch { transaction.Rollback(); throw; } } } OTHER EXAMPLE I FOUND WHILE READING ON MICROSOFT SUPPORT SITE public static void ShowSqlException(string connectionString) { string queryString = "EXECUTE NonExistantStoredProcedure"; StringBuilder errorMessages = new StringBuilder(); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); try { command.Connection.Open(); command.ExecuteNonQuery(); } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); } } } I AM doing at top of page as using system.data.sqlclient etc so why this using thing in middle of code, What if I omit it (I know the code will work) but what functionality will I be losing

    Read the article

  • Do I need Response.End() in ASP.Net 2.0

    - by Hamish Grubijan
    Hi, I am just starting with ASP.Net. I copied a ex-co-worker's code (from .Net 1.1 era) and it has a Response.End(); in case of an error. There is also a: catch (Exception ex) { Response.Write(ex.Message); Response.End(); } at the end of Page_Load(object sender, System.EventArgs e) which always appends "Thread was aborted." or something like that at the end. I suspect that this worked differently before, or the error conditions were not tested very well. Anyhow, I was able to stop using Response.End(); in case when I do not like the GET parameters, and use return; instead. It seemed to do the right think in a simple case. Is this Ok in general? There are some problems with the code I copied, but I do not want to do a rewrite; I just want to get it running first and find wrinkles later. The Response.End(); caused a mental block for me, however, so I want to figure it out. I want to keep the catch all clause just in case, at least for now. I could also end the method with: catch (System.Threading.ThreadAbortException) { Response.End(); } catch (Exception ex) { Response.Write(ex.Message); Response.End(); } but that just seems extremely stupid, once you think about all of the exceptions being generated. Please give me a few words of wisdom. Feel free to ask if something is not clear. Thanks! P.S. Ex-coworker was not fired and is a good coder - one more reason to reuse his example.

    Read the article

  • unroll nested for loops in C++

    - by Hristo
    How would I unroll the following nested loops? for(k = begin; k != end; ++k) { for(j = 0; j < Emax; ++j) { for(i = 0; i < N; ++i) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); } } } I tried the following, but my output isn't the same, and it should be: for(k = begin; k != end; ++k) { for(j = 0; j < Emax; ++j) { for(i = 0; i+4 < N; i+=4) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); array[k] += foo(i+1, tr[k][i+1], ex[j][i+1]); array[k] += foo(i+2, tr[k][i+2], ex[j][i+2]); array[k] += foo(i+3, tr[k][i+3], ex[j][i+3]); } if (i < N) { for (; i < N; ++i) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); } } } } I will be running this code in parallel using Intel's TBB so that it takes advantage of multiple cores. After this is finished running, another function prints out what is in array[] and right now, with my unrolling, the output isn't identical. Any help is appreciated. Thanks, Hristo

    Read the article

  • Issue selenium code maintenance

    - by Rajasankar
    I want to group the common methods in one file and use it. For example, login to a page using selenium may be used in multiple times. Define that in class A and call it in class B. However, it throws null pointer exception. class A has public void test_Login() throws Exception { try{ selenium.setTimeout("60000"); selenium.open("http://localhost"); selenium.windowFocus(); selenium.windowMaximize(); selenium.windowFocus(); selenium.type("userName", "admin"); selenium.type("password", "admin"); Result=selenium.isElementPresent("//input[@type='image']"); selenium.click("//input[@type='image']"); selenium.waitForPageToLoad(Timeout); } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } with all other java syntax in class B public void test_kk() throws Exception { try { a.test_Login(); } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } with all syntax. When I execute class B, I got this error, java.lang.NullPointerException at A.test_Login(A.java:32) at B.test_kk(savefile.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at junit.framework.TestCase.runTest(TestCase.java:168) at junit.framework.TestCase.runBare(TestCase.java:134) at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.j ava:212) at junit.framework.TestResult$1.protect(TestResult.java:110) at junit.framework.TestResult.runProtected(TestResult.java:128) at junit.framework.TestResult.run(TestResult.java:113) at junit.framework.TestCase.run(TestCase.java:124) at junit.framework.TestSuite.runTest(TestSuite.java:232) at junit.framework.TestSuite.run(TestSuite.java:227) at junit.textui.TestRunner.doRun(TestRunner.java:116) at junit.textui.TestRunner.doRun(TestRunner.java:109) at junit.textui.TestRunner.run(TestRunner.java:77) at B.main(B.java:77) I hope someone must have tried this before. I may miss something here.

    Read the article

  • 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

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