Search Results

Search found 72 results on 3 pages for 'inbetween'.

Page 3/3 | < Previous Page | 1 2 3 

  • MVVM - ListBox SelectedItem Binding Property Going Null

    - by Peanut
    So i have a listbox: <ListBox x:Name="listbox" HorizontalAlignment="Left" Margin="8,8,0,8" Width="272" BorderBrush="{x:Null}" Background="{x:Null}" Foreground="{x:Null}" ItemsSource="{Binding MenuItems}" ItemTemplate="{DynamicResource MenuItemsTemplate}" SelectionChanged="ListBox_SelectionChanged" SelectedItem="{Binding SelectedItem}"> </ListBox> and i have this included in my viewmodel: public ObservableCollection<MenuItem> MenuItems { get { return menuitems; } set { menuitems = value; NotifyPropertyChanged("MenuItems"); } } public MenuItem SelectedItem { get { return selecteditem; } set { selecteditem = value; NotifyPropertyChanged("SelectedItem"); } } and also in my viewmodel: public void UpdateStyle() { ActiveHighlight = SelectedItem.HighlightColor; ActiveShadow = SelectedItem.ShadowColor; } So, the objective is to call UpdateStyle() whenever selectedchanged event is fired. So in the .CS file, i call UpdateStyle(). The problem is, whenever I get into the selectionchanged event method, my ViewModel.SelectedItem is always null. I tried debugging this to see if the binding was working correctly, and it is. When I click on an item in the listbox, the SelectedItem Set is triggered, setting the value... but somewhere inbetween that and the selected changed (In the CS File) It gets reset to Null. Can anyone help out? Thanks

    Read the article

  • Weird behaviour of C++ destructors

    - by Vilx-
    #include <iostream> #include <vector> using namespace std; int main() { vector< vector<int> > dp(50000, vector<int>(4, -1)); cout << dp.size(); } This tiny program takes a split second to execute when simply run from the command line. But when run in a debugger, it takes over 8 seconds. Pausing the debugger reveals that it is in the middle of destroying all those vectors. WTF? Note - Visual Studio 2008 SP1, Core 2 Duo 6700 CPU with 2GB of RAM. Added: To clarify, no, I'm not confusing Debug and Release builds. These results are on one and the same .exe, without even any recompiling inbetween. In fact, switching between Debug and Release builds changes nothing.

    Read the article

  • How can I remove HTML span tags with a Perl one liner?

    - by yaya3
    I want to perform the following vim substitution as a one-liner in the terminal with Perl. I would prefer to allow for any occurences of whitespace or newlines, rather than explicitly catering for them as I am below. %s/blockDontForget">\n*\s*<p><span><a\(.*\)<\/span>/blockDontForget"><p><a\1/g I've tried this: perl -pi -e 's/blockDontForget"><p><span><a(.*)<\/span>/blockDontForget"><p><a$1/msg' I presume I am misinterpreting the flags. Where am I going wrong? Thanks. EDIT: The above example is to strip the spans out of the following html: <div class="block blockDontForget"> <p><span><a href="../../../foo/bar/x/x.html">Lorem Ipsum</a></span></p> EDIT: It's just the <span>'s and </span>'s that are inbetween <p> and <a> from the "blockDontForget" class </div> that I want to remove (there are lots or these blockDontForget divs with spans inside anchors that I want to keep).

    Read the article

  • Grabbing rows from MySql where current date is in between start date and end date (Check if current date lies between start date and end date)

    - by Jordan Parker
    I'm trying to select from the database to get the "campaigns" that dates fall into the month. So far i've been successful in grabbing rows that starts or ends inside the current month. What I need to do now is select rows that start in one month and ends a few months down the line ( EG: It's the 3rd month in the year, and there's a "campaign" that runs from the 1st month until the 5th. other example There is a "campaign" that runs from 2012 until 2013 ) I'm hoping there is some way to select via MySql all rows in which a capaign may run. If not should I grab all data in the database and only show the ones that run via the current month. I have already made a function that displays all the days inbetween each date inside an array, which is called "dateRange". I've also created another which shows how many days the campaign runs for called "runTime". Select all (Obviously) $result = mysql_query("SELECT * FROM campaign"); Select Starting This Month $result = mysql_query("SELECT * FROM campaign WHERE YEAR( START ) = YEAR( CURDATE( ) ) AND MONTH( START ) = MONTH( CURDATE( ) )"); Select Ending This Month $result = mysql_query("SELECT * FROM campaign WHERE YEAR( END ) = YEAR( CURDATE( ) ) AND MONTH( END ) = MONTH( CURDATE( ) ) LIMIT 0 , 30"); Code sample while($row = mysql_fetch_array($result)) { $dateArray = dateRange($row['start'], $row['end']); echo "<h3>" . $row['campname'] . "</h3> Start " . $row['start'] . "<br /> End " . $row['end']; echo runTime($row['start'], $row['end']); print_r($dateArray); } In regards to the dates, MySql database only holds start date and end date of the campaign.

    Read the article

  • How to migrate primary key generation from "increment" to "hi-lo"?

    - by Bevan
    I'm working with a moderate sized SQL Server 2008 database (around 120 tables, backups are around 4GB compressed) where all the table primary keys are declared as simple int columns. At present, primary key values are generated by NHibernate with the increment identity generator, which has worked well thus far, but precludes moving to a multiprocessing environment. Load on the system is growing, so I'm evaluating the work required to allow the use of multiple servers accessing a common database backend. Transitioning to the hi-lo generator seems to be the best way forward, but I can't find a lot of detail about how such a migration would work. Will NHibernate automatically create rows in the hi-lo table for me, or do I need to script these manually? If NHibernate does insert rows automatically, does it properly take account of existing key values? If NHibernate does take care of thing automatically, that's great. If not, are there any tools to help? Update NHibernate's increment identifier generator works entirely in-memory. It's seeded by selecting the maximum value of used identifiers from the table, but from that point on allocates new values by a simple increment, without reference back to the underlying database table. If any other process adds rows to the table, you end up with primary key collisions. You can run multiple threads within the one process just fine, but you can't run multiple processes. For comparison, the NHibernate identity generator works by configuring the database tables with identity columns, putting control over primary key generation in the hands of the database. This works well, but compromises the unit of work pattern. The hi-lo algorithm sits inbetween these - generation of primary keys is coordinated through the database, allowing for multiprocessing, but actual allocation can occur entirely in memory, avoiding problems with the unit of work pattern.

    Read the article

  • Getting zeros between data while reading a binary file in C

    - by indiajoe
    I have a binary data which I am reading into an array of long integers using a C programme. hexdump of the binary data shows, that after first few data points , it starts again at a location 20000 hexa adresses away. hexdump output is as shown below. 0000000 0000 0000 0000 0000 0000 0000 0000 0000 * 0020000 0000 0000 0053 0000 0064 0000 006b 0000 0020010 0066 0000 0068 0000 0066 0000 005d 0000 0020020 0087 0000 0059 0000 0062 0000 0066 0000 ........ and so on... But when I read it into an array 'data' of long integers. by the typical fread command fread(data,sizeof(*data),filelength/sizeof(*data),fd); It is filling up with all zeros in my data array till it reaches the 20000 location. After that it reads in data correctly. Why is it reading regions where my file is not there? Or how will I make it read only my file, not anything inbetween which are not in file? I know it looks like a trivial problem, but I cannot figure it out even after googling one night.. Can anyone suggest me where I am doing it wrong? Other Info : I am working on a gnu/linux machine. (slax-atma distro to be specific) My C compiler is gcc.

    Read the article

  • How to make HTML layout whitespace-agnostic?

    - by ssg
    If you have consecutive inline-blocks white-space becomes significant. It adds some level of space between elements. What's the "correct" way of avoiding whitespace effect to HTML layout if you want those blocks to look stuck to each other? Example: <span>a</span> <span>b</span> This renders differently than: <span>a</span><span>b</span> because of the space inbetween. I want whitespace-effect to go away without compromising HTML source code layout. I want my HTML templates to stay clean and well-indented. I think these options are ugly: 1) Tweaking text-indent, margin, padding etc. (Because it would be dependent on font-size, default white-space width etc) 2) Putting everything on a single line, next to each other. 3) Zero font-size. That would require overriding font-size in blocks, which would otherwise be inherited. 4) Possible document-wide solutions. I want the solution to stay local for a certain block of HTML. Any ideas, any obvious points which I'm missing?

    Read the article

  • How do i select all text nodes using XSL?

    - by user323719
    I want to get the generate-id(.) of all the text nodes after node and before node . I am looking for some generic XSL and not tightly coupled to the sample input pattern mentioned below. For any input pattern i want to get the ids of all the text nodes between node and . Sample input for better understanding: <a> <b> <c> This is first text node </c> </b> <d> <e> This is my second text node </e> <f> This is my <m/>third text node </f> <g> One more text node </g> <h> <i> This is my fourth text node </i> </h> <j> This is my fifth <n/>text node </j> <k> <l> This is my sixth text node </l> </k> </d> </a> Expected output: Generate id of the text nodes with values "third text node ", "One more text node", "This is my fourth text node", "This is my fifth" which lie inbetween nodes <m/> and <n/> Please give your ideas.

    Read the article

  • Loading user control dynamically looses data

    - by user228777
    I have a created a user control. This user control I dynamically load on a page inside Telerik Panelbar control. I have done all necessary coding to save the viewstate and load this dynamically created usercontrol every time page loads. On this User control I have a asp panel. By default this panel is invisible. When user clicks a button on this user control panel is made visible. On page load of this user control I populate all the controls on this panel. Everything works fine if I don’t load this use control dynamically but when I load this user control dynamically and if I make panel visible by default then only all fields on the panel are populated. But if I make by default invisible and on button click make panel visible none of the text boxes or comboboxes are populated. I populate comboboxes on page load of the userControl but inbetween postbacks all the comboboxes on the user control loose data. ON the parent page I am saving the viewstate This is my code on parent page to dynamically load userControl ( which has panel on it) Dim ucPiggyBank As SubscriberSetupPages_UserControls_PiggyBank = CType(LoadControl("~/SubscriberSetupPages/UserControls/PiggyBank.ascx"), SubscriberSetupPages_UserControls_PiggyBank) With ucPiggyBank .PiggyBankID = account.Id .ID = account.Id.ToString 'Setting up following 3 properties here to avoid database trips .PiggyBankEligibleAccounts = piggyBankEligibleAccountCollection .MemorizedNames = memorizednames .Period = period End With radPanelNewChild.Controls.Add(ucPiggyBank) radPanelNew.Items.Add(radPanelNewChild) radPanelNew.Expanded = True ‘this is the Panel item on parent page of Telerik Panelbar control. Dim radPanelPiggyBank As RadPanelItem = DirectCast(pnlbarPiggyBank.FindItemByValue("TestItem"), RadPanelItem) With radPanelPiggyBank .Items.Add(radPanelNew) .DataBind() End With ‘I am doing everything for saving viewstate on parent control This is the code on page load of userControl If Not IsPostBack Then If m_PiggyBankID <> Guid.Empty Then 'Load data Call GetPiggyBankDetails() End If I have a edit button on the user control which makes panel visible. It makes panel visible but with no data. Can you please tell me what’s happening? Thanks in advance.

    Read the article

  • Zend, slow load, "waiting for response" for 20-80 seconds on local site

    - by Tony C.
    So I have several sites running under the same zend setup. All of the sites run pretty normally except one. Upon loading or reloading this one site, reguardless of which page your on (excluding the 404 page explanation later...) you get a serious pause before any content begins to download. Using firebugs net panel you can see that the first request which is www.(siteaddress).com.local you see a "waiting for response" bar (purple) that is going for anywhere from 20 to sometimes 80+ seconds and this isn't on a dev site, this is on a local site under localhost. What I've managed to figure out so far is that all the pages do this except my 404 page. The reason the 404 page doesn't succumb to this is because it uses a seperate controller (the error controller) and therefore bypasses much of the controller and functions the other parts of the site use. Using exit statements I've manged to figure out that the problem happens somewhere between my post dispatch and my main (top most) controllers Init function. If i exit in the main controllers init the page loads (then exits instantly, no wait). If i do the same in the pre or post dispatch the page waits the 20-80 seconds then exits. Is there a diagram or explanation somewhere or a way for me to find out what events fire inbetween the post dispatch and the main controllers init function? Or does anyone have any clue what might cause this? Any help would be greatly appreciated...

    Read the article

  • jQuery slideToggle jump on close

    - by spankmaster79
    Hi, I'm trying to slideToggle a in a table with jQuery and it works in FF, OP, CHrome. Only IE (6,7,8) is giving me problems. It slides down perfectly down and up, but after the slide up animation is finished. The hidden pops up in full height and then closes. So I guess it must be somwhere inbetween when it switches from a minimal height to "display:none" that it appears for a short second. The code is built dynamically but I'll try to give an example: <table> <tr> <td> <script type="text/javascript"> function toggleTr_{$dynamicID}() { $('#content_{$dynamicID}').slideToggle('slow'); /* DO SOME OTHER STOFF LIKE COLOR CHANGES CSS CLASS CHANGES */ } </script> </td> </tr> <tr id="list_{$dynamicID}" onclick="toggleTr_{$dynamicID}();" style="cursor:pointer;"> <td> <!-- INFO HEADER --> </td> </tr> <tr> <td> <div id="content_{$dynamicID}" style="display:none;"> <!-- INFO BODY HIDDEN --> </div </td> </tr> Other problems here with slideToggle only descibed problems with padding, margin, or problems with the animation, but that all works. Help is appreciated. Thx, Spanky

    Read the article

  • How can I run an appear effect and a fade effect in scriptaculous? I need them to run in tandam so t

    - by LeeRM
    Hi, Ive been fiddling with this for hours and hours and just cant get it right. First off my sites are already using Prototytpe and Scriptaculous, and to change would take a long time. Basically I am after achieving a slideshow effect similar to jQuery Cycle plugin. I have written most of it but cant get over this hurdle: I need the user to be able to press a control button which will skip the slide to which ever one they have picked. My problem is that if a fade / appear effect is running, then it causes an overlap. I am using queues and they are in their own scope. The problem as I see it is that the fade effect on one slide and the appear effect on the next slide are separate functions. Which means that if the user clicks the control button to move to another slide whilst the animation is inbetween fade & appear, then the next cycle will slot itself in the queue between those 2 effects. The default is to append to the end of the existing queue, which should be fine. But if the appear hasnt been added when a new fade is instantiated, then the queue messes up. I can make it so nothing happens if animation is in effect but thats not the effect I am after. I want to be able to click a slide and whatever is happening to effectively stop and the next slide appear. This is an example of what I am after: http://www.zendesk.com/ Im sorry if that doesnt make sense. Its a tough one to explain. Thanks Lee

    Read the article

  • How expensive is a context switch? Is it better to implement a manual task switch than to rely on OS

    - by Vilx-
    The title says it all. Imagine I have two (three, four, whatever) tasks that have to run in parallel. Now, the easy way to do this would be to create separate threads and forget about it. But on a plain old single-core CPU that would mean a lot of context switching - and we all know that context switching is big, bad, slow, and generally simply Evil. It should be avoided, right? On that note, if I'm writing the software from ground up anyway, I could go the extra mile and implement my own task-switching. Split each task in parts, save the state inbetween, and then switch among them within a single thread. Or, if I detect that there are multiple CPU cores, I could just give each task to a separate thread and all would be well. The second solution does have the advantage of adapting to the number of available CPU cores, but will the manual task-switch really be faster than the one in the OS core? Especially if I'm trying to make the whole thing generic with a TaskManager and an ITask, etc?

    Read the article

  • PL-SQL - Two statements with begin and end, run fine seperately but not together?

    - by Twiss
    Hi all, Just wondering if anyone can help with this, I have two PLSQL statements for altering tables (adding extra fields) and they are as follows: -- Make GC_NAB field for Next Action By Dropdown begin if 'VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')>0 then execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10, ))'; elsif ('VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')=0) or 'VARCHAR2' = 'VARCHAR2' then execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10))'; else execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2)'; end if; commit; end; -- Make GC_NABID field for Next Action By Dropdown begin if 'NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')>0 then execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER(, ))'; elsif ('NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')=0) or 'NUMBER' = 'VARCHAR2' then execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER())'; else execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER)'; end if; commit; end; When I run these two queries seperately, no problems. However, when run together as shown above, Oracle gives me an error when it starts the second statement: Error report: ORA-06550: line 15, column 1: PLS-00103: Encountered the symbol "BEGIN" 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action: I'm assuming that this means the first statement is not terminated properly... is there anything I should put inbetween the statements to make it work properly? Thanks in advance everyone!

    Read the article

  • Dependencyproperty doesn't have value on load

    - by Jakob
    My problem is this, I have a UC called profile that contains another UC called FollowImageControl. In my Profile.xaml i declaretively bind a property of FollowImageControl called FollowerId to a CurrentUserId from Profile.xaml.cs. Problem is that I CurrentUserId is assigned in Profile.xaml.cs; the Profile.xaml code-behind. This means that I do not initially get the FollowerId. I have these methods in the FollowImageControl.xaml.cs: public static readonly DependencyProperty _followUserId = DependencyProperty.Register("FollowUserId", typeof(Guid), typeof(FollowImageControl), null); public Guid FollowUserId { get { return (Guid)GetValue(_followUserId); } set { SetValue(_followUserId, value); } } public FollowImageControl() { // Required to initialize variables InitializeComponent(); LoggedInUserId = WebContext.Current.User.UserId; var ctx = new NotesDomainContext(); if (ctx.IsFollowingUser(LoggedInUserId, FollowUserId).Value) SwitchToDelete.Begin(); } private void AddImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (LoggedInUserId != FollowUserId) { var ctx = new NotesDomainContext(); ctx.FollowUser(FollowUserId, LoggedInUserId); ctx.SubmitChanges(); } } THE WEIRD THING IS that when i insert breakpoints the FollowerUserId in FollowImageControl() is 0, but it has a value in AddImg_MouseLeftButtonDown, and there is no inbetween logic that sets the value of it. How is this??? Here's a little more code info: This is my binding from profile.xaml <internalCtrl:FollowImageControl FollowUserId="{Binding ElementName=ProfileCtrl, Path=CurrentUserId}" /> this is my constructor in profile.xaml.cs wherein the CurrentUserId is set public static readonly DependencyProperty _CurrentUserId = DependencyProperty.Register("CurrentUserId", typeof(Guid), typeof(Profile), null); public Guid CurrentUserId { get { return (Guid)GetValue(_CurrentUserId); } set { SetValue(_CurrentUserId, value); } } public Profile(Guid UserId) { CurrentUserId = UserId; InitializeComponent(); Loaded += new RoutedEventHandler(Profile_Loaded); } I'm seriously dumbfound that one minute the FollowerId has no value, and the next it holds the right, without me having changed the value in the code-behind.

    Read the article

  • adress-chunk: separate data stored in one collumn - into three (street, postal-code, town)

    - by zero
    hello dear community. Hello dear friends form all over the planet first of all - this is a great great forum. I like this place to share the ideas. It is so great to see such a supportive place - featuring the knowledge exchange! today i have the following thing to discuss: i want to separate the following data that are stored in one column of a calc-spreadsheet: See the following data: You see that there are the following categories:_ steet, postal-code, town All the data are stored in only one Colum; Well to be honest: i want to separate them into three colums steet, postal-code, town see the data: what can i do? note - you see that there are commas inbetween the enties: and besides this we see that we have a postal-code with four digits: that is a good thing. Perhaps we can use this as a marker that helps us to separate the data?! Perhaps See a data-sample! Here you can see some exceptions: eg. the town that has two words combinde with a "-" ... or somethims without any signs and characters... see the following... as an example: Max-Bader-Platz 1, 5620 Schwarzach im Pongau Pestalozzistraße 4, 9990 Nussdorf-Debant Schulstraße 4, 5162 Obertrum am See But i guess that this means no problem... What do you think about this? I am very very interested to get your opinion! i look forward to hear from you! regards see a snipped of the dataset - that is stored in one column -[b]Goal: [/b]i want to separate the datas into three collumns... : Schulweg 6, 9871 Seeboden Khevenhüllerstraße 45, 4861 Schörfling Franz Xaver Rennstr.18, 6460 Imst Schulstraße 4, 5162 Obertrum am See Schulweg 6, 7432 Oberschützen Pestalozzistraße 4, 9990 Nussdorf-Debant Niederndorf bei Kufstein 53c, 6342 Niederndorf bei Kufstein Hauptschulstraße 18, 2183 Neusiedl an der Zaya Seeweg 14, 5202 Neumarkt am Wallersee Europaplatz 1, 8820 Neumarkt in Steiermark Schulstraße 7, 4212 Neumarkt im Mühlkreis Schulstraße 20, 4720 Neumarkt im Hausruckkreis Bahnhofstr. 10, 4872 Neukirchen an der Vöckla Schulstraße 5b, 4780 Schärding Reitbergstraße 2, 4311 Schwertberg Europaplatz 1, 2320 Schwechat Am Schulberg 5, 3931 Schweiggers Waidach 8, 6130 Schwaz Waidach 8, 6130 Schwaz Max-Bader-Platz 1, 5620 Schwarzach im Pongau Markt 29, 2662 Schwarzau im Gebirge Hofsteigstraße 68, 6858 Schwarzach Gmundner Straße 7, 4690 Schwanenstadt Mühlfeldstraße 1, 4690 Schwanenstadt Mainsdorferstraße 18, 8541 Schwanberg Jakob Stemer-Weg 3, 6780 Schruns Obere Umfahrungsstraße 16, 2432 Schwadorf bei Wien Battloggstraße 54, 6780 Schruns Schloss-Straße 19, 5020 Salzburg Schillerplatz 2, 8280 Fürstenfeld Erzherzog-Johann-Str. 400, 8970 Schladming Schulgasse 261, 8811 Scheifling i look forward to hear from you!! regards

    Read the article

  • Using Artificial Intelligence (AI) to predict Stock Prices

    - by akaphenom
    Given a set of datavery similar to the Motley Fool CAPS system, where individual users enter BUY and SELL recommendations on various equities. What I would like to do is show each recommendation and I guess some how rate (1-5) as to whether it was good predictor<5 (ie corellation coeffient = 1) of the future stock price (or eps or whatever) or a horrible predictor (ie corellation coeffient = -1) or somewhere inbetween. Each recommendation is tagged to a particular user, so that can be tracked over time. I can also track market direction (bullish / bearish) based off of something like sp500 price. The components I think that would make sense in the model would be: user direction (long/short) market direction sector of stock The thought is that some users are better in bull markets than bear (and vice versa), and some are better at shorts than longs- and then a cobination the above. I can automatically tag the market direction and sector (based off the market at the time and the equity being recommended). The thought is that I could present a series of screens and allow me to rank each individual recommendation by displaying available data absolute, market and sector out performance for a specfic time period out. I would follow a detailed list for ranking the stocks so that the ranking is as objective as possible. My assumtion is that a single user is right no more than 57% of the time - but who knows. I could load the system and say "Lets rank the recommendation as a predictor of stock value 90 days forward"; and that would represent a very explicit set of rankings. NOW here is the crux - I want to create some sort of machine learning algorithm that can identify patterns over a series of time so that as recommendations stream into the application we maintain a ranking of that stock (ie. similar to correlation coeeficient) as to the likelihood of that recommendation (in addition to the past series of recommendations ) will affect the price. Now here is the super crux. I have never taken an AI class / read an AI book / never mind specific to machine learning. So I cam looking for guidance - sample or description of a similar system I could adapt. Place to look for info or any general help. Or even push me in the right direction to get started... My hope is to implment this with F# and be able to impress my friends with a new skillset in F# with an implementation of machine learnign and potentially something (application / source) I can include in a tech portfolio or blog space; Thank you for any advice in advance.

    Read the article

  • C++ How to deep copy a struct with unknown datatype?

    - by Ewald Peters
    hi, i have a "data provider" which stores its output in a struct of a certain type, for instance struct DATA_TYPE1{ std::string data_string; }; then this struct has to be casted into a general datatype, i thought about void * or char *, because the "intermediate" object that copies and stores it in its binary tree should be able to store many different types of such struct data. struct BINARY_TREE_ENTRY{ void * DATA; struct BINARY_TREE_ENTRY * next; }; this void * is then later taken by another object that casts the void * back into the (struct DATA_TYPE1 *) to get the original data. so the sender and the receiver know about the datatype DATA_TYPE1 but not the copying object inbetween. but how can the intermidiate object deep copy the contents of the different structs, when it doesn't know the datatype, only void * and it has no method to copy the real contents; dynamic_cast doesn't work for void *; the "intermediate" object should do something like: void store_data(void * CASTED_DATA_STRUCT){ void * DATA_COPY = create_a_deepcopy_of(CASTED_DATA_STRUCT); push_into_bintree(DATA_COPY); } a simple solution would be that the sending object doesn't delete the sent data struct, til the receiving object got it, but the sending objects are dynamically created and deleted, before the receiver got the data from the intermediate object, for asynchronous communication, therefore i want to copy it. instead of converting it to void * i also tried converting to a superclass pointer of which the intermediate copying object knows about, and which is inherited by all the different datatypes of the structs: struct DATA_BASE_OBJECT{ public: DATA_BASE_OBJECT(){} DATA_BASE_OBJECT(DATA_BASE_OBJECT * old_ptr){ std::cout << "this should be automatically overridden!" << std::endl; } virtual ~DATA_BASE_OBJECT(){} }; struct DATA_TYPE1 : public DATA_BASE_OBJECT { public: string str; DATA_TYPE1(){} ~DATA_TYPE1(){} DATA_TYPE1(DATA_TYPE1 * old_ptr){ str = old_ptr->str; } }; and the corresponding binary tree entry would then be: struct BINARY_TREE_ENTRY{ struct DATA_BASE_OBJECT * DATA; struct BINARY_TREE_ENTRY * next; }; and to then copy the unknown datatype, i tried in the class that just gets the unknown datatype as a struct DATA_BASE_OBJECT * (before it was the void *): void * copy_data(DATA_BASE_OBJECT * data_that_i_get_in_the_sub_struct){ struct DATA_BASE_OBJECT * copy_sub = new DATA_BASE_OBJECT(data_that_i_get_in_the_sub_struct); push_into_bintree(copy_sub); } i then added a copy constructor to the DATA_BASE_OBJECT, but if the struct DATA_TYPE1 is first casted to a DATA_BASE_OBJECT and then copied, the included sub object DATA_TYPE1 is not also copied. i then thought what about finding out the size of the actual object to copy and then just memcopy it, but the bytes are not stored in one row and how do i find out the real size in memory of the struct DATA_TYPE1 which holds a std::string? Which other c++ methods are available to deepcopy an unknown datatype (and to maybe get the datatype information somehow else during runtime) thanks Ewald

    Read the article

  • log-back and thirdparty writing to stdout. How to stop them getting interleaved.

    - by David Roussel
    First some background. I have a batch-type java process run from a DOS batch script. All the java logging goes to stdout, and the batch script redirects the stdout to a file. (This is good for me because I can ECHO from the script and it gets into the log file, so I can see all the java JVM command line args, which is great for debugging.) I may not I use slf4j API, and for the backend I used to use log4j, but recently switched to logback-classic. Although all my application code uses slf4j, I have a third party library that does it's own logging (not using a standard API) which also gets written to stdout. The problem is that sometimes log lines get mixed up and don't cleanly appear on separate lines. Here is an example of some messed up output: 2010-05-28 18:00:44.783 [thread-1 ] INFO CreditCorrelationElementBuilderImpl - Bump parameters exist for scenario, now attempting bumping. [indexDisplayName=STANDARD_S1_v300] 2010-05-28 18:01:43.517 [thread-1 ] INFO CreditCorrelationElementBuilderImpl - Found adjusted point in data, now applying bump. [point=0.144040000000000] 2010-05-28 18:01:58.642 [thread-1 ] DEBUG com.company.request.Request - Generated request for [dealName=XXX_20050225_01[5],dealType=GENERIC_XXX,correlationType=2,copulaType=1] in 73.8 s, Simon Stopwatch: [sys1.batchpricer.reqgen.gen INHERIT] total 1049 s, counter 24, max 74.1 s, min 212 ms 2010-05-28 18:05/28/10 18:02:20.236 INFO: [ServiceEvent] SubmittedTask:BC-STRESS_04_FZBC-2010-05-21-545024448189310126-23 01:58.658 [req-writer-2b ] INFO .c.g.r.o.OptionalFileDocumentOutput - Writing request XML to \\filserver\dir\file1.xml - write time: 21.4 ms - Simon Stopwatch: [sys1.batchpricer.reqgen.writeinputfile INHERIT] total 905 ms, counter 24, max 109 ms, min 10.8 ms 2010-05-28 18:02:33.626 [ResponseCallbacks-1: DriverJobSpace$TakeJobRunner$1] ERROR c.c.s.s.D.CalculatorCallback - Id:23 no deal found !! 2010-0505/28/10 18:02:50.267 INFO: [ServiceEvent] CompletedTask:BC-STRESS_04_FZBC-2010-05-21-545024448189310126-23:Total:24 Now comparing back to older log files, it seems the problem didn't occur when using log4j as the logging backend. So logback must be doing something different. The problem seems to be that although PrintStream.write(byte buf[], int off, int len) is synchronized, however I can see in ch.qos.logback.core.joran.spi.ConsoleTarget that System.out.write(int b) is the only write method called. So inbetween logback outputting each byte, the thirdparty library is managing to write a whole string to the stdout. (Not only is this cause me a problem, but it must also be a little inefficient?) Is there any other fix to this interleaving problem than patching the code to ConsoleTarget so it implments the other write methods? Any nice work arounds. Or should I just file a bug report? Here is my logback.xml: <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-16thread] %-5level %-35.35logger{30} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration> I'm using logback 0.9.20 with java 1.6.0_07.

    Read the article

  • Why are my hard drives failing?

    - by WishCow
    I have a small Ubuntu server running at home, with 2 HDDs. There are two software raids (raid1) on the disks, managed by mdadm, which I believe is irrelevant, but mentioning it anyway. Both of the HDDs are Western Digital, and have been used for around 2 years, when one of them started making clicking noises, and died. I figured that maybe it's natural after 2 years, so I bought a new one, and resynced the raid arrays. After about a month, the other drive also died. I didn't get suspicious, since both drives have been bought at the same time, it's not that surprising to see both of them near each other, so I bought another one. So far, 2 old drives failed, and 2 brand new in the system. After one month, one of the new drives died. This is when it started getting suspicious. Since the PC was put together from some really old parts (think AthlonXP), I figured that maybe the motherboard's SATA controller is the culprit. Of course you can't switch parts easily in an old PC like this, so I bought a whole system, new MB, new CPU, new RAM. Took the just failed drive back, since it was under warranty, and got it replaced. So it is up to 2 failed drives from the old ones, and 1 failed drive from the new ones. No problems, for 1 month. After that errors were creeping up again in /var/log/messages, and mdadm was reporting raid array failures. I started tearing my hair out. Everything is new in the system, it's up to the third brand new HDD, it's simply not possible that all of the new drives that I bought were faulty. Let's see what is still common... the cables. Okay, long shot, let's replace the SATA cables. Take HDD back, smile to the guy at the counter and say that I'm really unlucky. He replaces the HDD. I come home, one month passes and one of HDDs fails, again. I'm not joking. Two of the brand new HDDs have failed. Maybe it's a bug in the OS. Let's see what the manufacturer's testing tool says. Download testing tool, burn it to a CD, reboot, leave HDD testing overnight. Test says that the drive is faulty, and I should back up everything, if I still can. I don't know what's happening, but it does not look like a software problem, something is definitely thrashing the HDDs. I should mention now, that the whole system is in a shoebox. Since there are a load of "build your own ikea case" stuff, I thought there shouldn't be any problems throwing the thing in a box, and stuffing it away somewhere. The box is well ventilated, but I thought that just maybe the drives were overheating. There is no other possible answer to this. So I took the HDD back, and got it replaced (for the 3rd time), and bought HDD coolers. And just now, I have heard the sound of doom. click click whizzzzzzzzz. SSH into the box: You have new mail! mail r 1 DegradedArrayEvent on /dev/md0 ... dmesg output: [47128.000051] ata3: lost interrupt (Status 0x50) [47128.000097] end_request: I/O error, dev sda, sector 58588863 [47128.000134] md: super_written gets error=-5, uptodate=0 [48043.976054] ata3: lost interrupt (Status 0x50) [48043.976086] ata3.00: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x6 frozen [48043.976132] ata3.00: cmd c8/00:18:bf:40:52/00:00:00:00:00/e1 tag 0 dma 12288 in [48043.976135] res 40/00:00:00:4f:c2/00:00:00:00:00/00 Emask 0x4 (timeout) [48043.976208] ata3.00: status: { DRDY } [48043.976241] ata3: soft resetting link [48044.148446] ata3.00: configured for UDMA/133 [48044.148457] ata3.00: device reported invalid CHS sector 0 [48044.148477] ata3: EH complete Recap: No possibility of overheating 6 drives have failed, 4 of those have been brand new. I'm not sure now that the original two have been faulty, or suffered the same thing that the new ones. There is nothing common in the system, apart from the OS which is Ubuntu Karmic now (started with Jaunty). New MB, new CPU, new RAM, new SATA cables. No, the little holes on the HDD are not covered I'm crying. Really. I don't have the face to return to the store now, it's not possible for 4 drives to fail under 4 months. A few ideas that I have been thinking: Is it possible that I fuck up something when I partition and resync the drives? Can it be so bad that it physicaly wrecks the drive? (since the vendor supplied tool says that the drive is damaged) I do the partitoning with fdisk, and use the same block size for the raid1 partitions (I check the exact block sizes with fdisk -lu) Is it possible that the linux kernel or mdadm, or something is not compatible with this exact brand of HDDs, and thrashes them? Is it possible that it may be the shoebox? Try placing it somewhere else? It's under a shelf now, so humidity is not a problem either. Is it possible that a normal PC case will solve my problem (I'm going to shoot myself then)? I will get a picture tomorrow. Am I just simply cursed? Any help or speculation is greatly appreciated. Edit: The power strip is guarded against overvoltage. Edit2: I have moved inbetween these 4 months, so the possibility of the cause being "dirty" electricity in both places, is very low. Edit3: I have checked the voltages in the BIOS (couldn't borrow a multimeter), and they are all seem correct, the biggest discrepancy is in the 12V, because it's supplying 11.3. Should I be worried about that? Edit4: I put my desktop PC's PSU into the server. The BIOS reported much more accurate voltage readings, and also it has successfully rebuilt the raid1 array, which took some 3-4 hours, so I feel a little positive now. Will get a new PSU tomorrow to test with that. Also, attaching the picture about the box: (disregard the 3rd drive)

    Read the article

  • ASP.NET Frameworks and Raw Throughput Performance

    - by Rick Strahl
    A few days ago I had a curious thought: With all these different technologies that the ASP.NET stack has to offer, what's the most efficient technology overall to return data for a server request? When I started this it was mere curiosity rather than a real practical need or result. Different tools are used for different problems and so performance differences are to be expected. But still I was curious to see how the various technologies performed relative to each just for raw throughput of the request getting to the endpoint and back out to the client with as little processing in the actual endpoint logic as possible (aka Hello World!). I want to clarify that this is merely an informal test for my own curiosity and I'm sharing the results and process here because I thought it was interesting. It's been a long while since I've done any sort of perf testing on ASP.NET, mainly because I've not had extremely heavy load requirements and because overall ASP.NET performs very well even for fairly high loads so that often it's not that critical to test load performance. This post is not meant to make a point  or even come to a conclusion which tech is better, but just to act as a reference to help understand some of the differences in perf and give a starting point to play around with this yourself. I've included the code for this simple project, so you can play with it and maybe add a few additional tests for different things if you like. Source Code on GitHub I looked at this data for these technologies: ASP.NET Web API ASP.NET MVC WebForms ASP.NET WebPages ASMX AJAX Services  (couldn't get AJAX/JSON to run on IIS8 ) WCF Rest Raw ASP.NET HttpHandlers It's quite a mixed bag, of course and the technologies target different types of development. What started out as mere curiosity turned into a bit of a head scratcher as the results were sometimes surprising. What I describe here is more to satisfy my curiosity more than anything and I thought it interesting enough to discuss on the blog :-) First test: Raw Throughput The first thing I did is test raw throughput for the various technologies. This is the least practical test of course since you're unlikely to ever create the equivalent of a 'Hello World' request in a real life application. The idea here is to measure how much time a 'NOP' request takes to return data to the client. So for this request I create the simplest Hello World request that I could come up for each tech. Http Handler The first is the lowest level approach which is an HTTP handler. public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World. Time is: " + DateTime.Now.ToString()); } public bool IsReusable { get { return true; } } } WebForms Next I added a couple of ASPX pages - one using CodeBehind and one using only a markup page. The CodeBehind page simple does this in CodeBehind without any markup in the ASPX page: public partial class HelloWorld_CodeBehind : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write("Hello World. Time is: " + DateTime.Now.ToString() ); Response.End(); } } while the Markup page only contains some static output via an expression:<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="HelloWorld_Markup.aspx.cs" Inherits="AspNetFrameworksPerformance.HelloWorld_Markup" %> Hello World. Time is <%= DateTime.Now %> ASP.NET WebPages WebPages is the freestanding Razor implementation of ASP.NET. Here's the simple HelloWorld.cshtml page:Hello World @DateTime.Now WCF REST WCF REST was the token REST implementation for ASP.NET before WebAPI and the inbetween step from ASP.NET AJAX. I'd like to forget that this technology was ever considered for production use, but I'll include it here. Here's an OperationContract class: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfService { [OperationContract] [WebGet] public Stream HelloWorld() { var data = Encoding.Unicode.GetBytes("Hello World" + DateTime.Now.ToString()); var ms = new MemoryStream(data); // Add your operation implementation here return ms; } } WCF REST can return arbitrary results by returning a Stream object and a content type. The code above turns the string result into a stream and returns that back to the client. ASP.NET AJAX (ASMX Services) I also wanted to test ASP.NET AJAX services because prior to WebAPI this is probably still the most widely used AJAX technology for the ASP.NET stack today. Unfortunately I was completely unable to get this running on my Windows 8 machine. Visual Studio 2012  removed adding of ASP.NET AJAX services, and when I tried to manually add the service and configure the script handler references it simply did not work - I always got a SOAP response for GET and POST operations. No matter what I tried I always ended up getting XML results even when explicitly adding the ScriptHandler. So, I didn't test this (but the code is there - you might be able to test this on a Windows 7 box). ASP.NET MVC Next up is probably the most popular ASP.NET technology at the moment: MVC. Here's the small controller: public class MvcPerformanceController : Controller { public ActionResult Index() { return View(); } public ActionResult HelloWorldCode() { return new ContentResult() { Content = "Hello World. Time is: " + DateTime.Now.ToString() }; } } ASP.NET WebAPI Next up is WebAPI which looks kind of similar to MVC. Except here I have to use a StringContent result to return the response: public class WebApiPerformanceController : ApiController { [HttpGet] public HttpResponseMessage HelloWorldCode() { return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now.ToString(), Encoding.UTF8, "text/plain") }; } } Testing Take a minute to think about each of the technologies… and take a guess which you think is most efficient in raw throughput. The fastest should be pretty obvious, but the others - maybe not so much. The testing I did is pretty informal since it was mainly to satisfy my curiosity - here's how I did this: I used Apache Bench (ab.exe) from a full Apache HTTP installation to run and log the test results of hitting the server. ab.exe is a small executable that lets you hit a URL repeatedly and provides counter information about the number of requests, requests per second etc. ab.exe and the batch file are located in the \LoadTests folder of the project. An ab.exe command line  looks like this: ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorld which hits the specified URL 100,000 times with a load factor of 20 concurrent requests. This results in output like this:   It's a great way to get a quick and dirty performance summary. Run it a few times to make sure there's not a large amount of varience. You might also want to do an IISRESET to clear the Web Server. Just make sure you do a short test run to warm up the server first - otherwise your first run is likely to be skewed downwards. ab.exe also allows you to specify headers and provide POST data and many other things if you want to get a little more fancy. Here all tests are GET requests to keep it simple. I ran each test: 100,000 iterations Load factor of 20 concurrent connections IISReset before starting A short warm up run for API and MVC to make sure startup cost is mitigated Here is the batch file I used for the test: IISRESET REM make sure you add REM C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin REM to your path so ab.exe can be found REM Warm up ab.exe -n100 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldJsonab.exe -n100 -c20 http://localhost/aspnetperf/api/HelloWorldJson ab.exe -n100 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorld ab.exe -n100000 -c20 http://localhost/aspnetperf/handler.ashx > handler.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/HelloWorld_CodeBehind.aspx > AspxCodeBehind.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/HelloWorld_Markup.aspx > AspxMarkup.txt ab.exe -n100000 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorld > Wcf.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldCode > Mvc.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorld > WebApi.txt I ran each of these tests 3 times and took the average score for Requests/second, with the machine otherwise idle. I did see a bit of variance when running many tests but the values used here are the medians. Part of this has to do with the fact I ran the tests on my local machine - result would probably more consistent running the load test on a separate machine hitting across the network. I ran these tests locally on my laptop which is a Dell XPS with quad core Sandibridge I7-2720QM @ 2.20ghz and a fast SSD drive on Windows 8. CPU load during tests ran to about 70% max across all 4 cores (IOW, it wasn't overloading the machine). Ideally you can try running these tests on a separate machine hitting the local machine. If I remember correctly IIS 7 and 8 on client OSs don't throttle so the performance here should be Results Ok, let's cut straight to the chase. Below are the results from the tests… It's not surprising that the handler was fastest. But it was a bit surprising to me that the next fastest was WebForms and especially Web Forms with markup over a CodeBehind page. WebPages also fared fairly well. MVC and WebAPI are a little slower and the slowest by far is WCF REST (which again I find surprising). As mentioned at the start the raw throughput tests are not overly practical as they don't test scripting performance for the HTML generation engines or serialization performances of the data engines. All it really does is give you an idea of the raw throughput for the technology from time of request to reaching the endpoint and returning minimal text data back to the client which indicates full round trip performance. But it's still interesting to see that Web Forms performs better in throughput than either MVC, WebAPI or WebPages. It'd be interesting to try this with a few pages that actually have some parsing logic on it, but that's beyond the scope of this throughput test. But what's also amazing about this test is the sheer amount of traffic that a laptop computer is handling. Even the slowest tech managed 5700 requests a second, which is one hell of a lot of requests if you extrapolate that out over a 24 hour period. Remember these are not static pages, but dynamic requests that are being served. Another test - JSON Data Service Results The second test I used a JSON result from several of the technologies. I didn't bother running WebForms and WebPages through this test since that doesn't make a ton of sense to return data from the them (OTOH, returning text from the APIs didn't make a ton of sense either :-) In these tests I have a small Person class that gets serialized and then returned to the client. The Person class looks like this: public class Person { public Person() { Id = 10; Name = "Rick"; Entered = DateTime.Now; } public int Id { get; set; } public string Name { get; set; } public DateTime Entered { get; set; } } Here are the updated handler classes that use Person: Handler public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { var action = context.Request.QueryString["action"]; if (action == "json") JsonRequest(context); else TextRequest(context); } public void TextRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World. Time is: " + DateTime.Now.ToString()); } public void JsonRequest(HttpContext context) { var json = JsonConvert.SerializeObject(new Person(), Formatting.None); context.Response.ContentType = "application/json"; context.Response.Write(json); } public bool IsReusable { get { return true; } } } This code adds a little logic to check for a action query string and route the request to an optional JSON result method. To generate JSON, I'm using the same JSON.NET serializer (JsonConvert.SerializeObject) used in Web API to create the JSON response. WCF REST   [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfService { [OperationContract] [WebGet] public Stream HelloWorld() { var data = Encoding.Unicode.GetBytes("Hello World " + DateTime.Now.ToString()); var ms = new MemoryStream(data); // Add your operation implementation here return ms; } [OperationContract] [WebGet(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)] public Person HelloWorldJson() { // Add your operation implementation here return new Person(); } } For WCF REST all I have to do is add a method with the Person result type.   ASP.NET MVC public class MvcPerformanceController : Controller { // // GET: /MvcPerformance/ public ActionResult Index() { return View(); } public ActionResult HelloWorldCode() { return new ContentResult() { Content = "Hello World. Time is: " + DateTime.Now.ToString() }; } public JsonResult HelloWorldJson() { return Json(new Person(), JsonRequestBehavior.AllowGet); } } For MVC all I have to do for a JSON response is return a JSON result. ASP.NET internally uses JavaScriptSerializer. ASP.NET WebAPI public class WebApiPerformanceController : ApiController { [HttpGet] public HttpResponseMessage HelloWorldCode() { return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now.ToString(), Encoding.UTF8, "text/plain") }; } [HttpGet] public Person HelloWorldJson() { return new Person(); } [HttpGet] public HttpResponseMessage HelloWorldJson2() { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new ObjectContent<Person>(new Person(), GlobalConfiguration.Configuration.Formatters.JsonFormatter); return response; } } Testing and Results To run these data requests I used the following ab.exe commands:REM JSON RESPONSES ab.exe -n100000 -c20 http://localhost/aspnetperf/Handler.ashx?action=json > HandlerJson.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/MvcPerformance/HelloWorldJson > MvcJson.txt ab.exe -n100000 -c20 http://localhost/aspnetperf/api/HelloWorldJson > WebApiJson.txt ab.exe -n100000 -c20 http://localhost/AspNetPerf/WcfService.svc/HelloWorldJson > WcfJson.txt The results from this test run are a bit interesting in that the WebAPI test improved performance significantly over returning plain string content. Here are the results:   The performance for each technology drops a little bit except for WebAPI which is up quite a bit! From this test it appears that WebAPI is actually significantly better performing returning a JSON response, rather than a plain string response. Snag with Apache Benchmark and 'Length Failures' I ran into a little snag with Apache Benchmark, which was reporting failures for my Web API requests when serializing. As the graph shows performance improved significantly from with JSON results from 5580 to 6530 or so which is a 15% improvement (while all others slowed down by 3-8%). However, I was skeptical at first because the WebAPI test reports showed a bunch of errors on about 10% of the requests. Check out this report: Notice the Failed Request count. What the hey? Is WebAPI failing on roughly 10% of requests when sending JSON? Turns out: No it's not! But it took some sleuthing to figure out why it reports these failures. At first I thought that Web API was failing, and so to make sure I re-ran the test with Fiddler attached and runiisning the ab.exe test by using the -X switch: ab.exe -n100 -c10 -X localhost:8888 http://localhost/aspnetperf/api/HelloWorldJson which showed that indeed all requests where returning proper HTTP 200 results with full content. However ab.exe was reporting the errors. After some closer inspection it turned out that the dates varying in size altered the response length in dynamic output. For example: these two results: {"Id":10,"Name":"Rick","Entered":"2012-09-04T10:57:24.841926-10:00"} {"Id":10,"Name":"Rick","Entered":"2012-09-04T10:57:24.8519262-10:00"} are different in length for the number which results in 68 and 69 bytes respectively. The same URL produces different result lengths which is what ab.exe reports. I didn't notice at first bit the same is happening when running the ASHX handler with JSON.NET result since it uses the same serializer that varies the milliseconds. Moral: You can typically ignore Length failures in Apache Benchmark and when in doubt check the actual output with Fiddler. Note that the other failure values are accurate though. Another interesting Side Note: Perf drops over Time As I was running these tests repeatedly I was finding that performance steadily dropped from a startup peak to a 10-15% lower stable level. IOW, with Web API I'd start out with around 6500 req/sec and in subsequent runs it keeps dropping until it would stabalize somewhere around 5900 req/sec occasionally jumping lower. For these tests this is why I did the IIS RESET and warm up for individual tests. This is a little puzzling. Looking at Process Monitor while the test are running memory very quickly levels out as do handles and threads, on the first test run. Subsequent runs everything stays stable, but the performance starts going downwards. This applies to all the technologies - Handlers, Web Forms, MVC, Web API - curious to see if others test this and see similar results. Doing an IISRESET then resets everything and performance starts off at peak again… Summary As I stated at the outset, these were informal to satiate my curiosity not to prove that any technology is better or even faster than another. While there clearly are differences in performance the differences (other than WCF REST which was by far the slowest and the raw handler which was by far the highest) are relatively minor, so there is no need to feel that any one technology is a runaway standout in raw performance. Choosing a technology is about more than pure performance but also about the adequateness for the job and the easy of implementation. The strengths of each technology will make for any minor performance difference we see in these tests. However, to me it's important to get an occasional reality check and compare where new technologies are heading. Often times old stuff that's been optimized and designed for a time of less horse power can utterly blow the doors off newer tech and simple checks like this let you compare. Luckily we're seeing that much of the new stuff performs well even in V1.0 which is great. To me it was very interesting to see Web API perform relatively badly with plain string content, which originally led me to think that Web API might not be properly optimized just yet. For those that caught my Tweets late last week regarding WebAPI's slow responses was with String content which is in fact considerably slower. Luckily where it counts with serialized JSON and XML WebAPI actually performs better. But I do wonder what would make generic string content slower than serialized code? This stresses another point: Don't take a single test as the final gospel and don't extrapolate out from a single set of tests. Certainly Twitter can make you feel like a fool when you post something immediate that hasn't been fleshed out a little more <blush>. Egg on my face. As a result I ended up screwing around with this for a few hours today to compare different scenarios. Well worth the time… I hope you found this useful, if not for the results, maybe for the process of quickly testing a few requests for performance and charting out a comparison. Now onwards with more serious stuff… Resources Source Code on GitHub Apache HTTP Server Project (ab.exe is part of the binary distribution)© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

    - by Django Reinhardt
    This is driving the whole team crazy. There must be some simple mis-configured part of IIS or our Web Server, but every time we try to run out ASP.NET Web Application on IIS 7.5 we get the following error... Here's the error in full: HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid. `Detailed Error Information` Module IIS Web Core Notification Unknown Handler Not yet determined Error Code 0x8007000d Config Error Config File \\?\E:\wwwroot\web.config Requested URL http://localhost:80/Default.aspx Physical Path Logon Method Not yet determined Logon User Not yet determined Config Source -1: 0: The machine is running Windows Server 2008 R2. We're developing our Web Application using Visual Studio 2008. According to Microsoft the code 8007000d means there's a syntax error in our web.config -- except the project builds and runs fine locally. Looking at the web.config in XML Notepad doesn't bring up any syntax errors, either. I'm assuming it must be some sort of poor configuration on my part...? Does anyone know where I might find further information about the error? Nothing is showing in EventViewer, either :( Not sure what else would be helpful to mention... Assistance is greatly appreciated. Thanks! UPDATES! - POSTED WEB.CONFIG BELOW Ok, since I posted the original question above, I've tracked down the precise lines in the web.config that were causing the error. Here are the lines (they appear between <System.webServer> tags)... <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> </httpHandlers> Note: If I delete the lines between the <httpHandlers> I STILL get the error. I literally have to delete <httpHandlers> (and the lines inbetween) to stop getting the above error. Once I've done this I get a new 500.19 error, however. Thankfully, this time IIS actually tells me which bit of the web.config is causing a problem... <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> </handlers> Looking at these lines it's clear the problem has migrated further within the same <system.webServer> tag to the <handlers> tag. The new error is also more explicit and specifically complains that it doesn't recognize the attribute "validate" (as seen on the third line above). Removing this attribute then makes it complain that the same line doesn't have the required "name" attribute. Adding this attribute then brings up ASP.NET error... Could not load file or assembly 'System.web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56' or one of its dependencies. The system cannot find the file specified. Obviously I think these new errors have just arisen from me deleting the <httpHandlers> tags in the first place -- they're obviously needed by the application -- so the question remains: Why would these tags kick up an error in IIS in the first place??? Do I need to install something to IIS to make it work with them? Thanks again for any help. WEB.CONFIG Here's the troublesome bits of our web.Config... I hope this helps someone find our problem! <system.Web> <!-- stuff cut out --> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> </httpModules> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> </modules> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=f2cb5667dc123a56"/> </handlers> </system.webServer>

    Read the article

< Previous Page | 1 2 3