Daily Archives

Articles indexed Friday November 2 2012

Page 11/15 | < Previous Page | 7 8 9 10 11 12 13 14 15  | Next Page >

  • How to access the calling source line from interactive shell

    - by TJD
    I want to make a function that can determine the source code of how it was called. I'm aware of how to do this generally with the inspect module. For example, this question, works well and provides my desired output in the lines variable as shown below: def hello(x): frame,filename,line_number,function_name,lines,index=\ inspect.getouterframes(inspect.currentframe())[1] print(frame,filename,line_number,function_name,lines,index) The problem is that this solution doesn't work in an interactive command line session. For example, from a command line, the result looks like: >>> y = hello(7) (<frame object at 0x01ECA9E8>, '<stdin>', 1, '<module>', None, None) The problem is that the source file is '<stdin>', so the lines variable is None. How can I access the calling line to find the result containing the string y = hello(7) during an interactive session?

    Read the article

  • Get reference to all instances of jquery ui widget?

    - by Hailwood
    I am writing a jquery UI widget that simply wraps the bootstrap popover plugin, In the widget you can pass in the option 'singular', if this is passed in then it should call a function of all other instances of the plugin. something like $('#one').myWidget(); $('#two').myWidget(); $('#three').myWidget(); $('#four').myWidget(); $('#one').myWidget('show'); //stuff from widget one is now visible $('#two').myWidget('show'); //stuff from widget one and two are now visible $('#three').myWidget('show'); //stuff from widget one, two and three are now visible $('#two').myWidget('hide'); //stuff from widget one and three are now visible $('#four').myWidget('show', {singular:true}); //stuff from widget four is now visible So, I imagine the show function looking like: show: function(options){ options = options || {}; if(options.singular){ var instances = '????'; // how do I get all instances? $.each(instances, function(i, o){ o.myWidget('hide'); }); } this.element.popover('show'); } So, question being, how would I get a reference to all elements that have the myWidget widget on them?

    Read the article

  • Unicorn_init.sh cannot find app root on capistrano cold deploy

    - by oFca
    I am deploying Rails app and upon running cap deploy:cold I get the error saying * 2012-11-02 23:53:26 executing `deploy:migrate' * executing "cd /home/mr_deployer/apps/prjct_mngr/releases/20121102225224 && bundle exec rake RAILS_ENV=production db:migrate" servers: ["xxxxxxxxxx"] [xxxxxxxxxx] executing command command finished in 7464ms * 2012-11-02 23:53:34 executing `deploy:start' * executing "/etc/init.d/unicorn_prjct_mngr start" servers: ["xxxxxxxxxx"] [xxxxxxxxxx] executing command ** [out :: xxxxxxxxxx] /etc/init.d/unicorn_prjct_mngr: 33: cd: can't cd to /home/mr_deployer/apps/prjct_mngr/current; command finished in 694ms failed: "rvm_path=$HOME/.rvm/ $HOME/.rvm/bin/rvm-shell '1.9.3-p125@prjct_mngr' -c '/etc/init.d/unicorn_prjct_mngr start'" on xxxxxxxxxx but my app root is there! Why can't it find it? Here's part of my unicorn_init.sh file : 1 #!/bin/sh 2 set -e 3 # Example init script, this can be used with nginx, too, 4 # since nginx and unicorn accept the same signals 5 6 # Feel free to change any of the following variables for your app: 7 TIMEOUT=${TIMEOUT-60} 8 APP_ROOT=/home/mr_deployer/apps/prjct_mngr/current 9 PID=$APP_ROOT/tmp/pids/unicorn.pid 10 CMD="cd $APP_ROOT; bundle exec unicorn -D -c $APP_ROOT/config/unicorn.rb - E production" 11 # INIT_CONF=$APP_ROOT/config/init.conf 12 AS_USER=mr_deployer 13 action="$1" 14 set -u 15 16 # test -f "$INIT_CONF" && . $INIT_CONF 17 18 old_pid="$PID.oldbin" 19 20 cd $APP_ROOT || exit 1 21 22 sig () { 23 test -s "$PID" && kill -$1 `cat $PID` 24 } 25 26 oldsig () { 27 test -s $old_pid && kill -$1 `cat $old_pid` 28 } 29 case $action in 30 31 start) 32 sig 0 && echo >&2 "Already running" && exit 0 33 $CMD 34 ;; 35 36 stop) 37 sig QUIT && exit 0 38 echo >&2 "Not running" 39 ;; 40 41 force-stop) 42 sig TERM && exit 0 43 echo >&2 "Not running" 44 ;; 45 46 restart|reload) 47 sig HUP && echo reloaded OK && exit 0 48 echo >&2 "Couldn't reload, starting '$CMD' instead" 49 $CMD 50 ;; 51 52 upgrade) 53 if sig USR2 && sleep 2 && sig 0 && oldsig QUIT 54 then 55 n=$TIMEOUT 56 while test -s $old_pid && test $n -ge 0 57 do 58 printf '.' && sleep 1 && n=$(( $n - 1 )) 59 done 60 echo 61 62 if test $n -lt 0 && test -s $old_pid 63 then 64 echo >&2 "$old_pid still exists after $TIMEOUT seconds" 65 exit 1 66 fi 67 exit 0 68 fi 69 echo >&2 "Couldn't upgrade, starting '$CMD' instead" 70 $CMD 71 ;; 72 73 reopen-logs) 74 sig USR1 75 ;; 76 77 *) 78 echo >&2 "Usage: $0 <start|stop|restart|upgrade|force-stop|reopen-logs>" 79 exit 1 80 ;; 81 esac

    Read the article

  • Pointer to struct, containing pointer to an object, for which I want to call a function

    - by user1795609
    So I've created an ADT which is a singly linked list made up of nodes. These Nodes each have a pointer to an object in them called data. Class Structure { struct Node { Object *data; Node *next; }; }; Node *head; I am trying to call a function in the object, like this: head = new Node; head -> data = new Object(); head -> next = NULL; cout << head -> data.print(); I keep getting the following error at compile. error: request for member 'print' in 'head-Structure::Node::data', which is of non-class type 'Object'*

    Read the article

  • Including a List<SpecificType> in a model, and how to populate it

    - by Ray Sülzer
    I currently have two Model classes: class Leaders: List<Leaders> { public string LeaderName { get; set; } public string PrecintName { get; set; } } public class MarketReport { //A list of activists public Leaders leaderlist { get; set; } } Now, I have no idea if I am doing the above correctly, but I want to populate the list within the MarketReport foreach (var store in stores) { MarketReport.leaderlist.AddItem //I want to add an item of type Leader to the list //so that I can pass it to MVC view }

    Read the article

  • Java anagram recursion List<List<String>> only storing empty lists<Strings>

    - by Riff Rafffer
    Hi In this recursion method i am trying to find all anagrams and add it to a List but what happens when i run this code is it just returns alot of empty Lists. private List<List<String>> findAnagrams(LetterInventory words, ArrayList<String> anagram, int max, Map<String, LetterInventory> smallDict, int level, List<List<String>> result) { ArrayList<String> solvedWord = new ArrayList<String>(); LetterInventory shell; LetterInventory shell2; if (level < max || max == 0) { Iterator<String> it = smallDict.keySet().iterator(); while (it.hasNext()) { String k = it.next(); shell = new LetterInventory(k); shell2 = words; if (shell2.subtract(shell) != null) { anagram.add(k); shell2 = words.subtract(shell); if (shell2.isEmpty()) { //System.out.println(anagram.toString()); it prints off fine here result.add(anagram); // but doesnt add here } else findAnagrams(shell2, anagram, max, smallDict, level + 1, result); anagram.remove(anagram.size()-1); } } } return results; }

    Read the article

  • How do I convert a number (as a String) to an array of bytes in Java?

    - by user1795595
    I'm creating a method specific method for a java project i'm working on. The UML given specifies the return type to be of static byte[] that accepts the arguments (String, byte) So far, looks like this: public static byte[] convertNumToDigitArray(String number, byte numDigits) { } This method is supposed to convert a number (as a String) to an array of bytes. The ordering must go from most to least significant digits. For example, if the number String is “732” then index 0 of the array should contain 7. The last argument (numDigits) should match the length of the string passed in. How do I do this?

    Read the article

  • Error setting env thru subprocess.call to run a python script on a remote linux machine

    - by John Smith
    I am running a python script on a windows machine to invoke another python script on a remote linux machine. I am using subprocess.call with ssh to do this, like below: subprocess.call('ssh -i <identify file> username@hostname python <script_on_linux_machine>') and this works fine. However, if I want to set some environment variables, like below: subprocess.call('ssh -i <identify file> username@hostname python <script_on_linux_machine>', env={key1:value1}) it fails. I get the following error: ssh_connect: getnameinfo failed ssh: connect to host <hostname> port 22: Operation not permitted 255 I've tried splitting the ssh commands into list and passing. Didn't help. I've tried to run other 'local'(windows) commands thru subprocess.call() and tried setting the env. It works fine. I've tried to run other commands(such as ls) on the remote linux machine. Again, subprocess.call() works fine, as long as I don't try to set the environment. What am I doing wrong? Would I be able to set the environment for a python script on a remote machine? Any help will be appreciated.

    Read the article

  • Multiple AHK questions

    - by Tomezor
    1 - Curious as to how to make a popup asking to confirm if I want to load the program before it loads. Example: ^g::Run C:\GW2\gw2.exe 2 - How to set a title(instead of the script name), align text within msgbox and control the perimeters of msgbox with this format: F1::msgbox, (LTrim Insert Text Here ) 3 - How to either temporarily pause and unpause a specific AHK script only allowing that hotkey to work within the script OR to disable scripted hotkeys while in a full screen application or game OR a "on/off pause/resume" command to disable multiple other commands such as ^g, ^h and the like.

    Read the article

  • OutOfMemoryError loading Bitmap via DefaultHttpClient

    - by Goddchen
    i have a simple problem: Although i'm using sampleSize properly, my code doesn't even reach the BitmapFactorycode, since DefaultHttpClient is already throwing the exception. Here is my code: DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(mSongInfo.imageLarge); HttpResponse response = client.execute(request); int sampleSize = 1; while (response.getEntity().getContentLength() / sampleSize / sampleSize > 100 * 1024) { sampleSize *= 2; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = sampleSize; final Bitmap bitmap = BitmapFactory.decodeStream(response .getEntity().getContent(), null, options); And here is the exception: 0 java.lang.OutOfMemoryError: (Heap Size=11463KB, Allocated=7623KB, Bitmap Size=9382KB) 1 at org.apache.http.util.ByteArrayBuffer.<init>(ByteArrayBuffer.java:53) 2 at org.apache.http.impl.io.AbstractSessionInputBuffer.init(AbstractSessionInputBuffer.java:82) 3 at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:98) 4 at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83) 5 at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170) 6 at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106) 7 at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129) 8 at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:173) 9 at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 10 at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 11 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359) 12 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 13 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 14 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 15 at de.goddchen.android.easysongfinder.fragments.SongFragment$1.run(SongFragment.java:79) 16 at java.lang.Thread.run(Thread.java:1027) As you can see, the code doesn't even reach the part where i check the size (Content-Length) of the image and calculate a proper sample size. I wasn't aware that simply calling DefaultHttpClient.execute(...) will already load the complete content into the memory. Am i doing something wrong? What is the right way to first retrieve the content length and then start reading the content from an InputStream? EDIT To avoid common answers that show how to load images from a URL: i already know how to do that, i have also posted the code above, so why do you keep referencing tutorials on that? I explicitly was very clear about the problem: Why is HttpClient.execute(...)already fetching the whole content and storing it in memory instead of providing a proper ÌnputStreamto me? Please don't post any beginner tutorials on how to load aBitmap`from a URL...

    Read the article

  • How to parse deeply nested using LINQ to XML

    - by Picflight
    How do I parse the following XML using LINQ? I need to insert into a database table OrderNumber, ShipAddress, ShipCity, ShipState for each Order & OrderCancelled. Then in a separate table I need to insert OrderId from the Returns/Amount section. <!-- language: lang-xml --> <?xml version="1.0" encoding="utf-8"?> <OrdersReport Date="2012-08-01"> <Client> <ClientId>1</ClientId> <Orders> <Order> <OrderNumber>1</OrderNumber> <ShipAddress>123 Main St.</ShipAddress> <ShipCity>MyCity</ShipCity> <ShipState>AZ</ShipState> </Order> <Order> <OrderNumber>2</OrderNumber> <ShipAddress>111 Main St.</ShipAddress> <ShipCity>OtherCity</ShipCity> <ShipState>AL</ShipState> </Order> <OrderCancelled> <OrderNumber>3</OrderNumber> <ShipAddress>111 Main St.</ShipAddress> <ShipCity>OtherCity</ShipCity> <ShipState>AL</ShipState> </OrderCancelled> </Orders> <Returns> <Amount> <OrderId>2</OrderId> <OrderId>3</OrderId> </Amount> </Returns> </Client> <Client> <ClientId>2</ClientId> <!-- Same Tree structure as Client 1 --> </Client> </OrdersReport> Not sure why the XML is not showing red and blue colors and not indenting properly. :-(

    Read the article

  • Is it possible to use Regex through Hexadecimal to find email addresses

    - by LukeJenx
    Not sure if this is even possible but I have been looking at using Regex to get an email address that is in Hex. Basically this is to build up some of my automated forensic tools but I am having problems on making a suitable Regex algorithm. Regex for email: /^([a-z0-9_.-]+)@([\da-z.-]+).([a-z.]{2,6})$/ Hex values: @ = 40 . = 2E .com = 636f6d _ = 5f A/a = 41/61 [1] Z/z = 5a/7a - = 2d This is what I have got at the moment (it only takes into account lower case and .com). But it doesn't work! Have I messed something simple up? "/^([61-7a]+)40([61-7a]+)23(636f6d)$/" [1] I know email can only be lower case but I need to take uppercase into account too.

    Read the article

  • "import as" leads to unresolved import error, "from .. import" does not

    - by Markus R.
    I'm trying to write some plugins for the irc bot supybot with eclipse/pydev. Pydev gives me errors about unresolved imports on supybot-modules/packages (e. g. import supybot.utils as utils), but works ok on e. g. "from supybot.commands import *". So I guess I set up dydev correctly, as it finds the wanted modules. The problem must be in pydev/eclipse, as the bot works correct and in eric5 I get also no errors about that. Removing the interpreter and setting it up didn't help. Any other ideas on how to fix this? System: Arch Linux, Eclipse Juno, PyDev 2.7.1, wanted (and set up) python interpreter is 2.7, supybot is installed in site-packages for Python 2.7. Edit: Just noticed: PyDev doesn't mark the "from ... import *" as error, but if I use functions imported from there I get an error on that function.

    Read the article

  • Delete duplicate rows, do not preserve one row

    - by Radley
    I need a query that goes through each entry in a database, checks if a single value is duplicated elsewhere in the database, and if it is - deletes both entries (or all, if more than two). Problem is the entries are URLs, up to 255 characters, with no way of identifying the row. Some existing answers on Stackoverflow do not work for me due to performance limitations, or they use uniqueid which obviously won't work when dealing with a string. Long Version: I have two databases containing URLs (and only URLs). One database has around 3,000 urls and the other around 1,000. However, a large majority of the 1,000 urls were taken from the 3,000 url database. I need to merge the 1,000 into the 3,000 as new entries only. For this, I made a third database with combined URLs from both tables, about 4,000 entries. I need to find all duplicate entries in this database and delete them (Both of them, without leaving either). I have followed the query of a few examples on this site, but whenever I try to delete both entries it ends up deleting all the entries, or giving sql errors. Alternatively: I have two databases, each containing the separate database. I need to check each row from one database against the other to find any that aren't duplicates, and then add those to a third database. Edit: I've got my own PHP solution which is pretty hacky, but works. I cannot answer my own question for 8 hours because I'm new, so here it is for now: I went with a PHP script to accomplish this, as I'm more familiar with PHP than MySQL. This generates a simple list of urls that only exist in the target database, but not both. If you have more than 7,000 entries to parse this may take awhile, and you will need to copy/paste the results into a text file or expand the script to store them back into a database. I'm just doing it manually to save time. Note: Uses MeekroDB <pre> <?php require('meekrodb.2.1.class.php'); DB::$user = 'root'; DB::$password = ''; DB::$dbName = 'testdb'; $all = DB::query('SELECT * FROM old_urls LIMIT 7000'); foreach($all as $row) { $test = DB::query('SELECT url FROM new_urls WHERE url=%s', $row['url']); if (!is_array($test)) { echo $row['url'] . "\n"; }else{ if (count($test) == 0) { echo $row['url'] . "\n"; } } } ?> </pre>

    Read the article

  • Encoding::UndefinedConversionError from email body

    - by raam86
    using mail for ruby I am getting this message: mail.rb:22:in `encode': "\xC7" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError) from mail.rb:22:in `<main>' If I remove encode I get a message ruby /var/lib/gems/1.9.1/gems/bson-1.7.0/lib/bson/bson_ruby.rb:63:in `rescue in to_utf8_binary': String not valid utf-8: "<div dir=\"ltr\"><div class=\"gmail_quote\">l<br><br><br><div dir=\"ltr\"><div class=\"gmail_quote\"><br><br><br><div dir=\"ltr\"><div class=\"gmail_quote\"><br><br><br><div dir=\"ltr\"><div dir=\"rtl\">\xC7\xE1\xE4\xD5 \xC8\xC7\xE1\xE1\xDB\xC9 \xC7\xE1\xDA\xD1\xC8\xED\xC9</div></div>\r\n</div><br></div>\r\n</div><br></div>\r\n</div><br></div>" (BSON::InvalidStringEncoding) This is my code: require 'mail' require 'mongo' connection = Mongo::Connection.new db = connection.db("DB") db = Mongo::Connection.new.db("DB") newsCollection = db["news"] Mail.defaults do retriever_method :pop3, :address => "pop.gmail.com", :port => 995, :user_name => 'my_username', :password => '*****', :enable_ssl => true end emails = Mail.last #Checks if email is multipart and decods accordingly. Put to extract UTF8 from body plain_part = emails.multipart? ? (emails.text_part ? emails.text_part.body.decoded : nil) : emails.body.decoded html_part = emails.html_part ? emails.html_part.body.decoded : nil mongoMessage = {"date" => emails.date.to_s , "subject" => emails.subject , "body" => plain_part.encode('UTF-8') } msgID = newsCollection.insert(mongoMessage) #add the document to the database and returns it's ID puts msgID For English and Hebrew it works perfectly but it seems gmail is sending arabic with different encoding. Replacing UTF-8 with ASCII-8BIT gives a similar error. I get the same result when using plain_part for plain email messages. I am handling emails from one specific source so I can put html_part with confidence it's not causing the error. To make it extra weird Subject in Arabic is rendered perfectly. What encoding should I use?

    Read the article

  • jQuery AJAX chained calls + Celery in Django

    - by user1029968
    Currently clicking one of the links in my application, triggers AJAX call (GET) that - if succeeds - triggers the second one and this second one - if succeeds - calls the third one. This way user can be informed which part of process started when clicking the link is currently ongoing. So in the template file in Django project, click callback body for link mentioned looks like below: $("#the-link").click(function(item)) { // CALL 1 $.ajax({ url: {% url ajax_call_1 %}, data: { // something } }) .done(function(call1Result) { // CALL 2 $.ajax({ url: {% url ajax_call_1 %}, data: { // call1Result passed here to CALL 2 } }) .done(function(call2Result) { // CALL 3 $.ajax({ url: {%url ajax_call_3 %}, data: { // call2Result passed here to CALL 3 } }) .done(function(call3Result) { // expected result if everything went fine console.log("wow, it worked!"); console.log(call3Result); }) .fail(function(errorObject) { console.log("call3 failed"); console.log(errorObject); } }) .fail(function(errorObject)) { console.log("call2 failed"); console.log(errorObject); } }) .fail(function(errorObject) { console.log("call1 failed"); console.log(errorObject); }); }); This works fine for me. The thing is, I'd like to prevent interrupting the following calls if the user closes the browser and the calls are not finished (as it will take some time to finish all three), as there is some additional logic in Django view functions called in each GET request. For example, if user clicks the link and closes the browser during CALL 1, is it possible to somehow go on with the following CALL 2 and CALL 3? I know that normally I'd be able to use Celery Task to process the function but is it still possible here with the chained calls mentioned? Any help is much appreciated!

    Read the article

  • JavaScript date suffix formatting

    - by TexasB
    I have done my due diligence in investigating this and not had any success yet. Being rather green with JavaScript I am seeking some help. I am wanting to display the date NOV2012<br> 2<sup>nd</sup><br> 5:00 PM I have everything working (not my script) except being able to get the date suffix to change to st, nd, rd, or th as the case may be. This is what I have: <pre> <abbr title="Month"> <script type="text/javascript"> var d=new Date(); var month=new Array(12); month[0]="Jan"; month[1]="Feb"; month[2]="Mar"; month[3]="Apr"; month[4]="May"; month[5]="Jun"; month[6]="Jul"; month[7]="Aug"; month[8]="Sep"; month[9]="Oct"; month[10]="Nov"; month[11]="Dec"; document.write(month[d.getMonth()]); </script></abbr> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) ordinal : function (number) { var d = number % 10; return (~~ (number % 100 / 10) === 1) ? 'th' : (d === 1) ? 'st' : (d === 2) ? 'nd' : (d === 3) ? 'rd' : 'th'; } }); </script> <sup>%</sup> <abbr><script type="text/javascript"> var d = new Date() document.write(d.getFullYear()) </script></abbr> <sub> <script type="text/javascript"> <!-- var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() if (minutes < 10){ minutes = "0" + minutes } document.write(hours + ":" + minutes + " ") if(hours > 11){ document.write("PM") } else { document.write("AM") } //--> </script> </sub> </pre> I know the issue is with this part: <pre> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) ordinal : function (number) { var d = number % 10; return (~~ (number % 100 / 10) === 1) ? 'th' : (d === 1) ? 'st' : (d === 2) ? 'nd' : (d === 3) ? 'rd' : 'th'; } }); </script> < sup > % < /sup > </pre> but I can't seem to work out the right fix. This is where it is sitting: http://www.bcreativeservices.com/ Thank you as always. B

    Read the article

  • Unable to save data in database manually and get latest auto increment id, cakePHP

    - by shabby
    I have checked this question as well and this one as well. I am trying to implement the model described in this question. What I want to do is, on the add function of message controller, create a record in thread table(this table only has 1 field which is primary key and auto increment), then take its id and insert it in the message table along with the user id which i already have, and then save it in message_read_state and thread_participant table. This is what I am trying to do in Thread Model: function saveThreadAndGetId(){ //$data= array('Thread' => array()); $data= array('id' => ' '); //Debugger::dump(print_r($data)); $this->save($data); debug('id: '.$this->id); $threadId = $this->getInsertID(); debug($threadId); $threadId = $this->getLastInsertId(); debug($threadId); die(); return $threadId; } $data= array('id' => ' '); This line from the above function adds a row in the thread table, but i am unable to retrieve the id. Is there any way I can get the id, or am I saving it wrongly? Initially I was doing the query thing in the message controller: $this->Thread->query('INSERT INTO threads VALUES();'); but then i found out that lastId function doesnt work on manual queries so i reverted.

    Read the article

  • Getting "Object is read only" error when setting ClientCredentials in WCF

    - by Paul Mrozowski
    I have a proxy object generated by Visual Studio (client side) named ServerClient. I am attempting to set ClientCredentials.UserName.UserName/Password before opening up a new connection using this code: InstanceContext context = new InstanceContext(this); m_client = new ServerClient(context); m_client.ClientCredentials.UserName.UserName = "Sample"; As soon as the code hits the UserName line it fails with an "Object is read-only" error. I know this can happen if the connection is already open or faulted, but at this point I haven't called context.Open() yet. I have configured the Bindings (which uses netTcpBinding) to use Message as it's security mode, and MessageClientCredentialType is set to UserName. Any ideas?

    Read the article

  • Web API, JavaScript, Chrome &amp; Cross-Origin Resource Sharing

    - by Brian Lanham
    The team spent much of the week working through this issues related to Chrome running on Windows 8 consuming cross-origin resources using Web API.  We thought it was resolved on day 2 but it resurfaced the next day.  We definitely resolved it today though.  I believe I do not fully understand the situation but I am going to explain what I know in an effort to help you avoid and/or resolve a similar issue. References We referenced many sources during our trial-and-error troubleshooting.  These are the links we reference in order of applicability to the solution: Zoiner Tejada JavaScript and other material from -> http://www.devproconnections.com/content1/topic/microsoft-azure-cors-141869/catpath/windows-azure-platform2/page/3 WebDAV Where I learned about “Accept” –>  http://www-jo.se/f.pfleger/cors-and-iis? IT Hit Tells about NOT using ‘*’ –> http://www.webdavsystem.com/ajax/programming/cross_origin_requests Carlos Figueira Sample back-end code (newer) –> http://code.msdn.microsoft.com/windowsdesktop/Implementing-CORS-support-a677ab5d (older version) –> http://code.msdn.microsoft.com/CORS-support-in-ASPNET-Web-01e9980a   Background As a measure of protection, Web designers (W3C) and implementers (Google, Microsoft, Mozilla) made it so that a request, especially a JSON request (but really any URL), sent from one domain to another will only work if the requestee “knows” about the requester and allows requests from it. So, for example, if you write a ASP.NET MVC Web API service and try to consume it from multiple apps, the browsers used may (will?) indicate that you are not allowed by showing an “Access-Control-Allow-Origin” error indicating the requester is not allowed to make requests. Internet Explorer (big surprise) is the odd-hair-colored step-child in this mix. It seems that running locally at least IE allows this for development purposes.  Chrome and Firefox do not.  In fact, Chrome is quite restrictive.  Notice the images below. IE shows data (a tabular view with one row for each day of a week) while Chrome does not (trust me, neither does Firefox).  Further, the Chrome developer console shows an XmlHttpRequest (XHR) error. Screen captures from IE (left) and Chrome (right). Note that Chrome does not display data and the console shows an XHR error. Why does this happen? The Web browser submits these requests and processes the responses and each browser is different. Okay, so, IE is probably the only one that’s truly different.  However, Chrome has a specific process of performing a “pre-flight” check to make sure the service can respond to an “Access-Control-Allow-Origin” or Cross-Origin Resource Sharing (CORS) request.  So basically, the sequence is, if I understand correctly:  1)Page Loads –> 2)JavaScript Request Processed by Browser –> 3)Browsers Prepares to Submit Request –> 4)[Chrome] Browser Submits Pre-Flight Request –> 5)Server Responds with HTTP 200 –> 6)Browser Submits Request –> 7)Server Responds with Data –> 8)Page Shows Data This situation occurs for both GET and POST methods.  Typically, GET methods are called with query string parameters so there is no data posted.  Instead, the requesting domain needs to be permitted to request data but generally nothing more is required.  POSTs on the other hand send form data.  Therefore, more configuration is required (you’ll see the configuration below).  AJAX requests are not friendly with this (POSTs) either because they don’t post in a form. How to fix it. The team went through many iterations of self-hair removal and we think we finally have a working solution.  The trial-and-error approach eventually worked and we referenced many sources for the information.  I indicate those references above.  There are basically three (3) tasks needed to make this work. Assumptions: You are using Visual Studio, Web API, JavaScript, and have Cross-Origin Resource Sharing, and several browsers. 1. Configure the client Joel Cochran centralized our “cors-oriented” JavaScript (from here). There are two calls including one for GET and one for POST function(url, data, callback) {             console.log(data);             $.support.cors = true;             var jqxhr = $.post(url, data, callback, "json")                 .error(function(jqXhHR, status, errorThrown) {                     if ($.browser.msie && window.XDomainRequest) {                         var xdr = new XDomainRequest();                         xdr.open("post", url);                         xdr.onload = function () {                             if (callback) {                                 callback(JSON.parse(this.responseText), 'success');                             }                         };                         xdr.send(data);                     } else {                         console.log(">" + jqXhHR.status);                         alert("corsAjax.post error: " + status + ", " + errorThrown);                     }                 });         }; The GET CORS JavaScript function (credit to Zoiner Tejada) function(url, callback) {             $.support.cors = true;             var jqxhr = $.get(url, null, callback, "json")                 .error(function(jqXhHR, status, errorThrown) {                     if ($.browser.msie && window.XDomainRequest) {                         var xdr = new XDomainRequest();                         xdr.open("get", url);                         xdr.onload = function () {                             if (callback) {                                 callback(JSON.parse(this.responseText), 'success');                             }                         };                         xdr.send();                     } else {                         alert("CORS is not supported in this browser or from this origin.");                     }                 });         }; The POST CORS JavaScript function (credit to Zoiner Tejada) Now you need to call these functions to get and post your data (instead of, say, using $.Ajax). Here is a GET example: corsAjax.get(url, function(data) { if (data !== null && data.length !== undefined) { // do something with data } }); And here is a POST example: corsAjax.post(url, item); Simple…except…you’re not done yet. 2. Change Web API Controllers to Allow CORS There are actually two steps here.  Do you remember above when we mentioned the “pre-flight” check?  Chrome actually asks the server if it is allowed to ask it for cross-origin resource sharing access.  So you need to let the server know it’s okay.  This is a two-part activity.  a) Add the appropriate response header Access-Control-Allow-Origin, and b) permit the API functions to respond to various methods including GET, POST, and OPTIONS.  OPTIONS is the method that Chrome and other browsers use to ask the server if it can ask about permissions.  Here is an example of a Web API controller thus decorated: NOTE: You’ll see a lot of references to using “*” in the header value.  For security reasons, Chrome does NOT recognize this is valid. [HttpHeader("Access-Control-Allow-Origin", "http://localhost:51234")] [HttpHeader("Access-Control-Allow-Credentials", "true")] [HttpHeader("Access-Control-Allow-Methods", "ACCEPT, PROPFIND, PROPPATCH, COPY, MOVE, DELETE, MKCOL, LOCK, UNLOCK, PUT, GETLIB, VERSION-CONTROL, CHECKIN, CHECKOUT, UNCHECKOUT, REPORT, UPDATE, CANCELUPLOAD, HEAD, OPTIONS, GET, POST")] [HttpHeader("Access-Control-Allow-Headers", "Accept, Overwrite, Destination, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control")] [HttpHeader("Access-Control-Max-Age", "3600")] public abstract class BaseApiController : ApiController {     [HttpGet]     [HttpOptions]     public IEnumerable<foo> GetFooItems(int id)     {         return foo.AsEnumerable();     }     [HttpPost]     [HttpOptions]     public void UpdateFooItem(FooItem fooItem)     {         // NOTE: The fooItem object may or may not         // (probably NOT) be set with actual data.         // If not, you need to extract the data from         // the posted form manually.         if (fooItem.Id == 0) // However you check for default...         {             // We use NewtonSoft.Json.             string jsonString = context.Request.Form.GetValues(0)[0].ToString();             Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();             fooItem = js.Deserialize<FooItem>(new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(jsonString)));         }         // Update the set fooItem object.     } } Please note a few specific additions here: * The header attributes at the class level are required.  Note all of those methods and headers need to be specified but we find it works this way so we aren’t touching it. * Web API will actually deserialize the posted data into the object parameter of the called method on occasion but so far we don’t know why it does and doesn’t. * [HttpOptions] is, again, required for the pre-flight check. * The “Access-Control-Allow-Origin” response header should NOT NOT NOT contain an ‘*’. 3. Headers and Methods and Such We had most of this code in place but found that Chrome and Firefox still did not render the data.  Interestingly enough, Fiddler showed that the GET calls succeeded and the JSON data is returned properly.  We learned that among the headers set at the class level, we needed to add “ACCEPT”.  Note that I accidentally added it to methods and to headers.  Adding it to methods worked but I don’t know why.  We added it to headers also for good measure. [HttpHeader("Access-Control-Allow-Methods", "ACCEPT, PROPFIND, PROPPA... [HttpHeader("Access-Control-Allow-Headers", "Accept, Overwrite, Destin... Next Steps That should do it.  If it doesn’t let us know.  What to do next?  * Don’t hardcode the allowed domains.  Note that port numbers and other domain name specifics will cause problems and must be specified.  If this changes do you really want to deploy updated software?  Consider Miguel Figueira’s approach in the following link to writing a custom HttpHeaderAttribute class that allows you to specify the domain names and then you can do it dynamically.  There are, of course, other ways to do it dynamically but this is a clean approach. http://code.msdn.microsoft.com/windowsdesktop/Implementing-CORS-support-a677ab5d

    Read the article

  • AJI Report 14 &ndash; Brian Lagunas on XAML and Windows 8

    - by Jeff Julian
    We sat down with Brian at the Iowa Code Camp to talk about his sessions, WPF, Application Design, and what Infragistics has to offer developers. Infragistics is a huge supporter of regional events like Iowa Code Camp and we want to thank them for their support of the Midwest region. Brian is a sharp guy and it was great to meet him and learn more about what makes him tick. Brian Lagunas is an INETA Community Speaker, co-leader of the Boise .Net Developers User Group (NETDUG), and original author of the Extended WPF Toolkit. He is a multi-recipient of the Microsoft Community Contributor Award and can be found speaking at a variety of user groups and code camps around the nation. Brian currently works at Infragistics as a Product Manager for the award winning NetAdvantage for WPF and Silverlight components. Before geeking out, Brian served his country in the United States Army as an infantryman and later served his local community as a deputy sheriff.   Listen to the Show   Site: http://brianlagunas.com Twitter: @BrianLagunas

    Read the article

  • Symantec Protection Suite and System Recovery 2011 Desktop Edition

    - by rihatum
    I am re-posting this as my previous question was being treated as if I am "Shopping or seeking Product Recommendations" even though I was NOT - BTW they have deleted my comments too which were not offensive in nature. anyway - I have re-phrased some parts of my question and I hope SF Admins "Do Not Modify / Edit" this one - will be most grateful for that. I have a lot of respect for the People who visit this SITE and help others ! Just To clarify : Just to go by SF rules - I am not seeking someone to Design this solution, I am simply seeking real world examples, experiences, technical expert opinions / suggestions, any tips or tricks they may have or any problems they may have faced while doing something similar above with these products. I am also not asking for Capacity Planning for Storage, We have done some research and I am seeking Expert Assurance / Suggestions. We (our company) are planning to deploy Symantec Endpoint Protection and Symantec Desktop Recovery 2011 Desktop Edition to our 3000 - 4000 workstations (Windows7 32 and 64) with a few 100s with Windows XP 32/64 Bit. I have read the implementation guide for SEP and have read tech-notes for Desktop Recovery 2011. Our team have planned to deploy this as follows : 1 x dedicated SQL 2008R2 for Symantec Endpoint Protection (Instead of using the Embedded Database) 1 x Dedicated SQL 2008R2 for Symantec Desktop Recovery 2011 (Instead of using the Embedded Database) 1 x Dedicated W2K8 R2 Box for the SEPM (Symantec Endpoint Protection Manager - Mgmt. APP) 1 x Dedicated W2K8 R2 Box for the Symantec Desktop Recovery 2011 Management Application Agent Deployment : As per Symantec Documentation for both of the above, an agent can be pushed via the Mgmt. Application (provided no firewalls are blocking ports required etc. - we have Windows firewall disabled already). Server Hardware : Per SQL Server : 16GB RAM + SAS DISKS + Dual XEON, RAID-10 for the SQL DB or I can always mount a LUN from our existing Hitachi or EMC SAN. SEPM Server : 16GB RAM + SAS DISKS + DUAL XEON System Recovery MGMT SERVER : 16GB RAM + SAS DISKS + DUAL XEON Above is the initial plan we have for 3000 - 4000 client workstation (Windows) Now my Questions :-) a) If we had these users distributed amongst two sites with AD DC / GC in each site, How would I restrict SEPM and Desktop Mgmt. solution to only check for users in their respective site ? b) At present all users are under one building but we are going to move some dept. to a new location (with dedicated connectivity), How would we control which SEPM / MGMT Server is responsible for which site ? c) We have netbackup in our environment backing up other servers, I am planning to protect these 4 (2 x SQL, 1 x SEPM, 1 x System Recovery Mgmt. Server) via netbackup or I can use System recovery 2011 server edition on all 4 of these boxes as well. (License is not an issue as we have the complete symantec portfolio included in our license). d) Now - Saving Desktop backups - What strategies have you implemented ? Any best practice recommendation for a large user base ? I was thinking to either mount a LUN from our Hitachi SAN on the Symantec Recovery Server itself or backup to the users hard drive locally and then copy it over to a network location ? Suggestions welcome :-) If you have anything to add / correct - that will be really helpful before diving into the actual implementation phase. Will be most grateful with your suggestions, recommendations and corrections with above - Many Thanks !

    Read the article

  • DHCP for Multiple Subnets

    - by TheD
    So this is the current setup - essentially I would like to get my DHCP server, serving DHCP requests for two seperate subnets. Netgear DG834G acting as a modem connected to a Sonicwall Pro 2040. X0 - LAN - 192.168.1.0/24 X1 - WAN - <WAN-IP> X2 - WLAN - 192.168.10.0/24 At the moment, I have a 2008R2 server with DHCP installed, with an IP address on the 192.168.1.0/24 range handling DHCP fine for this subnet. The Sonicwall is configured correctly - anything connected to the WLAN has Full Allow to anything in the LAN, and vice versa but it will not lease an IP from my Server. I've also added another IP address to the server, so the physical NIC now has two IP's: 192.168.1.2 and 192.168.10.2 with a DHCP scope configured for each. Still no luck! Any ideas? Thanks!

    Read the article

  • No HTTP Response from Tomcat 7 EC2 instance

    - by David Kaczynski
    I am new to EC2 (and Tomcat, for that matter), and I am trying to deploy a vanilla Tomcat 7 server to an Ubuntu 12.04.1 EC2 instance and access the default test site over HTTP. My EC2 instance is running, and the Security Group includes port 80: My /etc/tomcat7/server.xml config has been edited to listen for HTTP requests on port 80: 0 I have restarted my Tomcat 7 server via sudo service tomcat7 restart. However, according to sudo netstat -lnp, Tomcat is not listed as listening over port 80: I am unable to get any response from going to the ...amazonaws.com public DNS in a web browser. What am I missing?

    Read the article

  • IBM Server searching for secondary server

    - by user1241438
    I just bought the following server IBM System x3950 Server, 4 x 3.0GHz Dual Core, 32GB, 6 x 73.4GB 10K SAS RAID, 256MB BBWC, 2x Power, CD-RW/DVD When i boot it up, it says "Searching for secondary server" and hangs their for almost 10 mins. After 10 mins, it says timeout on searching chassis 2. But after this it proceed to boot the OS properly. But my frustration, i need to wait for almost 15 mins to boot everytime. How do i prevent this error message.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15  | Next Page >