Search Results

Search found 990 results on 40 pages for 'readline'.

Page 15/40 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • How do you configure Perl CPAN in Solaris?

    - by Casey
    I can't seem to get CPAN installs working on a Solaris machine. Here is my current output. ~# perl -MCPAN -eshell Terminal does not support AddHistory. cpan shell -- CPAN exploration and modules installation (v1.7601) ReadLine support available (try 'install Bundle::CPAN') cpan> install Bundle::LWP CPAN: Storable loaded ok LWP not available CPAN: Net::FTP loaded ok Fetching with Net::FTP: ftp://ftp.dti.ad.jp/pub/lang/CPAN/authors/01mailrc.txt.gz Couldn't fetch 01mailrc.txt.gz from ftp.dti.ad.jp ... ... This output is repeated for every mirror. Any ideas why this doesn't work?

    Read the article

  • How to choose python version to install in gentoo

    - by Shamanu4
    Hello, I'm using linux gentoo and i want to install python2.5 but it's a problem. emerge -av python shows These are the packages that would be merged, in order: Calculating dependencies... done! [ebuild U ] dev-lang/python-3.1.2-r3 [3.1.1-r1] USE="gdbm ipv6 ncurses readline ssl threads (wide-unicode%*) xml -build -doc -examples -sqlite* -tk -wininst (-ucs2%)" 9,558 kB [ebuild U ] app-admin/python-updater-0.8 [0.7] 8 kB and there are ebuild for more versions: # ls /usr/portage/dev-lang/python ChangeLog files Manifest metadata.xml python-2.4.6.ebuild python-2.5.4-r4.ebuild python-2.6.4-r1.ebuild python-2.6.5-r2.ebuild python-3.1.2-r3.ebuild How to choose ebuild that I want? (python-2.5.4-r4)

    Read the article

  • Ubuntu server failing daily

    - by deanvz
    Symptoms: Server becomes unresponsive - Increase in load, all services stop Loss of connectivity - Ping/SSH Flush MySQL hosts after reboot - As MySQL refuses new connections Intermittent Apache crashes Generally happens early morning hours - 2 days of the week are however excluded Changes made: Updated the OS - to Ubuntu 10.04.4 LTS Not sure if the MySQL server was also updated in the process Current MySQL version - mysql Ver 14.14 Distrib 5.1.63, for debian-linux-gnu (x86_64) using readline 6.1 Updated Plesk from 10.4.4 Update #47 to 11.0.9 Update #23 Rebooted on almost daily basis All crons stopped for the times corresponding to the server crashes Created a MySQL log to monitor the lock times on queries Possible causes: Failing hardware Incorrect software configuration (MySQL, Apache etc) Responsibilities: Small webserver Runs our billing system - WHMCS Responsible for CRONs Bulk-email solution - No delivery times coincide with server crashes Proposed solutions: Move machine over to VM Format and restore the Plesk server backup and take it from there? Side notes: Seems to be a general Apache failure across all our linux servers - Intermittent problem Are we doing something fundamentally wrong in the Apache config? (I understand that this is a secondary question, just making sure that it isnt possibly holding any relevance)

    Read the article

  • How do I stop GNU Freetalk from automatically filling in the buddy name?

    - by Journeyman Geek
    I'm using GNU Freetalk along with expect in order to send notifications to my phone – Freetalk has a readline interface, and I use expect to make a series of non interactive scripts that send information to another Jabber account. I'd like to have these scripts end freetalk 'properly' – that is to say user@domainname message one user@domainname message two /quit which would print out message one message two then quit. However Freetalk 'helpfully' adds user@domainame automatically so I get message one message two /quit as the output. The expect script still ends, but there's a delay. How would I stop Freetalk from adding in the 'buddy' address automatically?

    Read the article

  • Is it possible to have tab completion of drop-down lists in web pages in Firefox?

    - by Nick Booker
    Does anyone know of a Firefox plugin that would enable tab-completion (or some other key sequence like Alt-L) of items in drop-down lists in web forms? e.g. ou<TAB>in<TAB>s<TAB> for 'OurCompany - Internal Support' Vimperator's hints mode makes it very ergonomic to focus the drop-down list with a key sequence like f13 but the keyboard interface to the drop-down list still sucks. I very frequently have to pick items from a very long list with very long common prefixes among the entries (e.g. 30-40 starting with OurCompany -), which renders both the built-in keyboard interface and the mouse pretty slow and unergonomic. I basically want readline support for filling webforms!

    Read the article

  • How can I make Bash (or Zsh) run a particular command before each entered command?

    - by Peeja
    I'd like to configure Bash to run a particular command before running each command line I enter at the prompt. Specifically, I'd like to tell Vim (which is running in another terminal) to write all open buffers, because in my workflow if anything's unsaved when I leave Vim it's a mistake. Is there an option for this in Bash? If not, is there an option in Zsh? (There is a readline-based solution that somewhat fits this problem on another question, but it feels a bit hacky. It'll take it as a last resort.)

    Read the article

  • mysql Incorrect Information in File: (corrupt) error

    - by Nick M.
    I've recently suffered from a power outage on one of my monitoring servers at the office. The result of that outage caused for some database tables to get corrupted. I've successfully repaired 3-4 tables by using the "use_frm" option however there are still 3 that seem to be badly corrupted and are not responding to the mysql REPAIR command (with or without use_frm) mysql> REPAIR TABLE poller_item; +-------------------+--------+----------+---------------------------------------------- ------------+ | Table | Op | Msg_type | Msg_text | +-------------------+--------+----------+------------------------------------------------- ---------+ | cacti.poller_item | repair | Error | Incorrect information in file: './cacti/poller_item.frm' | | cacti.poller_item | repair | error | Corrupt | +-------------------+--------+----------+------------------------------------------------- ---------+ In this scenario are there any other way to repair a table? MySQL Version mysql Ver 14.14 Distrib 5.1.49, for debian-linux-gnu (x86_64) using readline 6.1

    Read the article

  • why SET timestamp in Slow query logs?

    - by user79483
    I use mysql Ver 14.12 Distrib 5.0.86, for unknown-linux-gnu (x86_64) using readline 5.1, I am seeing below query in the slow query logs: # Time: 110907 7:00:09 # User@Host: XXX[XXX] @ [10.1.10.1] # Query_time: 3 Lock_time: 0 Rows_sent: 1 Rows_examined: 347519 SET timestamp=1315378809; # administrator command: Quit; # User@Host: XXX[XXX] @ [10.1.10.1] # Query_time: 3 Lock_time: 0 Rows_sent: 0 Rows_examined: 0 use XXX; SET timestamp=1315378809; # administrator command: Quit; # User@Host: XXX[XXX] @ [10.1.10.1] # Query_time: 3 Lock_time: 0 Rows_sent: 1 Rows_examined: 1 use XXX; SET timestamp=1315378809; # administrator command: Quit; It is on a master, with one slave attached. why SET timestamp in Slow query logs ? anyone can help me.

    Read the article

  • What does this error mean (Can't create TCP/IP socket (24))?

    - by user105196
    I have web server with OS RHEL 6.2 and Mysql 5.5.23 on another server and the web server can read from Mysql server without problem, but some time I got this error: [Sun Sep 23 06:13:07 2012] [error] [client XXXXX] DBI connect('XXXX:192.168.1.2:3306','XXX',...) failed: Can't create TCP/IP socket (24) at /var/www/html/file.pm line 199. my question : What does this error mean (Can't create TCP/IP socket (24))? is it OS error or Mysql error ? perl -v This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi mysql -V mysql Ver 14.14 Distrib 5.5.23, for Linux (x86_64) using readline 5.1 su - mysql -s /bin/bash -c 'ulimit -a' core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 127220 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) 1024 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited

    Read the article

  • apt-get install Error

    - by LINUX4U
    syslogd during install give following error from the server? How to diagnose this problem debconf: falling back to frontend: Readline Selecting previously deselected package sysklogd. (Reading database ... 32541 files and directories currently installed.) Unpacking sysklogd (from .../sysklogd_1.5-5ubuntu4_amd64.deb) ... Selecting previously deselected package klogd. Unpacking klogd (from .../klogd_1.5-5ubuntu4_amd64.deb) ... Setting up sysklogd (1.5-5ubuntu4) ... * Starting system log daemon... [ OK ] Setting up klogd (1.5-5ubuntu4) ... * Starting kernel log daemon... [fail]

    Read the article

  • Mysql loses its root password

    - by RubyDev
    I am having a strange problem, my mysql loses/resets the root password automatically. By which I mean that it resets it to none. It has happened twice this month. I am worried that it can be a security issue as data is open waiting only for someone trying no password! Here is the version: mysql --version mysql Ver 14.14 Distrib 5.1.56, for redhat-linux-gnu (i386) using readline 5.1 Any help would be appreciated. Update: Output of select user, host, password from mysql.user; how it looks after the password got reset | root | localhost | | root | 127.0.0.1 | | | localhost | | | admin | localhost | ################################# | (I have removed the actual output with #) So all the passwords are blank, except for for another user named 'admin'

    Read the article

  • Mysql loses its root password

    - by RubyDev
    I am having a strange problem, my mysql loses/resets the root password automatically. By which I mean that it resets it to none. It has happened twice this month. I am worried that it can be a security issue as data is open waiting only for someone trying no password! Here is the version: mysql --version mysql Ver 14.14 Distrib 5.1.56, for redhat-linux-gnu (i386) using readline 5.1 Any help would be appreciated. Update: Output of select user, host, password from mysql.user; how it looks after the password got reset | root | localhost | | root | 127.0.0.1 | | | localhost | | | admin | localhost | ################################# | (I have removed the actual output with #) So all the passwords are blank, except for for another user named 'admin'

    Read the article

  • Convert extended ASCII characters to it's right presentation using Console.ReadKey() method and ConsoleKeyInfo variable

    - by mishamosher
    Readed about 30 minutes, and didn't found some specific for this in this site. Suppose the following, in C#, console application: ConsoleKeyInfo cki; cki = Console.ReadKey(true); Console.WriteLine(cki.KeyChar.ToString()); //Or Console.WriteLine(cki.KeyChar) as well Console.ReadKey(true); Now, let's put ¿ in the console entry, and asign it to cki via a Console.ReadKey(true). What will be shown isn't the ¿ symbol, the ¨ symbol is the one that's shown instead. And the same happens with many other characters. Examples: ñ shows ¤, ¡ shows -, ´ shows ï. Now, let's take the same code snipplet and add some things for a more Console.ReadLine() like behavior: string data = string.Empty; ConsoleKeyInfo cki; for (int i = 0; i < 10; i++) { cki = Console.ReadKey(true); data += cki.KeyChar; } Console.WriteLine(data); Console.ReadKey(true); The question, how to handle this by the right way, end printing the right characters that should be stored on data, not things like ¨, ¤, -, ï, etc? Please note that I want a solution that works with ConsoleKeyInfo and Console.ReadKey(), not use other variable types, or read methods. EDIT: Because ReadKey() method, that comes from Console namespace, depends on Kernel32.dll and it definetively bad handles the extended ASCII and unicode, it's not an option anymore to just find a valid conversion for what it returns. The only valid way to handle the bad behavior of ReadKey() is to use the cki.Key property that's written in cki = Console.ReadKey(true) execution and apply a switch to it, then, return the right values on dependence of what key was pressed. For example, to handle the Ñ key pressing: string data = string.Empty; ConsoleKeyInfo cki; cki = Console.ReadKey(true); switch (cki.Key) { case ConsoleKey.Oem3: if (cki.Modifiers.ToString().Contains("Shift")) //Could added handlers for Alt and Control, but not putted in here to keep the code small and simple data += "Ñ"; else data += "ñ"; break; } Console.WriteLine(data); Console.ReadKey(true); So, now the question has a wider focus... Which others functions completes it's execution with only one key pressed, and returns what's pressed (a substitute of ReadKey())? I think that there's not such substitutes, but a confirmed answer would be usefull. EDIT2: HA! Found the way, for something I used for so many times Windows 98 SE. There are the codepages, the ones responsibles for how's presented the info in the console. ReadLine() reconfigures the codepage to use properly the extended ASCII and Unicode characters. ReadKey() leaves it in EN-US default (codepage 850). Just use a codepage that prints the characters you want, and that's all. Refer to http://en.wikipedia.org/wiki/Code_page for some of them :) So, for the Ñ key press, the solution is this: Console.OutputEncoding = Encoding.GetEncoding(1252); //Also 28591 is valid for `Ñ` key, and others too string data = string.Empty; ConsoleKeyInfo cki; cki = Console.ReadKey(true); data += cki.KeyChar; Console.WriteLine(data); Console.ReadKey(true); Simple :) Now I'm wrrr with myself... how could I forget those codepages!? Question answered, so, no more about this!

    Read the article

  • HttpParsing for hypertext

    - by Nani
    I am in process of getting all hierarchical links from a given link and validating them; This is the code I wrote. But I am not feeling it as efficient. Reasons are: 1.For the non unique links which open same page, code is getting sub-links again and again 2.Is the code getting all links? 3.Is it making valid URLs from the sub-links it derived? 4.May be some other reasons about which I have no idea. Please suggest me how to make this piece of code efficient . Thank you. class Program { public static ArrayList sublink = new ArrayList(); public static ArrayList subtitle = new ArrayList(); public static int ini = 0, len_o, len_n, counter = 0; static void Main(string[] args) { // Address of URL string URL = "http://www.techonthenet.com/"; sublink.Add(URL); l: len_o = sublink.Count; len_o); Console.WriteLine("-------------Level:" + counter++); for (int i = ini; i < len_o; i++) test(sublink[i].ToString()); len_n = sublink.Count; if (len_o < len_n) { ini = len_o; goto l; } Console.ReadKey(); } //method to get the sub-links public static void test(string URL) { try { // Get HTML data WebClient client = new WebClient(); Stream data = client.OpenRead(URL); StreamReader reader = new StreamReader(data); string str = "", htmldata = "", temp; int n1, n2; str = reader.ReadLine(); while (str != null) { htmldata += str; str = reader.ReadLine(); } data.Close(); for (int i = 0; i < htmldata.Length - 5; i++) { if (htmldata.Substring(i, 5) == "href=") { n1 = htmldata.Substring(i + 6, htmldata.Length - (i + 6)).IndexOf("\""); temp = htmldata.Substring(i + 6, n1); if (temp.Length > 4 && temp.Substring(0, 4) != "http") { if(temp.Substring(0,1)!="/") temp=URL.Substring(0,URL.IndexOf(".com/")+5)+temp; else temp = URL.Substring(0, URL.IndexOf(".com/") + 5) + temp.Remove(0,1); } if (temp.Length < 4) temp = URL.Substring(0, URL.IndexOf(".com/") + 5) + temp; sublink.Add(temp); n2 = htmldata.Substring(i + n1 + 1, htmldata.Length - (i + n1 + 1)).IndexOf("<"); subtitle.Add(htmldata.Substring(i + 6 + n1 + 2, n2 - 7)); i += temp.Length + htmldata.Substring(i + 6 + n1 + 2, n2 - 7).Length; } } for (int i = len_n; i < sublink.Count; i++) Console.WriteLine(i + "--> " + sublink[i]); } catch (WebException exp) { Console.WriteLine("URL Could not be Resolved" + URL); Console.WriteLine(exp.Message, "Exception"); } } }

    Read the article

  • Best style for Python programs: what do you suggest?

    - by Noctis Skytower
    A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements). #! /usr/bin/env python ################################################################################ """\ CLASS INFORMATION ----------------- Program Name: Program 11 Programmer: Stephen Chappell Instructor: Stephen Chappell for CS 999-0, Python Due Date: 17 May 2010 DOCUMENTATION ------------- This is a simple encryption program that can encode and decode messages.""" ################################################################################ import sys KEY_FILE = 'Key.txt' BACKUP = '''\ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO\ PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ _@/6-UC'GzaV0%5Mo9g+yNh8b">Bi=<Lx [sQn#^R.D2Xc(\ Jm!4e${lAEWud&t7]H\`}pvPw)FY,Z~?qK|3SOfk*:1;jTrI''' ################################################################################ def main(): "Run the program: loads key, runs processing loop, and saves key." encode_map, decode_map = load_key(KEY_FILE) try: run_interface_loop(encode_map, decode_map) except SystemExit: pass save_key(KEY_FILE, encode_map) def run_interface_loop(encode_map, decode_map): "Shows the menu and runs the appropriate command." print('This program handles encryption via a customizable key.') while True: print('''\ MENU ==== (1) Encode (2) Decode (3) Custom (4) Finish''') switch = get_character('Select: ', tuple('1234')) FUNC[switch](encode_map, decode_map) def get_character(prompt, choices): "Gets a valid menu option and returns it." while True: sys.stdout.write(prompt) sys.stdout.flush() line = sys.stdin.readline()[:-1] if not line: sys.exit() if line in choices: return line print(repr(line), 'is not a valid choice.') ################################################################################ def load_key(filename): "Gets the key file data and returns encoding/decoding dictionaries." plain, cypher = open_file(filename) return dict(zip(plain, cypher)), dict(zip(cypher, plain)) def open_file(filename): "Load the keys and tries to create it when not available." while True: try: with open(filename) as file: plain, cypher = file.read().split('\n') return plain, cypher except: with open(filename, 'w') as file: file.write(BACKUP) def save_key(filename, encode_map): "Dumps the map into two buffers and saves them to the key file." plain = cypher = str() for p, c in encode_map.items(): plain += p cypher += c with open(filename, 'w') as file: file.write(plain + '\n' + cypher) ################################################################################ def encode(encode_map, decode_map): "Encodes message for the user." print('Enter your message to encode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(encode_map[char] if char in encode_map else char) def decode(encode_map, decode_map): "Decodes message for the user." print('Enter your message to decode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(decode_map[char] if char in decode_map else char) def custom(encode_map, decode_map): "Allows user to edit the encoding/decoding dictionaries." plain, cypher = get_new_mapping() for p, c in zip(plain, cypher): encode_map[p] = c decode_map[c] = p ################################################################################ def get_message(): "Gets and returns text entered by the user (until EOF)." buffer = [] while True: line = sys.stdin.readline() if line: buffer.append(line) else: return ''.join(buffer) def get_new_mapping(): "Prompts for strings to edit encoding/decoding maps." while True: plain = get_unique_chars('What do you want to encode from?') cypher = get_unique_chars('What do you want to encode to?') if len(plain) == len(cypher): return plain, cypher print('Both lines should have the same length.') def get_unique_chars(prompt): "Gets strings that only contain unique characters." print(prompt) while True: line = input() if len(line) == len(set(line)): return line print('There were duplicate characters: please try again.') ################################################################################ # This map is used for dispatching commands in the interface loop. FUNC = {'1': encode, '2': decode, '3': custom, '4': lambda a, b: sys.exit()} ################################################################################ if __name__ == '__main__': main() For all those Python programmers out there, your help is being requested. How should the formatting (not necessarily the coding by altered to fit Python's style guide? My friend does not need to be learning things that are not correct. If you have suggestions on the code, feel free to post them to this wiki as well.

    Read the article

  • Differing styles in Python program: what do you suggest?

    - by Noctis Skytower
    A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements). #! /usr/bin/env python ################################################################################ """\ CLASS INFORMATION ----------------- Program Name: Program 11 Programmer: Stephen Chappell Instructor: Stephen Chappell for CS 999-0, Python Due Date: 17 May 2010 DOCUMENTATION ------------- This is a simple encryption program that can encode and decode messages.""" ################################################################################ import sys KEY_FILE = 'Key.txt' BACKUP = '''\ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO\ PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ _@/6-UC'GzaV0%5Mo9g+yNh8b">Bi=<Lx [sQn#^R.D2Xc(\ Jm!4e${lAEWud&t7]H\`}pvPw)FY,Z~?qK|3SOfk*:1;jTrI''' ################################################################################ def main(): "Run the program: loads key, runs processing loop, and saves key." encode_map, decode_map = load_key(KEY_FILE) try: run_interface_loop(encode_map, decode_map) except SystemExit: pass save_key(KEY_FILE, encode_map) def run_interface_loop(encode_map, decode_map): "Shows the menu and runs the appropriate command." print('This program handles encryption via a customizable key.') while True: print('''\ MENU ==== (1) Encode (2) Decode (3) Custom (4) Finish''') switch = get_character('Select: ', tuple('1234')) FUNC[switch](encode_map, decode_map) def get_character(prompt, choices): "Gets a valid menu option and returns it." while True: sys.stdout.write(prompt) sys.stdout.flush() line = sys.stdin.readline()[:-1] if not line: sys.exit() if line in choices: return line print(repr(line), 'is not a valid choice.') ################################################################################ def load_key(filename): "Gets the key file data and returns encoding/decoding dictionaries." plain, cypher = open_file(filename) return dict(zip(plain, cypher)), dict(zip(cypher, plain)) def open_file(filename): "Load the keys and tries to create it when not available." while True: try: with open(filename) as file: plain, cypher = file.read().split('\n') return plain, cypher except: with open(filename, 'w') as file: file.write(BACKUP) def save_key(filename, encode_map): "Dumps the map into two buffers and saves them to the key file." plain = cypher = str() for p, c in encode_map.items(): plain += p cypher += c with open(filename, 'w') as file: file.write(plain + '\n' + cypher) ################################################################################ def encode(encode_map, decode_map): "Encodes message for the user." print('Enter your message to encode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(encode_map[char] if char in encode_map else char) def decode(encode_map, decode_map): "Decodes message for the user." print('Enter your message to decode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(decode_map[char] if char in decode_map else char) def custom(encode_map, decode_map): "Allows user to edit the encoding/decoding dictionaries." plain, cypher = get_new_mapping() for p, c in zip(plain, cypher): encode_map[p] = c decode_map[c] = p ################################################################################ def get_message(): "Gets and returns text entered by the user (until EOF)." buffer = [] while True: line = sys.stdin.readline() if line: buffer.append(line) else: return ''.join(buffer) def get_new_mapping(): "Prompts for strings to edit encoding/decoding maps." while True: plain = get_unique_chars('What do you want to encode from?') cypher = get_unique_chars('What do you want to encode to?') if len(plain) == len(cypher): return plain, cypher print('Both lines should have the same length.') def get_unique_chars(prompt): "Gets strings that only contain unique characters." print(prompt) while True: line = input() if len(line) == len(set(line)): return line print('There were duplicate characters: please try again.') ################################################################################ # This map is used for dispatching commands in the interface loop. FUNC = {'1': encode, '2': decode, '3': custom, '4': lambda a, b: sys.exit()} ################################################################################ if __name__ == '__main__': main() For all those Python programmers out there, your help is being requested. How should the formatting (not necessarily the coding by altered to fit Python's style guide? My friend does not need to be learning things that are not correct. If you have suggestions on the code, feel free to post them to this wiki as well.

    Read the article

  • Input not cleared.

    - by SoulBeaver
    As the question says, for some reason my program is not flushing the input or using my variables in ways that I cannot identify at the moment. This is for a homework project that I've gone beyond what I had to do for it, now I just want the program to actually work :P Details to make the finding easier: The program executes flawlessly on the first run through. All throws work, only the proper values( n 0 ) are accepted and turned into binary. As soon as I enter my terminate input, the program goes into a loop and only asks for the termiante again like so: When I run this program on Netbeans on my Linux Laptop, the program crashes after I input the terminate value. On Visual C++ on Windows it goes into the loop like just described. In the code I have tried to clear every stream and initialze every variable new as the program restarts, but to no avail. I just can't see my mistake. I believe the error to lie in either the main function: int main( void ) { vector<int> store; int terminate = 1; do { int num = 0; string input = ""; if( cin.fail() ) { cin.clear(); cin.ignore( numeric_limits<streamsize>::max(), '\n' ); } cout << "Please enter a natural number." << endl; readLine( input, num ); cout << "\nThank you. Number is being processed..." << endl; workNum( num, store ); line; cout << "Go again? 0 to terminate." << endl; cin >> terminate // No checking yet, just want it to work! cin.clear(); }while( terminate ); cin.get(); return 0; } or in the function that reads the number: void readLine( string &input, int &num ) { int buf = 1; stringstream ss; vec_sz size; if( ss.fail() ) { ss.clear(); ss.ignore( numeric_limits<streamsize>::max(), '\n' ); } if( getline( cin, input ) ) { size = input.size(); for( int loop = 0; loop < size; ++loop ) if( isalpha( input[loop] ) ) throw domain_error( "Invalid Input." ); ss << input; ss >> buf; if( buf <= 0 ) throw domain_error( "Invalid Input." ); num = buf; ss.clear(); } }

    Read the article

  • How can I get SQL Server transactions to use record-level locks?

    - by Joe White
    We have an application that was originally written as a desktop app, lo these many years ago. It starts a transaction whenever you open an edit screen, and commits if you click OK, or rolls back if you click Cancel. This worked okay for a desktop app, but now we're trying to move to ADO.NET and SQL Server, and the long-running transactions are problematic. I found that we'll have a problem when multiple users are all trying to edit (different subsets of) the same table at the same time. In our old database, each user's transaction would acquire record-level locks to every record they modified during their transaction; since different users were editing different records, everyone gets their own locks and everything works. But in SQL Server, as soon as one user edits a record inside a transaction, SQL Server appears to get a lock on the entire table. When a second user tries to edit a different record in the same table, the second user's app simply locks up, because the SqlConnection blocks until the first user either commits or rolls back. I'm aware that long-running transactions are bad, and I know that the best solution would be to change these screens so that they no longer keep transactions open for a long time. But since that would mean some invasive and risky changes, I also want to research whether there's a way to get this code up and running as-is, just so I know what my options are. How can I get two different users' transactions in SQL Server to lock individual records instead of the entire table? Here's a quick-and-dirty console app that illustrates the issue. I've created a database called "test1", with one table called "Values" that just has ID (int) and Value (nvarchar) columns. If you run the app, it asks for an ID to modify, starts a transaction, modifies that record, and then leaves the transaction open until you press ENTER. I want to be able to start the program and tell it to update ID 1; let it get its transaction and modify the record; start a second copy of the program and tell it to update ID 2; have it able to update (and commit) while the first app's transaction is still open. Currently it freezes at step 4, until I go back to the first copy of the app and close it or press ENTER so it commits. The call to command.ExecuteNonQuery blocks until the first connection is closed. public static void Main() { Console.Write("ID to update: "); var id = int.Parse(Console.ReadLine()); Console.WriteLine("Starting transaction"); using (var scope = new TransactionScope()) using (var connection = new SqlConnection(@"Data Source=localhost\sqlexpress;Initial Catalog=test1;Integrated Security=True")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = "UPDATE [Values] SET Value = 'Value' WHERE ID = " + id; Console.WriteLine("Updating record"); command.ExecuteNonQuery(); Console.Write("Press ENTER to end transaction: "); Console.ReadLine(); scope.Complete(); } } Here are some things I've already tried, with no change in behavior: Changing the transaction isolation level to "read uncommitted" Specifying a "WITH (ROWLOCK)" on the UPDATE statement

    Read the article

  • Using IF statements to find string length in array for alignment (Visual Basic)

    - by Brodoin
    My question is just as it says in the title. How would one use IF statements to find the string-length of content in an array, and then make it so that they show up in a Rich Text Box with the left sides aligned? Noting that one value in my array is a Decimal. Imports System.IO Imports System.Convert Public Class frmAll 'Declare Streamreader Private objReader As StreamReader 'Declare arrays to hold the information Private strNumber(24) As String Private strName(24) As String Private strSize(24) As String Private decCost(24) As Integer Private Sub frmAll_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Set objReader objReader = New StreamReader("products.csv") 'Call the FillArray sub to fill the array Call FillArray() End Sub Private Sub FillArray() 'Declare variables and arrays Dim decCost(24, 1) As Decimal Dim strFields() As String Dim strRec As String Dim intCount As Integer = 0 Dim chrdelim As Char = ToChar(",") 'Set strRec to read the lines strRec = objReader.ReadLine 'Do while loop to fill array. Do While strRec <> Nothing strFields = strRec.Split(chrdelim) strNumber(intCount) = strFields(0) strName(intCount) = strFields(1) strSize(intCount) = strFields(2) decCost(intCount, 0) = ToDecimal(strFields(3)) decCost(intCount, 1) = ToDecimal(strFields(4)) 'Set strRec to read the lines again strRec = objReader.ReadLine 'increment the index intCount += 1 Loop 'Call the Calculate sub for calculation Call Calculate(decCost) End Sub Private Sub Calculate(ByVal numIn(,) As Decimal) 'Define arrays to hold total cost Dim decRowTotal(24) As Decimal 'Define variables to hold the counters for rows and columns Dim intR As Integer Dim intC As Integer 'Calcualte total cost For intC = 0 To 1 For intR = 0 To 24 decRowTotal(intR) += numIn(intR, intC) * 1 Next Next 'Call the Output sub to configure the output. Call Output(numIn, decRowTotal) End Sub Private Sub Output(ByVal NumIn(,) As Decimal, _ ByVal RowTotalIn() As Decimal) 'Variables Dim strOut As String Dim intR As Integer = 0 Dim intC As Integer = 0 'Set header for output. strOut = "ID" & vbTab & "Item" & vbTab & vbTab & vbTab & "Size" & _ vbTab & vbTab & vbTab & vbTab & "Total Price" & _ vbCrLf & "---------- ... -------------------------" & vbCrLf 'For loop to add each line to strOut, setting 'the RowTotalIn to currency. For intC = 0 To 24 strOut &= strNumber(intC) & vbTab strOut &= strName(intC) & vbTab strOut &= strSize(intC) & vbTab strOut &= RowTotalIn(intC).ToString("c") & vbCrLf Next 'Add strOut to rbtAll rtbAll.Text = strOut End Sub End Class Output It shows up with vbTabs in my output, but still, it looks similar in that they are not aligned. The first two do, but after that they are not, and I am totally lost. P0001 Coffee - Colombian Supreme 24/Case: Pre-Ground 1.75 Oz Bags $16.50 P0002 Coffee - Hazelnut 24/Case: Pre-Ground 1.75 Oz Bags $24.00 P0003 Coffee - Mild Blend 24/Case: Pre-Ground 1.75 Oz Bags $20.50 P0004 Coffee - Assorted Flavors 18/Case. Pre-Ground 1.75 Oz Bags $23.50 P0005 Coffee - Decaf 24/Case: Pre-Ground 1.75 Oz Bags $20.50

    Read the article

  • Need help in creating test appliaction in Java and passing parameters into a new designed Java API.

    - by Christophe
    Need help, Please!!! By following the protocol, the Request should be built in 5 byte length, including 1 byte for changing Braud rate (Speed), and send request to a RS-232 port. Protocol: --------------- Request for the command processing, with optional extra byte for changing Baud Rate: LGT : length message ( LGT = 5 ) TYPE : 0x06 TO(time out): 0x0000 CMD : (1 byte) 0x02 application update Baud Rate : (1 byte) 0xNN (optional parameter to change baud rate of the Mnt App) where NN can be: 0x00 = No Baud Rate Change (similar to 4-byte command above) 0x09 = Change to 9600 Baud for Application Update speed 0x0A = Change to 19200 Baud for Application Update speed 0x0E = Change to 115200 Baud for Application Update speed All other bytes are not accepted and will result in a status of 0x01. ------------------ I'm trying to test if my code works or not by creating another class (TestApplication.java) and pass the "3 differenr Baut rate" to this CPXAppliaction. the 3 Baud Rate is supposed to input by reading a file.txt. Question: How do you think these code (first half)? please don't warry about the details about the "sending part". I mean, do I need setter/getter for the "speed" parameter pass? I created the demo test class DemoApp.java (input speed by reading a txt file, and pass into CPXAppliaction). how do you think about that code? Many thanks to you guys!! public class CPXApplication extends CPXCommand { private int speed; . public CPXApplication() { speed = 9600; } public CPXApplication(int speedinit) { speed = speedinit; // TODO: where to get the speed? } protected void buildRequest() throws ElitePortException { String trans = ""; // build the full-qualified message following the protocol trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 5); trans = addToRequest(trans, (char) 6); trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 2); switch (speed) { case 9600: trans = addToRequest(trans, (char) 0x09); break; case 19200: trans = addToRequest(trans, (char) 0x0A); break; case 115200: trans = addToRequest(trans, (char) 0x0E); break; default: // TODO: unexpected baud rate. throw(); break; } trans = EncryptBinary(trans); trans = "F0." + trans; wrapRequest(trans); } protected String addToRequest(String req, char c) { return req + c; } protected String addToRequest(String req, String s) { return req + s; } protected String addToRequest(String req) { return req; } public void analyzeResponse() { //.............. } } Here is the demo test code: package com.ingenico.testApp; import com.ingenico.EliteFd.; import java.util.Scanner; import java.io.; class Run { public static void run() { CPXAppliactionUpdate input = new CpXApplicationUpdate(); int lineno = 0; try { FileReader fr = new FileReader("baudRateSpeed.txt"); BufferedReader reader = new BufferedReader(fr); String line = reader.readLine(); Scanner scan = null; while (line != null) { scan = new Scanner(line); String speed; speed = scan.next(); if (lineno == 0) { input.speed = speed; lineno++; } else { input = cpxapplicationupdate(speed, input); } line = reader.readLine(); } reader.close(); } catch (FileNotFoundException e) { System.out.println("Could not find the file"); } catch (IOException e) { System.out.println("Had a problem reading from file"); } } public class DemoApp{ public void main(String args[]) { run(); } } }

    Read the article

  • Need help in creating test application in Java and passing parameters into a new designed Java API.

    - by Christophe
    Need help, Please!!! By following the protocol, the Request should be built in 5 byte length, including 1 byte for changing Braud rate (Speed), and send request to a RS-232 port. Protocol: Request for the command processing, with optional extra byte for changing Baud Rate: LGT : length message ( LGT = 5 ) TYPE : 0x06 TO(time out): 0x0000 CMD : (1 byte) 0x02 application update Baud Rate : (1 byte) 0xNN (optional parameter to change baud rate of the Mnt App) where NN can be: 0x00 = No Baud Rate Change (similar to 4-byte command above) 0x09 = Change to 9600 Baud for Application Update speed 0x0A = Change to 19200 Baud for Application Update speed 0x0E = Change to 115200 Baud for Application Update speed All other bytes are not accepted and will result in a status of 0x01. I'm trying to test if my code works or not by creating another class (TestApplication.java) and pass the "3 differenr Baut rate" to this CPXAppliaction. the 3 Baud Rate is supposed to input by reading a file.txt. Question: How do you think these code (first half)? please don't warry about the details about the "sending part". I mean, do I need setter/getter for the "speed" parameter pass? I created the demo test class DemoApp.java (input speed by reading a txt file, and pass into CPXAppliaction). how do you think about that code? Many thanks to you guys!! public class CPXApplication extends CPXCommand { private int speed; . public CPXApplication() { speed = 9600; } public CPXApplication(int speedinit) { speed = speedinit; // TODO: where to get the speed? } protected void buildRequest() throws ElitePortException { String trans = ""; // build the full-qualified message following the protocol trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 5); trans = addToRequest(trans, (char) 6); trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 2); switch (speed) { case 9600: trans = addToRequest(trans, (char) 0x09); break; case 19200: trans = addToRequest(trans, (char) 0x0A); break; case 115200: trans = addToRequest(trans, (char) 0x0E); break; default: // TODO: unexpected baud rate. throw(); break; } trans = EncryptBinary(trans); trans = "F0." + trans; wrapRequest(trans); } protected String addToRequest(String req, char c) { return req + c; } protected String addToRequest(String req, String s) { return req + s; } protected String addToRequest(String req) { return req; } public void analyzeResponse() { //.............. } } Here is the demo test code: class Run { public static void run() { CPXAppliaction input = new CpXApplication(); int lineno = 0; try { FileReader fr = new FileReader("baudRateSpeed.txt"); BufferedReader reader = new BufferedReader(fr); String line = reader.readLine(); Scanner scan = null; while (line != null) { scan = new Scanner(line); String speed; speed = scan.next(); if (lineno == 0) { input.speed = speed; lineno++; } else { input = cpxapplication(speed, input); } line = reader.readLine(); } reader.close(); } catch (FileNotFoundException e) { System.out.println("Could not find the file"); } catch (IOException e) { System.out.println("Had a problem reading from file"); } } } public class DemoApp{ public void main(String args[]) { run(); }

    Read the article

  • Java Logger API

    - by Koppar
    This is a more like a tip rather than technical write up and serves as a quick intro for newbies. The logger API helps to diagnose application level or JDK level issues at runtime. There are 7 levels which decide the detailing in logging (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST). Its best to start with highest level and as we narrow down, use more detailed logging for a specific area. SEVERE is the highest and FINEST is the lowest. This may not make sense until we understand some jargon. The Logger class provides the ability to stream messages to an output stream in a format that can be controlled by the user. What this translates to is, I can create a logger with this simple invocation and use it add debug messages in my class: import java.util.logging.*; private static final Logger focusLog = Logger.getLogger("java.awt.focus.KeyboardFocusManager"); if (focusLog.isLoggable(Level.FINEST)) { focusLog.log(Level.FINEST, "Calling peer setCurrentFocusOwner}); LogManager acts like a book keeper and all the getLogger calls are forwarded to LogManager. The LogManager itself is a singleton class object which gets statically initialized on JVM start up. More on this later. If there is no existing logger with the given name, a new one is created. If there is one (and not yet GC’ed), then the existing Logger object is returned. By default, a root logger is created on JVM start up. All anonymous loggers are made as the children of the root logger. Named loggers have the hierarchy as per their name resolutions. Eg: java.awt.focus is the parent logger for java.awt.focus.KeyboardFocusManager etc. Before logging any message, the logger checks for the log level specified. If null is specified, the log level of the parent logger will be set. However, if the log level is off, no log messages would be written, irrespective of the parent’s log level. All the messages that are posted to the Logger are handled as a LogRecord object.i.e. FocusLog.log would create a new LogRecord object with the log level and message as its data members). The level of logging and thread number are also tracked. LogRecord is passed on to all the registered Handlers. Handler is basically a means to output the messages. The output may be redirected to either a log file or console or a network logging service. The Handler classes use the LogManager properties to set filters and formatters. During initialization or JVM start up, LogManager looks for logging.properties file in jre/lib and sets the properties if the file is provided. An alternate location for properties file can also be specified by setting java.util.logging.config.file system property. This can be set in Java Control Panel ? Java ? Runtime parameters as -Djava.util.logging.config.file = <mylogfile> or passed as a command line parameter java -Djava.util.logging.config.file = C:/Sunita/myLog The redirection of logging depends on what is specified rather registered as a handler with JVM in the properties file. java.util.logging.ConsoleHandler sends the output to system.err and java.util.logging.FileHandler sends the output to file. File name of the log file can also be specified. If you prefer XML format output, in the configuration file, set java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter and if you prefer simple text, set set java.util.logging.FileHandler.formatter =java.util.logging.SimpleFormatter Below is the default logging Configuration file: ############################################################ # Default Logging Configuration File # You can use a different file by specifying a filename # with the java.util.logging.config.file system property. # For example java -Djava.util.logging.config.file=myfile ############################################################ ############################################################ # Global properties ############################################################ # "handlers" specifies a comma separated list of log Handler # classes. These handlers will be installed during VM startup. # Note that these classes must be on the system classpath. # By default we only configure a ConsoleHandler, which will only # show messages at the INFO and above levels. handlers= java.util.logging.ConsoleHandler # To also add the FileHandler, use the following line instead. #handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler # Default global logging level. # This specifies which kinds of events are logged across # all loggers. For any given facility this global level # can be overriden by a facility specific level # Note that the ConsoleHandler also has a separate level # setting to limit messages printed to the console. .level= INFO ############################################################ # Handler specific properties. # Describes specific configuration info for Handlers. ############################################################ # default file output is in user's home directory. java.util.logging.FileHandler.pattern = %h/java%u.log java.util.logging.FileHandler.limit = 50000 java.util.logging.FileHandler.count = 1 java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter # Limit the message that are printed on the console to INFO and above. java.util.logging.ConsoleHandler.level = INFO java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter ############################################################ # Facility specific properties. # Provides extra control for each logger. ############################################################ # For example, set the com.xyz.foo logger to only log SEVERE # messages: com.xyz.foo.level = SEVERE Since I primarily use this method to track focus issues, here is how I get detailed awt focus related logging. Just set the logger name to java.awt.focus.level=FINEST and change the default log level to FINEST. Below is a basic sample program. The sample programs are from http://www2.cs.uic.edu/~sloan/CLASSES/java/ and have been modified to illustrate the logging API. By changing the .level property in the logging.properties file, one can control the output written to the logs. To play around with the example, try changing the levels in the logging.properties file and notice the difference in messages going to the log file. Example --------KeyboardReader.java------------------------------------------------------------------------------------- import java.io.*; import java.util.*; import java.util.logging.*; public class KeyboardReader { private static final Logger mylog = Logger.getLogger("samples.input"); public static void main (String[] args) throws java.io.IOException { String s1; String s2; double num1, num2, product; // set up the buffered reader to read from the keyboard BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); System.out.println ("Enter a line of input"); s1 = br.readLine(); if (mylog.isLoggable(Level.SEVERE)) { mylog.log (Level.SEVERE,"The line entered is " + s1); } if (mylog.isLoggable(Level.INFO)) { mylog.log (Level.INFO,"The line has " + s1.length() + " characters"); } if (mylog.isLoggable(Level.FINE)) { mylog.log (Level.FINE,"Breaking the line into tokens we get:"); } int numTokens = 0; StringTokenizer st = new StringTokenizer (s1); while (st.hasMoreTokens()) { s2 = st.nextToken(); numTokens++; if (mylog.isLoggable(Level.FINEST)) { mylog.log (Level.FINEST, " Token " + numTokens + " is: " + s2); } } } } ----------MyFileReader.java---------------------------------------------------------------------------------------- import java.io.*; import java.util.*; import java.util.logging.*; public class MyFileReader extends KeyboardReader { private static final Logger mylog = Logger.getLogger("samples.input.file"); public static void main (String[] args) throws java.io.IOException { String s1; String s2; // set up the buffered reader to read from the keyboard BufferedReader br = new BufferedReader (new FileReader ("MyFileReader.txt")); s1 = br.readLine(); if (mylog.isLoggable(Level.SEVERE)) { mylog.log (Level.SEVERE,"ATTN The line is " + s1); } if (mylog.isLoggable(Level.INFO)) { mylog.log (Level.INFO, "The line has " + s1.length() + " characters"); } if (mylog.isLoggable(Level.FINE)) { mylog.log (Level.FINE,"Breaking the line into tokens we get:"); } int numTokens = 0; StringTokenizer st = new StringTokenizer (s1); while (st.hasMoreTokens()) { s2 = st.nextToken(); numTokens++; if (mylog.isLoggable(Level.FINEST)) { mylog.log (Level.FINEST,"Breaking the line into tokens we get:"); mylog.log (Level.FINEST," Token " + numTokens + " is: " + s2); } } //end of while } // end of main } // end of class ----------MyFileReader.txt------------------------------------------------------------------------------------------ My first logging example -------logging.properties------------------------------------------------------------------------------------------- handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler .level= FINEST java.util.logging.FileHandler.pattern = java%u.log java.util.logging.FileHandler.limit = 50000 java.util.logging.FileHandler.count = 1 java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter java.util.logging.ConsoleHandler.level = FINEST java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter java.awt.focus.level=ALL ------Output log------------------------------------------------------------------------------------------- May 21, 2012 11:44:55 AM MyFileReader main SEVERE: ATTN The line is My first logging example May 21, 2012 11:44:55 AM MyFileReader main INFO: The line has 24 characters May 21, 2012 11:44:55 AM MyFileReader main FINE: Breaking the line into tokens we get: May 21, 2012 11:44:55 AM MyFileReader main FINEST: Breaking the line into tokens we get: May 21, 2012 11:44:55 AM MyFileReader main FINEST: Token 1 is: My May 21, 2012 11:44:55 AM MyFileReader main FINEST: Breaking the line into tokens we get: May 21, 2012 11:44:55 AM MyFileReader main FINEST: Token 2 is: first May 21, 2012 11:44:55 AM MyFileReader main FINEST: Breaking the line into tokens we get: May 21, 2012 11:44:55 AM MyFileReader main FINEST: Token 3 is: logging May 21, 2012 11:44:55 AM MyFileReader main FINEST: Breaking the line into tokens we get: May 21, 2012 11:44:55 AM MyFileReader main FINEST: Token 4 is: example Invocation command: "C:\Program Files (x86)\Java\jdk1.6.0_29\bin\java.exe" -Djava.util.logging.config.file=logging.properties MyFileReader References Further technical details are available here: http://docs.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html#1.0 http://docs.oracle.com/javase/1.4.2/docs/api/java/util/logging/package-summary.html http://www2.cs.uic.edu/~sloan/CLASSES/java/

    Read the article

  • Transactional Messaging in the Windows Azure Service Bus

    - by Alan Smith
    Introduction I’m currently working on broadening the content in the Windows Azure Service Bus Developer Guide. One of the features I have been looking at over the past week is the support for transactional messaging. When using the direct programming model and the WCF interface some, but not all, messaging operations can participate in transactions. This allows developers to improve the reliability of messaging systems. There are some limitations in the transactional model, transactions can only include one top level messaging entity (such as a queue or topic, subscriptions are no top level entities), and transactions cannot include other systems, such as databases. As the transaction model is currently not well documented I have had to figure out how things work through experimentation, with some help from the development team to confirm any questions I had. Hopefully I’ve got the content mostly correct, I will update the content in the e-book if I find any errors or improvements that can be made (any feedback would be very welcome). I’ve not had a chance to look into the code for transactions and asynchronous operations, maybe that would make a nice challenge lab for my Windows Azure Service Bus course. Transactional Messaging Messaging entities in the Windows Azure Service Bus provide support for participation in transactions. This allows developers to perform several messaging operations within a transactional scope, and ensure that all the actions are committed or, if there is a failure, none of the actions are committed. There are a number of scenarios where the use of transactions can increase the reliability of messaging systems. Using TransactionScope In .NET the TransactionScope class can be used to perform a series of actions in a transaction. The using declaration is typically used de define the scope of the transaction. Any transactional operations that are contained within the scope can be committed by calling the Complete method. If the Complete method is not called, any transactional methods in the scope will not commit.   // Create a transactional scope. using (TransactionScope scope = new TransactionScope()) {     // Do something.       // Do something else.       // Commit the transaction.     scope.Complete(); }     In order for methods to participate in the transaction, they must provide support for transactional operations. Database and message queue operations typically provide support for transactions. Transactions in Brokered Messaging Transaction support in Service Bus Brokered Messaging allows message operations to be performed within a transactional scope; however there are some limitations around what operations can be performed within the transaction. In the current release, only one top level messaging entity, such as a queue or topic can participate in a transaction, and the transaction cannot include any other transaction resource managers, making transactions spanning a messaging entity and a database not possible. When sending messages, the send operations can participate in a transaction allowing multiple messages to be sent within a transactional scope. This allows for “all or nothing” delivery of a series of messages to a single queue or topic. When receiving messages, messages that are received in the peek-lock receive mode can be completed, deadlettered or deferred within a transactional scope. In the current release the Abandon method will not participate in a transaction. The same restrictions of only one top level messaging entity applies here, so the Complete method can be called transitionally on messages received from the same queue, or messages received from one or more subscriptions in the same topic. Sending Multiple Messages in a Transaction A transactional scope can be used to send multiple messages to a queue or topic. This will ensure that all the messages will be enqueued or, if the transaction fails to commit, no messages will be enqueued.     An example of the code used to send 10 messages to a queue as a single transaction from a console application is shown below.   QueueClient queueClient = messagingFactory.CreateQueueClient(Queue1);   Console.Write("Sending");   // Create a transaction scope. using (TransactionScope scope = new TransactionScope()) {     for (int i = 0; i < 10; i++)     {         // Send a message         BrokeredMessage msg = new BrokeredMessage("Message: " + i);         queueClient.Send(msg);         Console.Write(".");     }     Console.WriteLine("Done!");     Console.WriteLine();       // Should we commit the transaction?     Console.WriteLine("Commit send 10 messages? (yes or no)");     string reply = Console.ReadLine();     if (reply.ToLower().Equals("yes"))     {         // Commit the transaction.         scope.Complete();     } } Console.WriteLine(); messagingFactory.Close();     The transaction scope is used to wrap the sending of 10 messages. Once the messages have been sent the user has the option to either commit the transaction or abandon the transaction. If the user enters “yes”, the Complete method is called on the scope, which will commit the transaction and result in the messages being enqueued. If the user enters anything other than “yes”, the transaction will not commit, and the messages will not be enqueued. Receiving Multiple Messages in a Transaction The receiving of multiple messages is another scenario where the use of transactions can improve reliability. When receiving a group of messages that are related together, maybe in the same message session, it is possible to receive the messages in the peek-lock receive mode, and then complete, defer, or deadletter the messages in one transaction. (In the current version of Service Bus, abandon is not transactional.)   The following code shows how this can be achieved. using (TransactionScope scope = new TransactionScope()) {       while (true)     {         // Receive a message.         BrokeredMessage msg = q1Client.Receive(TimeSpan.FromSeconds(1));         if (msg != null)         {             // Wrote message body and complete message.             string text = msg.GetBody<string>();             Console.WriteLine("Received: " + text);             msg.Complete();         }         else         {             break;         }     }     Console.WriteLine();       // Should we commit?     Console.WriteLine("Commit receive? (yes or no)");     string reply = Console.ReadLine();     if (reply.ToLower().Equals("yes"))     {         // Commit the transaction.         scope.Complete();     }     Console.WriteLine(); }     Note that if there are a large number of messages to be received, there will be a chance that the transaction may time out before it can be committed. It is possible to specify a longer timeout when the transaction is created, but It may be better to receive and commit smaller amounts of messages within the transaction. It is also possible to complete, defer, or deadletter messages received from more than one subscription, as long as all the subscriptions are contained in the same topic. As subscriptions are not top level messaging entities this scenarios will work. The following code shows how this can be achieved. try {     using (TransactionScope scope = new TransactionScope())     {         // Receive one message from each subscription.         BrokeredMessage msg1 = subscriptionClient1.Receive();         BrokeredMessage msg2 = subscriptionClient2.Receive();           // Complete the message receives.         msg1.Complete();         msg2.Complete();           Console.WriteLine("Msg1: " + msg1.GetBody<string>());         Console.WriteLine("Msg2: " + msg2.GetBody<string>());           // Commit the transaction.         scope.Complete();     } } catch (Exception ex) {     Console.WriteLine(ex.Message); }     Unsupported Scenarios The restriction of only one top level messaging entity being able to participate in a transaction makes some useful scenarios unsupported. As the Windows Azure Service Bus is under continuous development and new releases are expected to be frequent it is possible that this restriction may not be present in future releases. The first is the scenario where messages are to be routed to two different systems. The following code attempts to do this.   try {     // Create a transaction scope.     using (TransactionScope scope = new TransactionScope())     {         BrokeredMessage msg1 = new BrokeredMessage("Message1");         BrokeredMessage msg2 = new BrokeredMessage("Message2");           // Send a message to Queue1         Console.WriteLine("Sending Message1");         queue1Client.Send(msg1);           // Send a message to Queue2         Console.WriteLine("Sending Message2");         queue2Client.Send(msg2);           // Commit the transaction.         Console.WriteLine("Committing transaction...");         scope.Complete();     } } catch (Exception ex) {     Console.WriteLine(ex.Message); }     The results of running the code are shown below. When attempting to send a message to the second queue the following exception is thrown: No active Transaction was found for ID '35ad2495-ee8a-4956-bbad-eb4fedf4a96e:1'. The Transaction may have timed out or attempted to span multiple top-level entities such as Queue or Topic. The server Transaction timeout is: 00:01:00..TrackingId:947b8c4b-7754-4044-b91b-4a959c3f9192_3_3,TimeStamp:3/29/2012 7:47:32 AM.   Another scenario where transactional support could be useful is when forwarding messages from one queue to another queue. This would also involve more than one top level messaging entity, and is therefore not supported.   Another scenario that developers may wish to implement is performing transactions across messaging entities and other transactional systems, such as an on-premise database. In the current release this is not supported.   Workarounds for Unsupported Scenarios There are some techniques that developers can use to work around the one top level entity limitation of transactions. When sending two messages to two systems, topics and subscriptions can be used. If the same message is to be sent to two destinations then the subscriptions would have the default subscriptions, and the client would only send one message. If two different messages are to be sent, then filters on the subscriptions can route the messages to the appropriate destination. The client can then send the two messages to the topic in the same transaction.   In scenarios where a message needs to be received and then forwarded to another system within the same transaction topics and subscriptions can also be used. A message can be received from a subscription, and then sent to a topic within the same transaction. As a topic is a top level messaging entity, and a subscription is not, this scenario will work.

    Read the article

  • My Optimized Adam &amp; Eve

    - by MarkPearl
    Today I had a few minutes in the evening to go over my original Adam and Eve code… what I wanted to see tonight was if I could optimize the code any further… which I was pretty sure could be done. Ultimately what I wanted to find from the experiment was a balance between optimized code an reusable code. On the one hand I can put everything into a single function and end up with a totally unusable function that is extremely compressed, which would have big comebacks when making modifications at a later stage. Alternatively I could have many single line functions that are extremely loosely coupled but sparsely spaced and so would almost be to fragmented to grok. Ultimately I found with my current iteration something that I consider readable, yet compressed. Code below… // Learn more about F# at http://fsharp.net open System let people = [ ("Adam", None); ("Eve", None); ("Cain", Some("Adam", "Eve")); ("Abel", Some("Adam", "Eve")) ] // // Prints the details // let showDetails(person : string * (string * string) option) = let ParentsName = let parents = snd(person) match parents with | Some(dad, mum) -> "Father " + dad + " and Mother " + mum | None -> "Has no parents!" let result = fst(person) + Environment.NewLine + ParentsName result // // Searches an array of people and looks for a match of names // let findPerson(name : string, people : (string * (string * string) option) list) = // Try and find a match of the name let o = Seq.tryFind(fun person -> match name with | firstName when firstName = fst(person) -> true | _ -> false) people // Show the details based on the match result match o with | Option.Some(x) -> showDetails(Option.get(o)) | _ -> "Not Found" Console.WriteLine(findPerson("Cains", people)) Console.ReadLine()

    Read the article

  • Conditional Operator Example

    - by mbcrump
    If you haven’t taken the time to learn conditional operators, then now is the time. I’ve added a quick and dirty example for those on the forums.   Code Snippet using System; using System.Net.Mail; using System.Net; using System.Globalization; using System.Windows.Forms;   class Demo {     //Please use conditional statements in your code. See example below.       public static void Main()     {         int dollars = 10;           //Bad Coder Bad !!! Don't do this         if (dollars == 1)         {             Console.WriteLine("Please deposit {0} dollar.", dollars);         }         else         {             Console.WriteLine("Please deposit {0} dollars.", dollars);         }             //Good Coder Good !!! Do this         Console.WriteLine("Please deposit {0} dollar{1}.", dollars, dollars == 1 ? ' ' : 's');         //                                                          expression   ? true : false           Console.ReadLine();          } }

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >