Search Results

Search found 713 results on 29 pages for 'quantity'.

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

  • using jquery to load data from mysql database

    - by Ieyasu Sawada
    I'm currently using jquery's ajax feature or whatever they call it. To load data from mysql database. Its working fine, but one of the built in features of this one is to load all the data which is on the database when you press on backspace and there's no character left on the text box. Here's my query: SELECT * FROM prod_table WHERE QTYHAND>0 AND PRODUCT LIKE '$prod%' OR P_DESC LIKE '$desc%' OR CATEGORY LIKE '$cat%' As you can see I only want to load the products which has greater than 0 quantity on hand. I'm using this code to communicate to the php file which has the query on it: $('#inp').keyup(function(){ var inpval=$('#inp').val(); $.ajax({ type: 'POST', data: ({p : inpval}), url: 'querys.php', success: function(data) { $('.result').html(data); } }); }); Is it possible to also filter the data that it outputs so that when I press on backspace and there's no character left. The only products that's going to display are those with greater than 0 quantity?

    Read the article

  • List of items with same values

    - by user559780
    I'm creating a list of items from a file BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("H:/temp/data.csv"))); try { List<Item> items = new ArrayList<Item>(); Item item = new Item(); String line = null; while ((line = reader.readLine()) != null) { String[] split = line.split(","); item.name = split[0]; item.quantity = Integer.valueOf(split[1]); item.price = Double.valueOf(split[2]); item.total = item.quantity * item.price; items.add(item); } for (Item item2 : items) { System.out.println("Item: " + item2.name); } } catch (IOException e) { reader.close(); e.printStackTrace(); } Problem is the list is displaying the last line in the file as the value for all items.

    Read the article

  • Is there any Python library that allows me to parse an HTML document similar to what jQuery does?

    - by Sachin Tendulkar
    Is there any Python library that allows me to parse an HTML document similar to what jQuery does? i.e. I'd like to be able to use CSS selector syntax to grab an arbitrary set of nodes from the document, read their content/attributes, etc. The only Python HTML parsing lib I've used before was BeautifulSoup, and even though it's fine I keep thinking it would be faster to do my parsing if I had jQuery syntax available. :D Write an iterative program that finds the largest number of McNuggets that cannot be bought in exact quantity. Your program should print the answer in the following format (where the correct number is provided in place of n): "Largest number of McNuggets that cannot be bought in exact quantity: n"

    Read the article

  • How to return Json from WCF Service?

    - by Zinoo
    Hi, I have the piece of code below of a template Ajax enabled WCF service. What can i do to make it return JSon instead of XML? thanks. using System; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; [ServiceContract(Namespace = "WCFServiceEight")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class CostService { // Add [WebGet] attribute to use HTTP GET [OperationContract] [WebGet] public double CostOfSandwiches(int quantity) { return 1.25 * quantity; } }

    Read the article

  • MySQL Query, how to group and count in one row ?

    - by Akarun
    Hi All, To simplify, I have tree tables: products, products-vs-orders, orders products fields : 'ProductID', 'Name', 'isGratis', ... products-vs-orders fields : 'ProductID', 'OrderID' orders fields : 'OrderID', 'Title', ... Actually, I have a query like this: SELECT orders.OrderID, orders.Title, COUNT(`products`.`isGratis`) AS "Quantity", `products`.`isGratis` FROM `orders`, `products-vs-orders`, `products` WHERE `orders`.`OrderID` = `products-vs-orders`.`OrderID` AND `products-vs-orders`.`ProductID` = `products`.`ProductID` GROUP BY `products`.`PackID`, `products`.`isGratis` This query works and return this surch of result: OrderID, Title, Quantity, isGratis 1 My Order 20 0 1 My Order 3 1 2 An other 8 0 2 An other 1 1 How can I retrieve the count of products 'gratis' and 'paid' in to separate cols ? OrderID, Title, Qt Paid, Qt Gratis 1 My Order 20 3 2 An other 8 1 Thanks for your help

    Read the article

  • Fluent nHibernate - How to map a non-key column on a junction table?

    - by The Matt
    Taking an example that is provided on the Fluent nHibernate website, I need to extend it slightly: I need to add a 'Quantity' column to the StoreProduct table. How would I map this using nHibernate? An example mapping is provided for the given scenario above, but I'm not sure how I would get the Quantity column to map to a property on the Product class: public class StoreMap : ClassMap<Store> { public StoreMap() { Id(x => x.Id); Map(x => x.Name); HasMany(x => x.Employee) .Inverse() .Cascade.All(); HasManyToMany(x => x.Products) .Cascade.All() .Table("StoreProduct"); } }

    Read the article

  • What's an elegant solution to get the property values from two classes (that have the same property

    - by SlipToFall
    Essentially I have to deal with a poorly implemented web service. They have two classes that don't derive from a parent class, but have the same properties (Ughh...). So it looks like this in my web service proxy class file: public partial class Product1 { public int Quantity; public int Price; } public partial class Product2 { public int Quantity; public int Price; } So what's the best way to grab the values from known properties without duplicating the code and casting to their respective classes? I know I probably could use reflection, but that can get ugly. If there is an easier less crazier way to do it (maybe in the new c# features?) please let me know.

    Read the article

  • What is the response on a REST call where a field is not valid?

    - by MediaSlayer
    There are many questions on StackOverflow about this, but no definitive answer. I have a REST resource where an entity's field, ProductId, is sent. If the ProductId passed is invalid, what kind of response would you do? I want to send the right response code plus information to the requester on what they can do to fix it. Initial thoughts were 422 with the body containing the list of errors in JSON/XML format. Maybe like this (JSON): [ { FieldName : "ProductId", ErrorCode : "M123", Description : "Product Not Found" }, { FieldName : "Quantity", ErrorCode : "Q001", Description : "Quantity cannot be more than 100" } ] Thoughts?

    Read the article

  • php regex to split invoice line item description

    - by user1053700
    I am attempting to split strings like the following: An item (Item A) which may contain 89798 numbers and letters @ $550.00 4 of Item B @ $420.00 476584 of Item C, with a larger quantity and different currency symbol @ £420.00 into: array( 0 => 1 1 => "some item which may contain 89798 numbers and letters" 2 => $550.00 ); does that make sense? I am looking for a regex pattern which will split the quantity, description, and price (including symbol). the strings will always be: qty x description @ price+symbol so i assume the regex would be something like: `(match a number and only a number) x (get description letters and numbers before the @ symbol) @ (match the currency symbol and price)` How should I approach this?

    Read the article

  • Mass data store with SQL SERVER

    - by Leo
    We need management 10,000 GPS devices, each GPS device upload a GPS data every 30 seconds, these data need to store in the database(MS SQL Server 2005). Each GPS device daily data quantity is: 24 * 60 * 2 = 2,880 10 000 10,000 GPS devices daily data quantity is: 10000 * 2880 = 28,800,000 Each GPS data approximately 160Byte, the amount of data per day is: 28,800,000 * 160 = 4.29GB We need hold at least 3 months of GPS data in the database, My question is: 1, whether SQL Server 2005 can support such a large amount of data store? 2, How to plan data table? (all GPS data storage in one table? Daily table? Each GPS device with a GPS data table?) The GPS data: GPSID varchar(21), RecvTime datetime, GPSTime datetime, IsValid bit, IsNavi bit, Lng float, Lat float, Alt float, Spd smallint, Head smallint, PulseValue bigint, Oil float, TSW1 bigint, TSW1Mask bigint, TSW2 bigint, TSW2Mask, BSW bigint, StateText varchar(200), PosText varchar(200), UploadType tinyint

    Read the article

  • Grouping and retrieving most recent entry in a table for each group

    - by Lisa
    First off, please bear with me if I don't state the SQL question correctly. I have a table that has multiple columns of data. The selection criteria for my table groups based on column 1(order #). There could be multiple items on each order, but the item #'s are not grouped together. Example: Order Customer Order Date Order Time Item Quantity 123456 45 01/02/2010 08:00 140 4 123456 45 01/02/2010 08:30 270 29 123456 45 03/03/2010 09:00 140 6 123456 45 04/02/2010 09:30 140 10 123456 45 04/02/2010 10:00 270 35 What I need is a result like: Order Customer Order Date Order Time Item Quantity 123456 45 04/02/2010 09:30 140 10 123456 45 04/02/2010 10:00 270 35 This result shows that after all the changes the final order includes 10 of Item 140 and 35 of Item 270. Is this possible. python

    Read the article

  • Stop running this script, IE7 using PHP

    - by Jomel Dicen
    I incorporate javascript in my PHP program: Try to check my codes. It loops depend on the number of records in database. for instance: $counter = 0; foreach($row_value as $data): echo $this->javascript($counter, $data->exrate, $data->tab); endforeach; private function javascript($counter=NULL, $exrate=NULL, $tab=NULL){ $js = " <script type='text/javascript'> $(function () { var textBox0 = $('input:text[id$=quantity{$counter}]').keyup(foo); var textBox1 = $('input:text[id$=mc{$counter}]').keyup(foo); var textBox2 = $('input:text[id$=lc{$counter}]').keyup(foo); function foo() { var value0 = textBox0.val(); var value1 = textBox1.val(); var value2 = textBox2.val(); var sum = add(value1, value2) * (value0 * {$exrate}); $('input:text[id$=result{$counter}]').val(parseFloat(sum).toFixed(2)); // Compute Total Quantity var qtotal = 0; $('.quantity{$tab}').each(function() { qtotal += Number($(this).val()); }); $('#tquantity{$tab}').text(qtotal); // Compute MC UNIT var mctotal = 0; $('.mc{$tab}').each(function() { mctotal += Number($(this).val()); }); $('#tmc{$tab}').text(mctotal); // Compute LC UNIT var lctotal = 0; $('.lc{$tab}').each(function() { lctotal += Number($(this).val()); }); $('#tlc{$tab}').text(lctotal); // Compute Result var result = 0; $('.result{$tab}').each(function() { result += Number($(this).val()); }); $('#tresult{$tab}').text(result); } function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { if (IsNumeric(arguments[i])) { sum += parseFloat(arguments[i]); } } return sum; } function IsNumeric(input) { return (input - 0) == input && input.length > 0; } }); </script> "; return $js; } When I running this on IE this message is always annoying me " Stop running this script? A script on this page is causing your web browser to run slowly. If it continues to run, your computer might become unresponsive." but in firefox it's functioning well.

    Read the article

  • how to get change event on created fields in jquery

    - by frosty
    I have some jquery code the creates an quantity text box. Like so <input type="text" value="1000" class="qty" name="[0].Quantity"> I wish to add some validation to this text box but can hit the method. I believe i need to utlise Live(). But can't quite figure out how this is implemented. This is where i'm at $(document).ready(function () { $(".qty").change(checkValue); }); function checkValue() { alert("on change"); }

    Read the article

  • How do I specify a default value in a MS Access query?

    - by jheddings
    I have three tables similar to the following: tblInvoices: Number | Date | Customer tblInvDetails: Invoice | Quantity | Rate | Description tblPayments: Invoice | Date | Amount I have created a query called exInvDetails that adds an Amount column to tblInvDetails: SELECT tblInvDetails.*, [tblInvDetails.Quantity]*[tblInvDetails.Rate]* AS Amount FROM tblInvDetails; I then created a query exInvoices to add Total and Balance columns to tblInvoices: SELECT tblInvoices.*, (SELECT Sum(exInvDetails.Amount) FROM exInvDetails WHERE exInvDetails.Invoice = tblInvoices.Number) AS Total, (SELECT Sum(tblPayments.Amount) FROM tblPayments WHERE tblPayments.Invoice = tblInvoices.Number) AS Payments, (Total-Payments) AS Balance FROM tblInvoices; If there are no corresponding payments in tblPayments, the fields are null instead of 0. Is there a way to force the resulting query to put a 0 in this column?

    Read the article

  • How to using String.split in this case?

    - by hoang nguyen
    I want to write a fuction like that: - Input: "1" -> return : "1" - Input: "12" -> return : ["1","2"] If I use the function split(): String.valueOf("12").split("") -> ["","1","2"] But, I only want to get the result: ["1","2"]. What the best way to do this? Infact, I can do that: private List<String> decomposeQuantity(final int quantity) { LinkedList<String> list = new LinkedList<String>(); int parsedQuantity = quantity; while (parsedQuantity > 0) { list.push(String.valueOf(parsedQuantity % 10)); parsedQuantity = parsedQuantity / 10; } return list; } But, I want to use split() for having an affective code

    Read the article

  • TSQL Prefixing String Literal on Insert - Any Value to This, or Redundant?

    - by SethO
    I just inherited a project that has code similar to the following (rather simple) example: DECLARE @Demo TABLE ( Quantity INT, Symbol NVARCHAR(10) ) INSERT INTO @Demo (Quantity, Symbol) SELECT 127, N'IBM' My interest is with the N before the string literal. I understand that the prefix N is to specify encoding (in this case, Unicode). But since the select is just for inserting into a field that is clearly already Unicode, wouldn't this value be automatically upcast? I've run the code without the N and it appears to work, but am I missing something that the previous programmer intended? Or was the N an oversight on his/her part? I expect behavior similar to when I pass an int to a decimal field (auto-upcast). Can I get rid of those Ns?

    Read the article

  • Query to return substring from string in SQL Server

    - by Jowie
    I have a user defined function called Sync_CheckData under Scalar-valued functions in Microsoft SQL Server. What it actually does is to check the quantity of issued product and balance quantity are the same. If something is wrong, returns an ErrorStr nvarchar(255). Output Example: Balance Stock Error for Product ID : 4 From the above string, I want to get 4 so that later on I can SELECT the rows which is giving errors by using WHERE clause (WHERE Product_ID = 4). Which SQL function can I use to get the substring?

    Read the article

  • Access to related Objects inside a model propery

    - by aliem
    Hi, I just run into some problems with django models. Example code is better than any word: class Cart(models.Model): updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'date %s;'%(self.created_at) def __str__(self): return self.__unicode__() def _total_items(self): """ Totale n di oggetti """ a = 0 for i in self.items.all: a += i.quantity return a total_items = property(_total_items) class Item(models.Model): cart = models.ForeignKey(Cart) quantity = models.PositiveIntegerField() def __unicode__(self): return u'product %s'%(self.id) def __str__(self): return self.__unicode__() but, when i call the cart property here's what i get in the python console: >>> a.total_items Traceback (most recent call last): File "<console>", line 1, in <module> File "models.py", line 49, in _total_items for i in self.item_set.all: TypeError: 'RelatedManager' object is not callable

    Read the article

  • Is this data set in third normal form?

    - by user2980802
    UNF: (Customer-name, Customer-id, Customer-address, (Unit-price, Order-id, Quantity, Product-id, Delivery-date) (Supplier-name, Supplier-id, Supplier-Address) 3NF: CUSTOMER (Customer-id, Order-id, Customer-name, Customer-address) ORDER (Order-id, Customer-id) ORDER/PRODUCT (Order-id, Quantity, Product-id) PRODUCT (Order-id, Product-id, Delivery-date, Supplier-id, Unit-price,) SUPPLIER (Supplier-name, Supplier-id, Supplier-Address, Product-id) Basically, the UNF is the un-normalised form. The information should have EXACTLY five tables, it's a hint we were given. The tables listed are the definite table names. We were told to make assumptions based on this information: Customer Invoice is generated from customer orders (Order & Order/Product entities) Supplier Order is generated for products that are low in stock (Product entity) Assumptions A customer can place many orders but an order is placed by only one customer An order can be for many products and a product can be ordered many times A product is supplied by only one supplier, a supplier may supply many products This is one of my modules in university and my lecturer is all but useful, I'm really struggling so any help is really appreciated.

    Read the article

  • [ASP.NET MVC] Problem with View - it does not refresh after db update

    - by crocodillez
    Hi, I am working with small ASP.NET MVC project - online store. I have addToCart method which adds selected product to cart - it updates cart table in my db and showing cart view with its content. But I have problems. while db is updating correctly the view does not. I see that quantity of the product in my db is incremented correctly but quantity in view is not changed. I have to stop debugging my app in visual studia and restart it - then my view is showing correct data. What can be wrong?

    Read the article

  • EF Linq Product Sum when no records returned

    - by user1622713
    I’ve seen variations of this question all over the place but none of the answers work for me. Most of them are just trying to sum a single column too – nothing more complex such as the sum of a product as below: public double Total { get { return _Context.Sales.Where(t => t.Quantity > 0) .DefaultIfEmpty() .Sum(t => t.Quantity * t.Price); } } If no rows are returned I want to return zero. However if no rows are returned the .Sum() fails. There are various options of trying to insert Convert.ToDouble and using null coalesce operators, but they all still gave me errors. I’m sure I am missing a simple way to do this – any help greatly appreciated after too long banging head against google brick wall!

    Read the article

  • Second query to SQLite (on iPhone) errors.

    - by Luke
    Hi all, On the iPhone, I am developing a class for a cart that connects directly to a database. To view the cart, all items can be pulled from the database, however, it seems that removing them doesn't work. It is surprising to me because the error occurs during connection to the database, except not the second time I connect even after the DB has been closed. #import "CartDB.h" #import "CartItem.h" @implementation CartDB @synthesize database, databasePath; - (NSMutableArray *) getAllItems { NSMutableArray *items = [[NSMutableArray alloc] init]; if([self openDatabase]) { const char *sqlStatement = "SELECT * FROM items;"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(cartDatabase, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { while(sqlite3_step(compiledStatement) == SQLITE_ROW) { int rowId = sqlite3_column_int(compiledStatement, 0); int productId = sqlite3_column_int(compiledStatement, 1); NSString *features = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; int quantity = sqlite3_column_int(compiledStatement, 3); CartItem *cartItem = [[CartItem alloc] initWithRowId:rowId productId:productId features:features quantity:quantity]; [items addObject:cartItem]; [cartItem release]; } } sqlite3_finalize(compiledStatement); } [self closeDatabase]; return items; } - (BOOL) removeCartItem:(CartItem *)item { sqlite3_stmt *deleteStatement; [self openDatabase]; const char *sql = "DELETE FROM items WHERE id = ?"; if(sqlite3_prepare_v2(cartDatabase, sql, -1, &deleteStatement, NULL) != SQLITE_OK) { return NO; } sqlite3_bind_int(deleteStatement, 1, item.rowId); if(SQLITE_DONE != sqlite3_step(deleteStatement)) { sqlite3_reset(deleteStatement); [self closeDatabase]; return NO; } else { sqlite3_reset(deleteStatement); [self closeDatabase]; return YES; } } - (BOOL) openDatabase { if(sqlite3_open([databasePath UTF8String], &cartDatabase) == SQLITE_OK) { return YES; } else { return NO; } } - (void) closeDatabase { sqlite3_close(cartDatabase); } The error occurs on the line where the connection is opened in openDatabase. Any ideas? Need to flush something? Something gets autoreleased? I really can't figure it out. --Edit-- The error that I receive is GDB: Program received signal "EXC_BAD_ACCESS". --Edit-- I ended up just connecting in the init and closing in the free methods, which might not be the proper way, but that's another question altogether so it's effectively persistent instead of connecting multiple times. Still would be nice to know what was up with this for future reference.

    Read the article

  • jQuery code .val(); not working in FF

    - by SzamDev
    Hi I have this code function calculateTotal() { var total = 0; $(".quantity").each(function() { if (!isNaN(this.value) && this.value.length != 0) { total += parseFloat(this.value); } }); $("#total_quantity").val(total); } <input onchange="calculateTotal();" name="sol1" type="text" class="result_form_textbox_small quantity" id="sol1" /> <input name="total_quantity" type="text" class="result_form_textbox_small" id="total_quantity" /> This code is working in IE very good but it's not working in FF. What is the proplem? Thanks in advance.

    Read the article

  • FAQ: GridView Calculation with JavaScript - Formatting and Validation

    - by Vincent Maverick Durano
    In my previous post here we've talked about how to calculate the sub-totals and grand total in GridView using JavaScript. In this post I'm going take more step further and will demonstrate how are we going to format the totals into a currency and how to validate the input that would only allow you to enter a whole number in the quantity TextBox. Here are the code blocks below: ASPX Source:   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script type="text/javascript"> function CalculateTotals() { var gv = document.getElementById("<%= GridView1.ClientID %>"); var tb = gv.getElementsByTagName("input"); var lb = gv.getElementsByTagName("span"); var sub = 0; var total = 0; var indexQ = 1; var indexP = 0; var price = 0; for (var i = 0; i < tb.length; i++) { if (tb[i].type == "text") { ValidateNumber(tb[i]); price = lb[indexP].innerHTML.replace("$", "").replace(",", ""); sub = parseFloat(price) * parseFloat(tb[i].value); if (isNaN(sub)) { lb[i + indexQ].innerHTML = "0.00"; sub = 0; } else { lb[i + indexQ].innerHTML = FormatToMoney(sub, "$", ",", "."); ; } indexQ++; indexP = indexP + 2; total += parseFloat(sub); } } lb[lb.length - 1].innerHTML = FormatToMoney(total, "$", ",", "."); } function ValidateNumber(o) { if (o.value.length > 0) { o.value = o.value.replace(/[^\d]+/g, ''); //Allow only whole numbers } } function isThousands(position) { if (Math.floor(position / 3) * 3 == position) return true; return false; }; function FormatToMoney(theNumber, theCurrency, theThousands, theDecimal) { var theDecimalDigits = Math.round((theNumber * 100) - (Math.floor(theNumber) * 100)); theDecimalDigits = "" + (theDecimalDigits + "0").substring(0, 2); theNumber = "" + Math.floor(theNumber); var theOutput = theCurrency; for (x = 0; x < theNumber.length; x++) { theOutput += theNumber.substring(x, x + 1); if (isThousands(theNumber.length - x - 1) && (theNumber.length - x - 1 != 0)) { theOutput += theThousands; }; }; theOutput += theDecimal + theDecimalDigits; return theOutput; } </script> </head> <body> <form id="form1" runat="server"> <asp:gridview ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> <asp:BoundField DataField="Description" HeaderText="Item Description" /> <asp:TemplateField HeaderText="Item Price"> <ItemTemplate> <asp:Label ID="LBLPrice" runat="server" Text='<%# Eval("Price","{0:C}") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="TXTQty" runat="server" onkeyup="CalculateTotals();"></asp:TextBox> </ItemTemplate> <FooterTemplate> <b>Total Amount:</b> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Sub-Total"> <ItemTemplate> <asp:Label ID="LBLSubTotal" runat="server" ForeColor="Green" Text="0.00"></asp:Label> </ItemTemplate> <FooterTemplate> <asp:Label ID="LBLTotal" runat="server" ForeColor="Green" Font-Bold="true" Text="0.00"></asp:Label> </FooterTemplate> </asp:TemplateField> </Columns> </asp:gridview> </form> </body> </html> Code Behind Source:   public partial class GridCalculation : System.Web.UI.Page { private void BindDummyDataToGrid() { DataTable dt = new DataTable(); DataRow dr = null; dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); dt.Columns.Add(new DataColumn("Description", typeof(string))); dt.Columns.Add(new DataColumn("Price", typeof(decimal))); dr = dt.NewRow(); dr["RowNumber"] = 1; dr["Description"] = "Nike"; dr["Price"] = "1000"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 2; dr["Description"] = "Converse"; dr["Price"] = "800"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 3; dr["Description"] = "Adidas"; dr["Price"] = "500"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 4; dr["Description"] = "Reebok"; dr["Price"] = "750"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 5; dr["Description"] = "Vans"; dr["Price"] = "1100"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 6; dr["Description"] = "Fila"; dr["Price"] = "200"; dt.Rows.Add(dr); //Bind the Gridview GridView1.DataSource = dt; GridView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDummyDataToGrid(); } } } Running the code above will display something like this: On initial load After entering the quantity in the TextBox That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,C#,ADO.NET,JavaScript,GridView

    Read the article

  • ANTS CLR and Memory Profiler In Depth Review (Part 1 of 2 &ndash; CLR Profiler)

    - by ToStringTheory
    One of the things that people might not know about me, is my obsession to make my code as efficient as possible.  Many people might not realize how much of a task or undertaking that this might be, but it is surely a task as monumental as climbing Mount Everest, except this time it is a challenge for the mind…  In trying to make code efficient, there are many different factors that play a part – size of project or solution, tiers, language used, experience and training of the programmer, technologies used, maintainability of the code – the list can go on for quite some time. I spend quite a bit of time when developing trying to determine what is the best way to implement a feature to accomplish the efficiency that I look to achieve.  One program that I have recently come to learn about – Red Gate ANTS Performance (CLR) and Memory profiler gives me tools to accomplish that job more efficiently as well.  In this review, I am going to cover some of the features of the ANTS profiler set by compiling some hideous example code to test against. Notice As a member of the Geeks With Blogs Influencers program, one of the perks is the ability to review products, in exchange for a free license to the program.  I have not let this affect my opinions of the product in any way, and Red Gate nor Geeks With Blogs has tried to influence my opinion regarding this product in any way. Introduction The ANTS Profiler pack provided by Red Gate was something that I had not heard of before receiving an email regarding an offer to review it for a license.  Since I look to make my code efficient, it was a no brainer for me to try it out!  One thing that I have to say took me by surprise is that upon downloading the program and installing it you fill out a form for your usual contact information.  Sure enough within 2 hours, I received an email from a sales representative at Red Gate asking if she could help me to achieve the most out of my trial time so it wouldn’t go to waste.  After replying to her and explaining that I was looking to review its feature set, she put me in contact with someone that setup a demo session to give me a quick rundown of its features via an online meeting.  After having dealt with a massive ordeal with one of my utility companies and their complete lack of customer service, Red Gates friendly and helpful representatives were a breath of fresh air, and something I was thankful for. ANTS CLR Profiler The ANTS CLR profiler is the thing I want to focus on the most in this post, so I am going to dive right in now. Install was simple and took no time at all.  It installed both the profiler for the CLR and Memory, but also visual studio extensions to facilitate the usage of the profilers (click any images for full size images): The Visual Studio menu options (under ANTS menu) Starting the CLR Performance Profiler from the start menu yields this window If you follow the instructions after launching the program from the start menu (Click File > New Profiling Session to start a new project), you are given a dialog with plenty of options for profiling: The New Session dialog.  Lots of options.  One thing I noticed is that the buttons in the lower right were half-covered by the panel of the application.  If I had to guess, I would imagine that this is caused by my DPI settings being set to 125%.  This is a problem I have seen in other applications as well that don’t scale well to different dpi scales. The profiler options give you the ability to profile: .NET Executable ASP.NET web application (hosted in IIS) ASP.NET web application (hosted in IIS express) ASP.NET web application (hosted in Cassini Web Development Server) SharePoint web application (hosted in IIS) Silverlight 4+ application Windows Service COM+ server XBAP (local XAML browser application) Attach to an already running .NET 4 process Choosing each option provides a varying set of other variables/options that one can set including options such as application arguments, operating path, record I/O performance performance counters to record (43 counters in all!), etc…  All in all, they give you the ability to profile many different .Net project types, and make it simple to do so.  In most cases of my using this application, I would be using the built in Visual Studio extensions, as they automatically start a new profiling project in ANTS with the options setup, and start your program, however RedGate has made it easy enough to profile outside of Visual Studio as well. On the flip side of this, as someone who lives most of their work life in Visual Studio, one thing I do wish is that instead of opening an entirely separate application/gui to perform profiling after launching, that instead they would provide a Visual Studio panel with the information, and integrate more of the profiling project information into Visual Studio.  So, now that we have an idea of what options that the profiler gives us, its time to test its abilities and features. Horrendous Example Code – Prime Number Generator One of my interests besides development, is Physics and Math – what I went to college for.  I have especially always been interested in prime numbers, as they are something of a mystery…  So, I decided that I would go ahead and to test the abilities of the profiler, I would write a small program, website, and library to generate prime numbers in the quantity that you ask for.  I am going to start off with some terrible code, and show how I would see the profiler being used as a development tool. First off, the IPrimes interface (all code is downloadable at the end of the post): interface IPrimes { IEnumerable<int> GetPrimes(int retrieve); } Simple enough, right?  Anything that implements the interface will (hopefully) provide an IEnumerable of int, with the quantity specified in the parameter argument.  Next, I am going to implement this interface in the most basic way: public class DumbPrimes : IPrimes { public IEnumerable<int> GetPrimes(int retrieve) { //store a list of primes already found var _foundPrimes = new List<int>() { 2, 3 }; //if i ask for 1 or two primes, return what asked for if (retrieve <= _foundPrimes.Count()) return _foundPrimes.Take(retrieve); //the next number to look at int _analyzing = 4; //since I already determined I don't have enough //execute at least once, and until quantity is sufficed do { //assume prime until otherwise determined bool isPrime = true; //start dividing at 2 //divide until number is reached, or determined not prime for (int i = 2; i < _analyzing && isPrime; i++) { //if (i) goes into _analyzing without a remainder, //_analyzing is NOT prime if (_analyzing % i == 0) isPrime = false; } //if it is prime, add to found list if (isPrime) _foundPrimes.Add(_analyzing); //increment number to analyze next _analyzing++; } while (_foundPrimes.Count() < retrieve); return _foundPrimes; } } This is the simplest way to get primes in my opinion.  Checking each number by the straight definition of a prime – is it divisible by anything besides 1 and itself. I have included this code in a base class library for my solution, as I am going to use it to demonstrate a couple of features of ANTS.  This class library is consumed by a simple non-MVVM WPF application, and a simple MVC4 website.  I will not post the WPF code here inline, as it is simply an ObservableCollection<int>, a label, two textbox’s, and a button. Starting a new Profiling Session So, in Visual Studio, I have just completed my first stint developing the GUI and DumbPrimes IPrimes class, so now I want to check my codes efficiency by profiling it.  All I have to do is build the solution (surprised initiating a profiling session doesn’t do this, but I suppose I can understand it), and then click the ANTS menu, followed by Profile Performance.  I am then greeted by the profiler starting up and already monitoring my program live: You are provided with a realtime graph at the top, and a pane at the bottom giving you information on how to proceed.  I am going to start by asking my program to show me the first 15000 primes: After the program finally began responding again (I did all the work on the main UI thread – how bad!), I stopped the profiler, which did kill the process of my program too.  One important thing to note, is that the profiler by default wants to give you a lot of detail about the operation – line hit counts, time per line, percent time per line, etc…  The important thing to remember is that this itself takes a lot of time.  When running my program without the profiler attached, it can generate the 15000 primes in 5.18 seconds, compared to 74.5 seconds – almost a 1500 percent increase.  While this may seem like a lot, remember that there is a trade off.  It may be WAY more inefficient, however, I am able to drill down and make improvements to specific problem areas, and then decrease execution time all around. Analyzing the Profiling Session After clicking ‘Stop Profiling’, the process running my application stopped, and the entire execution time was automatically selected by ANTS, and the results shown below: Now there are a number of interesting things going on here, I am going to cover each in a section of its own: Real Time Performance Counter Bar (top of screen) At the top of the screen, is the real time performance bar.  As your application is running, this will constantly update with the currently selected performance counters status.  A couple of cool things to note are the fact that you can drag a selection around specific time periods to drill down the detail views in the lower 2 panels to information pertaining to only that period. After selecting a time period, you can bookmark a section and name it, so that it is easy to find later, or after reloaded at a later time.  You can also zoom in, out, or fit the graph to the space provided – useful for drilling down. It may be hard to see, but at the top of the processor time graph below the time ticks, but above the red usage graph, there is a green bar. This bar shows at what times a method that is selected in the ‘Call tree’ panel is called. Very cool to be able to click on a method and see at what times it made an impact. As I said before, ANTS provides 43 different performance counters you can hook into.  Click the arrow next to the Performance tab at the top will allow you to change between different counters if you have them selected: Method Call Tree, ADO.Net Database Calls, File IO – Detail Panel Red Gate really hit the mark here I think. When you select a section of the run with the graph, the call tree populates to fill a hierarchical tree of method calls, with information regarding each of the methods.   By default, methods are hidden where the source is not provided (framework type code), however, Red Gate has integrated Reflector into ANTS, so even if you don’t have source for something, you can select a method and get the source if you want.  Methods are also hidden where the impact is seen as insignificant – methods that are only executed for 1% of the time of the overall calling methods time; in other words, working on making them better is not where your efforts should be focused. – Smart! Source Panel – Detail Panel The source panel is where you can see line level information on your code, showing the code for the currently selected method from the Method Call Tree.  If the code is not available, Reflector takes care of it and shows the code anyways! As you can notice, there does seem to be a problem with how ANTS determines what line is the actual line that a call is completed on.  I have suspicions that this may be due to some of the inline code optimizations that the CLR applies upon compilation of the assembly.  In a method with comments, the problem is much more severe: As you can see here, apparently the most offending code in my base library was a comment – *gasp*!  Removing the comments does help quite a bit, however I hope that Red Gate works on their counter algorithm soon to improve the logic on positioning for statistics: I did a small test just to demonstrate the lines are correct without comments. For me, it isn’t a deal breaker, as I can usually determine the correct placements by looking at the application code in the region and determining what makes sense, but it is something that would probably build up some irritation with time. Feature – Suggest Method for Optimization A neat feature to really help those in need of a pointer, is the menu option under tools to automatically suggest methods to optimize/improve: Nice feature – clicking it filters the call tree and stars methods that it thinks are good candidates for optimization.  I do wish that they would have made it more visible for those of use who aren’t great on sight: Process Integration I do think that this could have a place in my process.  After experimenting with the profiler, I do think it would be a great benefit to do some development, testing, and then after all the bugs are worked out, use the profiler to check on things to make sure nothing seems like it is hogging more than its fair share.  For example, with this program, I would have developed it, ran it, tested it – it works, but slowly. After looking at the profiler, and seeing the massive amount of time spent in 1 method, I might go ahead and try to re-implement IPrimes (I actually would probably rewrite the offending code, but so that I can distribute both sets of code easily, I’m just going to make another implementation of IPrimes).  Using two pieces of knowledge about prime numbers can make this method MUCH more efficient – prime numbers fall into two buckets 6k+/-1 , and a number is prime if it is not divisible by any other primes before it: public class SmartPrimes : IPrimes { public IEnumerable<int> GetPrimes(int retrieve) { //store a list of primes already found var _foundPrimes = new List<int>() { 2, 3 }; //if i ask for 1 or two primes, return what asked for if (retrieve <= _foundPrimes.Count()) return _foundPrimes.Take(retrieve); //the next number to look at int _k = 1; //since I already determined I don't have enough //execute at least once, and until quantity is sufficed do { //assume prime until otherwise determined bool isPrime = true; int potentialPrime; //analyze 6k-1 //assign the value to potential potentialPrime = 6 * _k - 1; //if there are any primes that divise this, it is NOT a prime number //using PLINQ for quick boost isPrime = !_foundPrimes.AsParallel() .Any(prime => potentialPrime % prime == 0); //if it is prime, add to found list if (isPrime) _foundPrimes.Add(potentialPrime); if (_foundPrimes.Count() == retrieve) break; //analyze 6k+1 //assign the value to potential potentialPrime = 6 * _k + 1; //if there are any primes that divise this, it is NOT a prime number //using PLINQ for quick boost isPrime = !_foundPrimes.AsParallel() .Any(prime => potentialPrime % prime == 0); //if it is prime, add to found list if (isPrime) _foundPrimes.Add(potentialPrime); //increment k to analyze next _k++; } while (_foundPrimes.Count() < retrieve); return _foundPrimes; } } Now there are definitely more things I can do to help make this more efficient, but for the scope of this example, I think this is fine (but still hideous)! Profiling this now yields a happy surprise 27 seconds to generate the 15000 primes with the profiler attached, and only 1.43 seconds without.  One important thing I wanted to call out though was the performance graph now: Notice anything odd?  The %Processor time is above 100%.  This is because there is now more than 1 core in the operation.  A better label for the chart in my mind would have been %Core time, but to each their own. Another odd thing I noticed was that the profiler seemed to be spot on this time in my DumbPrimes class with line details in source, even with comments..  Odd. Profiling Web Applications The last thing that I wanted to cover, that means a lot to me as a web developer, is the great amount of work that Red Gate put into the profiler when profiling web applications.  In my solution, I have a simple MVC4 application setup with 1 page, a single input form, that will output prime values as my WPF app did.  Launching the profiler from Visual Studio as before, nothing is really different in the profiler window, however I did receive a UAC prompt for a Red Gate helper app to integrate with the web server without notification. After requesting 500, 1000, 2000, and 5000 primes, and looking at the profiler session, things are slightly different from before: As you can see, there are 4 spikes of activity in the processor time graph, but there is also something new in the call tree: That’s right – ANTS will actually group method calls by get/post operations, so it is easier to find out what action/page is giving the largest problems…  Pretty cool in my mind! Overview Overall, I think that Red Gate ANTS CLR Profiler has a lot to offer, however I think it also has a long ways to go.  3 Biggest Pros: Ability to easily drill down from time graph, to method calls, to source code Wide variety of counters to choose from when profiling your application Excellent integration/grouping of methods being called from web applications by request – BRILLIANT! 3 Biggest Cons: Issue regarding line details in source view Nit pick – Processor time vs. Core time Nit pick – Lack of full integration with Visual Studio Ratings Ease of Use (7/10) – I marked down here because of the problems with the line level details and the extra work that that entails, and the lack of better integration with Visual Studio. Effectiveness (10/10) – I believe that the profiler does EXACTLY what it purports to do.  Especially with its large variety of performance counters, a definite plus! Features (9/10) – Besides the real time performance monitoring, and the drill downs that I’ve shown here, ANTS also has great integration with ADO.Net, with the ability to show database queries run by your application in the profiler.  This, with the line level details, the web request grouping, reflector integration, and various options to customize your profiling session I think create a great set of features! Customer Service (10/10) – My entire experience with Red Gate personnel has been nothing but good.  their people are friendly, helpful, and happy! UI / UX (8/10) – The interface is very easy to get around, and all of the options are easy to find.  With a little bit of poking around, you’ll be optimizing Hello World in no time flat! Overall (8/10) – Overall, I am happy with the Performance Profiler and its features, as well as with the service I received when working with the Red Gate personnel.  I WOULD recommend you trying the application and seeing if it would fit into your process, BUT, remember there are still some kinks in it to hopefully be worked out. My next post will definitely be shorter (hopefully), but thank you for reading up to here, or skipping ahead!  Please, if you do try the product, drop me a message and let me know what you think!  I would love to hear any opinions you may have on the product. Code Feel free to download the code I used above – download via DropBox

    Read the article

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