Search Results

Search found 42685 results on 1708 pages for 'page speed'.

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

  • How to get the if the Page is Liked in my Facebook Application page

    - by Axe
    I'm using the Facebook sdk from codeplex I've tried the suggestion at How to get the Page Id in my Facebook Application page which is this: if (FacebookWebContext.Current.SignedRequest != null) { dynamic data = FacebookWebContext.Current.SignedRequest.Data; if (data.page != null) { var pageId = (String)data.page.id; var isUserAdmin = (Boolean)data.page.admin; var userLikesPage = (Boolean)data.page.liked; } else { // not on a page } } But my data.page is null. Do I need to ask for some extra permissions on the authorization or something? Also tried this the FQL suggested at http://blog.woodylabs.com/2010/09/facebook-graph-api-is-user-a-fan-of-page-id-using-fql-and-opengraph-to-mimic-pages-isfan/ But I only have an appId not a page ID. Any ideas?

    Read the article

  • Slow self hosted wordpress website

    - by Integrati Marketing
    Hi All, we have a great site which has been humming along nicely for about 5 months and then in May it went from a page load speed time of 3-5 secs to now an agonising 15+ secs!!! The host has been really helpful and has even shifted the site to a new server which is faster! I guess seeing as though we do not have the insight or your expertise we would ask the Serverfault community and see what this crowd of experts could recommend? Appreciate any insight, thank you. site is here: integrati.com.au Cheers. :)

    Read the article

  • Slow slef hosted wordpress website

    - by Integrati Marketing
    Hi All, we have a great site which has been humming along nicely for about 5 months and then in May it went from a page load speed time of 3-5 secs to now an agonising 15+ secs!!! The host has been really helpful and has even shifted the site to a new server which is faster! I guess seeing as though we do not have the insight or your expertise we would ask the Serverfault community and see what this crowd of experts could recommend? Appreciate any insight, thank you. site is here: integrati.com.au Cheers. :)

    Read the article

  • Facebook: I became Admin of a Page but can't edit it

    - by Michael G.
    Hello! I'm testing around with facebook and made a test-page with a workmate. He made me an admin. I clicked the link in the mail from facebook, i got to the side and there's no "edit the page" link under the picture. So we added an other workmate as admin. Even he isn't supposed to edit the page. What can it be?

    Read the article

  • game speed problem

    - by Meko
    HI..I made a little game.But this game works on every computer with different speed.I think it is about resolution.I used every thing in paintcomponent.and If I change screen size the game goes slower or faster.And if i run this game on another computer wich has different resolution it also works different. This is my game http://rapidshare.com/files/364597095/ShooterGame.2.6.0.jar and here code public class Shooter extends JFrame implements KeyListener, Runnable { JFrame frame = new JFrame(); String player; Font startFont, startSubFont, timerFont,healthFont; Image img; Image backGround; Graphics dbi; URL url1 = this.getClass().getResource("Images/p2.gif"); URL url2 = this.getClass().getResource("Images/p3.gif"); URL url3 = this.getClass().getResource("Images/p1.gif"); URL url4 = this.getClass().getResource("Images/p4.gif"); URL urlMap = this.getClass().getResource("Images/zemin.jpg"); Player p1 = new Player(5, 150, 10, 40, Color.GREEN, url3); Computer p2 = new Computer(750, 150, 10, 40, Color.BLUE, url1); Computer p3 = new Computer(0, 0, 10, 40, Color.BLUE, url2); Computer p4 = new Computer(0, 0, 10, 40, Color.BLUE, url4); ArrayList<Bullets> b = new ArrayList<Bullets>(); ArrayList<CBullets> cb = new ArrayList<CBullets>(); Thread sheap; boolean a, d, w, s; boolean toUp, toDown; boolean GameOver; boolean Level2; boolean newGame, resart, pause; int S, E; int random; int cbSpeed = 0; long timeStart, timeEnd; int timeElapsed; long GameStart, GameEnd; int GameScore; int Timer = 0; int timerStart, timerEnd; public Shooter() { sheap = new Thread(this); sheap.start(); startFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 32); startSubFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 25); timerFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 16); healthFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 16); setTitle("Shooter 2.5.1"); setBounds(350, 250, 800, 600); // setResizable(false); setBackground(Color.black); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addKeyListener(this); a = d = w = s = false; toUp = toDown = true; GameOver = true; newGame = true; Level2 = false; S = E = 0; setVisible(true); } public void paint(Graphics g) { img = createImage(getWidth(), getHeight()); dbi = img.getGraphics(); paintComponent(dbi); g.drawImage(img, 0, 0, this); } public void paintComponent(Graphics g) { repaint(); timeStart = System.currentTimeMillis(); backGround = Toolkit.getDefaultToolkit().getImage(urlMap); g.drawImage(backGround, 0, 0, null); g.setColor(Color.red); g.setFont(healthFont); g.drawString("" + player + " Health : " + p1.health, 30, 50); g.setColor(Color.red); g.drawString("Computer Health : " + (p2.health + p3.health + p4.health), 600, 50); g.setColor(Color.BLUE); g.setFont(timerFont); g.drawString("Time : " + Timer, 330, 50); if (newGame) { g.setColor(Color.LIGHT_GRAY); g.setFont(startFont); g.drawString("Well Come To Shoot Game", 200, 190); g.drawString("Press ENTER To Start", 250, 220); g.setColor(Color.LIGHT_GRAY); g.setFont(startSubFont); g.drawString("Use W,A,S,D and Space For Fire", 200, 250); g.drawString("GOOD LUCK", 250, 280); newGame(); } if (!GameOver) { for (Bullets b1 : b) { b1.draw(g); } for (CBullets b2 : cb) { b2.draw(g); } update(); // Here MOvements for Player and For Fires } if (p1.health <= 0) { g.setColor(p2.col); g.setFont(startFont); g.drawString("Computer Wins ", 200, 190); g.drawString("Press Key R to Restart ", 200, 220); GameOver = true; } else if (p2.health <= 0 && p3.health <= 0 && p4.health <= 0) { g.setColor(p1.col); g.setFont(startFont); g.drawString(""+player+" Wins ", 200, 190); g.drawString("Press Key R to Resart ", 200, 220); GameOver = true; g.setColor(Color.MAGENTA); g.drawString(""+player+"`s Score is " + Timer, 200, 120); } if (Level2) { if (p3.health >= 0) { p3.draw(g); for (CBullets b3 : cb) { b3.draw(g); } } else { p3.x = 1000; } if (p4.health >= 0) { p4.draw(g); for (CBullets b4 : cb) { b4.draw(g); } } else { p4.x = 1000; } } if (p1.health >= 0) { p1.draw(g); } if (p2.health >= 0) { p2.draw(g); } else { p2.x = 1000; } } public void update() { if (w && p1.y > 54) { p1.moveUp(); } if (s && p1.y < 547) { p1.moveDown(); } if (a && p1.x > 0) { p1.moveLeft(); } if (d && p1.x < 200) { p1.moveRight(); } random = 1 * (int) (Math.random() * 100); if (random > 96) { if (p2.health >= 0) { CBullets bo = p2.getCBull(); bo.xVel =-1-cbSpeed; cb.add(bo); } if (Level2) { if (p3.health >= 0) { CBullets bo1 = p3.getCBull(); bo1.xVel = -2-cbSpeed; cb.add(bo1); } if (p4.health >= 0) { CBullets bo2 = p4.getCBull(); bo2.xVel = -4-cbSpeed; cb.add(bo2); } } } if (S == 1) { if (p1.health >= 0) { Bullets bu = p1.getBull(); bu.xVel = 5; b.add(bu); S += 1; } } //Here Also Problem .. When COmputer have More fire then it gaves Array Exeption . Or Player have More Fire for (int i = cb.size() -1; i = 0 ; i--) { boolean bremoved = false; for (int j = b.size() -1 ; j =0 ; j--) { if (b.get(j).rect.intersects(cb.get(i).rect) || cb.get(i).rect.intersects(b.get(j).rect)) { bremoved = true; b.remove(j); } } if(bremoved) cb.remove(i); } for (int i = 0; i < b.size(); i++) { b.get(i).move(); if (b.get(i).rect.intersects(p2.rect)) { if (p2.health >= 0) { p2.health--; b.remove(i); // System.out.println("Hited P2"); i--; continue; } } if (b.get(i).rect.intersects(p3.rect)) { if (p3.health >= 0) { p3.health--; b.remove(i); // System.out.println("Hited P3"); i--; continue; } } if (b.get(i).rect.intersects(p4.rect)) { if (p4.health >= 0) { p4.health--; b.remove(i); // System.out.println("Hited P4"); i--; continue; } } if (b.get(i).rect.x > 790) { b.remove(i); } } for (int j = 0; j < cb.size(); j++) { cb.get(j).move(); if (cb.get(j).rect.intersects(p1.rect) && cb.get(j).xVel < 0) { p1.health--; cb.remove(j); j--; continue; } } timeEnd = System.currentTimeMillis(); timeElapsed = (int) (timeEnd - timeStart); } public void level2() { if (p2.health <= 10) { Level2 = true; cbSpeed = 4; p3.x = 750; p4.x = 750; p2.speed = 10; p3.speed = 20; p4.speed = 30; } } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_ENTER: newGame = false; break; case KeyEvent.VK_P: pause = true; break; case KeyEvent.VK_R: resart = true; break; case KeyEvent.VK_A: a = true; break; case KeyEvent.VK_D: d = true; break; case KeyEvent.VK_W: w = true; break; case KeyEvent.VK_S: s = true; break; case KeyEvent.VK_SPACE: S += 1; break; } } public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_A: a = false; break; case KeyEvent.VK_D: d = false; break; case KeyEvent.VK_W: w = false; break; case KeyEvent.VK_S: s = false; break; case KeyEvent.VK_SPACE: S = 0; break; } } public void newGame() { p1.health = 20; p2.health = 20; p3.health = 20; p4.health = 20; p3.x = 0; p4.x = 0; p2.x = 750; Level2 = false; cbSpeed = 0; p2.speed = 9; b.removeAll(b); cb.removeAll(cb); timerStart = (int) System.currentTimeMillis(); GameOver = false; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { KeyListener k = new Shooter(); } }); } @Override public void run() { player = JOptionPane.showInputDialog(frame, "Enter Player Name", "New Player", JOptionPane.DEFAULT_OPTION); while (true) { timerEnd = (int) System.currentTimeMillis(); if (resart) { newGame(); resart = false; } if (pause) { Thread.currentThread().notify(); } try { if (!GameOver) { Timer = timerEnd - timerStart; level2(); if (p1.y < p2.y && p2.y60) { p2.moveUp(); } if (p1.y < p3.y && p3.y43) { p3.moveUp(); } if (p1.y < p4.y && p4.y43) { p4.moveUp(); } if (p1.y > p2.y && p2.y<535) { p2.moveDown(); } if (p1.y > p3.y && p3.y<535) { p3.moveDown(); } if (p1.y > p4.y && p4.y<530) { p4.moveDown(); } } if (timeElapsed < 125) { Thread.currentThread().sleep(125); } } catch (InterruptedException ex) { System.out.print("FInished"); } } } }

    Read the article

  • Increasing speed of python code

    - by Curious2learn
    Hi, I have some python code that has many classes. I used cProfile to find that the total time to run the program is 68 seconds. I found that the following function in a class called Buyers takes about 60 seconds of those 68 seconds. I have to run the program about 100 times, so any increase in speed will help. Can you suggest ways to increase the speed by modifying the code? If you need more information that will help, please let me know. def qtyDemanded(self, timePd, priceVector): '''Returns quantity demanded in period timePd. In addition, also updates the list of customers and non-customers. Inputs: timePd and priceVector Output: count of people for whom priceVector[-1] < utility ''' ## Initialize count of customers to zero ## Set self.customers and self.nonCustomers to empty lists price = priceVector[-1] count = 0 self.customers = [] self.nonCustomers = [] for person in self.people: if person.utility >= price: person.customer = 1 self.customers.append(person) else: person.customer = 0 self.nonCustomers.append(person) return len(self.customers) self.people is a list of person objects. Each person has customer and utility as its attributes. EDIT - responsed added ------------------------------------- Thanks so much for the suggestions. Here is the response to some questions and suggestions people have kindly made. I have not tried them all, but will try others and write back later. (1) @amber - the function is accessed 80,000 times. (2) @gnibbler and others - self.people is a list of Person objects in memory. Not connected to a database. (3) @Hugh Bothwell cumtime taken by the original function - 60.8 s (accessed 80000 times) cumtime taken by the new function with local function aliases as suggested - 56.4 s (accessed 80000 times) (4) @rotoglup and @Martin Thomas I have not tried your solutions yet. I need to check the rest of the code to see the places where I use self.customers before I can make the change of not appending the customers to self.customers list. But I will try this and write back. (5) @TryPyPy - thanks for your kind offer to check the code. Let me first read a little on the suggestions you have made to see if those will be feasible to use. EDIT 2 Some suggested that since I am flagging the customers and noncustomers in the self.people, I should try without creating separate lists of self.customers and self.noncustomers using append. Instead, I should loop over the self.people to find the number of customers. I tried the following code and timed both functions below f_w_append and f_wo_append. I did find that the latter takes less time, but it is still 96% of the time taken by the former. That is, it is a very small increase in the speed. @TryPyPy - The following piece of code is complete enough to check the bottleneck function, in case your offer is still there to check it with other compilers. Thanks again to everyone who replied. import numpy class person(object): def __init__(self, util): self.utility = util self.customer = 0 class population(object): def __init__(self, numpeople): self.people = [] self.cus = [] self.noncus = [] numpy.random.seed(1) utils = numpy.random.uniform(0, 300, numpeople) for u in utils: per = person(u) self.people.append(per) popn = population(300) def f_w_append(): '''Function with append''' P = 75 cus = [] noncus = [] for per in popn.people: if per.utility >= P: per.customer = 1 cus.append(per) else: per.customer = 0 noncus.append(per) return len(cus) def f_wo_append(): '''Function without append''' P = 75 for per in popn.people: if per.utility >= P: per.customer = 1 else: per.customer = 0 numcustomers = 0 for per in popn.people: if per.customer == 1: numcustomers += 1 return numcustomers

    Read the article

  • PHP speed optimisation.

    - by Petah
    Hi, Im wondering about speed optimization in PHP. I have a series of files that are requested every page load. On average there are 20 files. Each file must be read an parsed if they have changed. And this is excluding that standard files required for a web page (HTML, CSS, images, etc). EG - client requests page - server outputs html, css, images - server outputs dynamic content (20+/- files combined and minified). What would be the best way to serve these files as fast as possible?

    Read the article

  • which factors determines the speed of a processor? [closed]

    - by Deb
    I think that clock rate of processor determines the speed of core, in my case it is 1.86GHz. But If I am not wrong, it also determines that how much energy it will consume. If you have more frequency then more power it will consume. I choose Power Saver scheme to increase my battery life, however it reduces my core speed to half of the actual speed. I understand this happens because of SpeedStep, but I don't see any slowdown of my computer. So my problem is why we have such high frequency cores as it uses too much power. We can use low frequency cores. Actually I get confused between the two terms Speed of the processor and its frequency. So how much important is the frequency of core in case of any processor.

    Read the article

  • How to get an ARM CPU clock speed in Linux?

    - by MiKy
    I have an ARM-based embedded machine based on S3C2416 board. According to the specifications I have available there should be a 533 MHz ARM9 (ARM926EJ-S according to /proc/cpuinfo), however the software running on it "feels" slow, compared to the same software on my Android phone with a 528MHz ARM CPU. /proc/cpuinfo tells me that BogoMIPS is 266.24. I know that I should not trust BogoMIPS regarding performance ("Bogo" = bogus), however I would like to get a measurement on the actual CPU speed. On x86, I could use the rdtsc instruction to get the time stamp counter, wait a second (sleep(1)), read the counter again to get an approximation on the CPU speed, and according to my experience, this value was close enough to the real CPU speed. How can I find the actual CPU speed of given ARM processor? Update I found this simple Pi calculator, which I compiled both for my Android phone and the ARM board. The results are as follows: S3C2416 # cat /proc/cpuinfo Processor : ARM926EJ-S rev 5 (v5l) BogoMIPS : 266.24 Features : swp half fastmult edsp java ... #./pi_arm 10000 Calculation of PI using FFT and AGM, ver. LG1.1.2-MP1.5.2a.memsave ... 8.50 sec. (real time) Android # cat /proc/cpuinfo Processor : ARMv6-compatible processor rev 2 (v6l) BogoMIPS : 527.56 Features : swp half thumb fastmult edsp java # ./pi_android 10000 Calculation of PI using FFT and AGM, ver. LG1.1.2-MP1.5.2a.memsave ... 5.95 sec. (real time) So it seems that the ARM926EJ-S is slower than my Android phone, but not twice slower as I would expect by the BogoMIPS figures. I am still unsure about the clock speed of the ARM9 CPU.

    Read the article

  • How much the distance and ms can affect on the download speed ?

    - by Prix
    Let's consider A (client) and B (server) where A makes download from B. How much can a bad routing from A to B affect the download speed ? For example A does a tracert to B and get a response of 10 steps where the avg ms is around 300 with 10% packet loss at the 4 step and when the connection is normal the avg from A to B is 10 ~ 30 ms. Could this sort of impact reduce A download speed drasticaly or as long as both side and routes have enough link for the full speed of A from B and vice-versa it should maintain the same speed ? Besides tracert and the ping analyse of A to B what else is used to identify the problem ? If you need extra information please let me know.

    Read the article

  • ASP.Net Cross Page Posting

    - by John
    Currently I have two pages: The first page contains an input form, and the 2nd page generates an excel document. The input form's button posts to this 2nd page. What I'd like to do is add a second button which also posts to the 2nd page; however, I'll need requests created from this new button to act differently, which brings me to my question: Is there a way I can tell, from the 2nd page, which button was pressed to submit the request? The main reason I'm asking is I'd like to re-use the 2nd page's logic in parsing the information from the first page if possible; I'd rather not have to copy it to a new page and have the new button post to that. Thanks!

    Read the article

  • Access &lt;body element from content page via a nested master page

    - by danwellman
    All I want to do is access the <body element from the code-behind of a content page and add a class name to it. I have a top-level master page with the <body element in it. Then I have a nested master page which is the master page for the content page. From the code behind of the content page I want to add a class name to the body element. That's all. I have this in the top-level master: <body id="bodyNode" runat="server"> I added this to the code-behind for the content page: Master.bodyNode.Attributes.add("class", "home-page"); And I get a message that: System.Web.UI.MasterPage' does not contain a definition for 'bodyNode If I add this to the aspx content page: <% @ MasterType VirtualPath="~/MasterPage.master"%> The message then changes to: bodyNode is inaccessible due to its protection level Please advise, I've wasted like 2 hours on what feels like something that should be really simple to do :(

    Read the article

  • how to increase speed of my execution

    - by ratty
    i am creating project in c#.net. my execution process is very slow. i also found the reason for that.in one method i copied the values from one list to another.that list consists more 3000values for every row . how can i speed up this process.any body help me

    Read the article

  • Python vs. Java performance (runtime speed)

    - by Bijan
    Ignoring all the characteristics of each languages and focusing SOLELY on speed, which language is better performance-wise? You'd think this would be a rather simple question to answer, but I haven't found a decent one. I'm aware that some types of operations may be faster with python, and vice-versa, but I cannot find any detailed information on this. Can anyone shed some light on the performance differences?

    Read the article

  • Speed of NSScanner vs NSXMLParser?

    - by Chris
    I have an iPhone App that reads in an XML file, then pulls out the necessary data by looping through an NSScanner. The XML is not particularly long. I am wondering if it would be worth the work to implement NSXMLParser in place of using NSScanner, if I will see any real improvement in speed?

    Read the article

  • Speed test (open source)

    - by Nimbuz
    Are there any good (preferably PHP) open source scripts that I use to measure download/upload speeds? Something like speedtest.net but without Flash. Basically, I want to put up a 'broadband speed test' website. I found this but is there anything better already available? Thanks!

    Read the article

  • Page reload needed several times before loading normally

    - by tim peterson
    Sorry my question is so vague I just have no idea where to start in solving it and am quite a novice with servers. Recently my site (an https connection, running on an Amazon EC2 ubuntu apache2.2) has this issue where I need to load the page several times (3-4) before it will load normally without issue. It will then load normally as long as I keep loading pages regularly (every couple seconds). It will stall again if I don't load pages for a few minutes. It has nothing to do with my application because I don't have this problem with the exact same app codebase on my Apache installation on my laptop. The only thing to my knowledge that I changed is that I installed mod_pagespeed https://developers.google.com/speed/pagespeed/mod. However, I have since turned it off by setting my pagespeed.conf to mod_pagespeed off. Unfortunately, that didn't solve the problem. I'm wondering general advice on how to troubleshoot this problem. For instance are there linux commands to check page loading peformance? Also, it looks like I have lots of new error.logs in my /var/log/apache2 directory which i believe weren't there a few months ago. lots of this : error.log RewriteLog.log.24.gz ssl_access.log.40.gz error.log.1 RewriteLog.log.25.gz ssl_access.log.41.gz error.log.10.gz RewriteLog.log.26.gz ssl_access.log.42.gz error.log.11.gz RewriteLog.log.27.gz any thoughts? thank you, tim

    Read the article

  • Security Issues with Single Page Apps

    - by Stephen.Walther
    Last week, I was asked to do a code review of a Single Page App built using the ASP.NET Web API, Durandal, and Knockout (good stuff!). In particular, I was asked to investigate whether there any special security issues associated with building a Single Page App which are not present in the case of a traditional server-side ASP.NET application. In this blog entry, I discuss two areas in which you need to exercise extra caution when building a Single Page App. I discuss how Single Page Apps are extra vulnerable to both Cross-Site Scripting (XSS) attacks and Cross-Site Request Forgery (CSRF) attacks. This goal of this blog post is NOT to persuade you to avoid writing Single Page Apps. I’m a big fan of Single Page Apps. Instead, the goal is to ensure that you are fully aware of some of the security issues related to Single Page Apps and ensure that you know how to guard against them. Cross-Site Scripting (XSS) Attacks According to WhiteHat Security, over 65% of public websites are open to XSS attacks. That’s bad. By taking advantage of XSS holes in a website, a hacker can steal your credit cards, passwords, or bank account information. Any website that redisplays untrusted information is open to XSS attacks. Let me give you a simple example. Imagine that you want to display the name of the current user on a page. To do this, you create the following server-side ASP.NET page located at http://MajorBank.com/SomePage.aspx: <%@Page Language="C#" %> <html> <head> <title>Some Page</title> </head> <body> Welcome <%= Request["username"] %> </body> </html> Nothing fancy here. Notice that the page displays the current username by using Request[“username”]. Using Request[“username”] displays the username regardless of whether the username is present in a cookie, a form field, or a query string variable. Unfortunately, by using Request[“username”] to redisplay untrusted information, you have now opened your website to XSS attacks. Here’s how. Imagine that an evil hacker creates the following link on another website (hackers.com): <a href="/SomePage.aspx?username=<script src=Evil.js></script>">Visit MajorBank</a> Notice that the link includes a query string variable named username and the value of the username variable is an HTML <SCRIPT> tag which points to a JavaScript file named Evil.js. When anyone clicks on the link, the <SCRIPT> tag will be injected into SomePage.aspx and the Evil.js script will be loaded and executed. What can a hacker do in the Evil.js script? Anything the hacker wants. For example, the hacker could display a popup dialog on the MajorBank.com site which asks the user to enter their password. The script could then post the password back to hackers.com and now the evil hacker has your secret password. ASP.NET Web Forms and ASP.NET MVC have two automatic safeguards against this type of attack: Request Validation and Automatic HTML Encoding. Protecting Coming In (Request Validation) In a server-side ASP.NET app, you are protected against the XSS attack described above by a feature named Request Validation. If you attempt to submit “potentially dangerous” content — such as a JavaScript <SCRIPT> tag — in a form field or query string variable then you get an exception. Unfortunately, Request Validation only applies to server-side apps. Request Validation does not help in the case of a Single Page App. In particular, the ASP.NET Web API does not pay attention to Request Validation. You can post any content you want – including <SCRIPT> tags – to an ASP.NET Web API action. For example, the following HTML page contains a form. When you submit the form, the form data is submitted to an ASP.NET Web API controller on the server using an Ajax request: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form data-bind="submit:submit"> <div> <label> User Name: <input data-bind="value:user.userName" /> </label> </div> <div> <label> Email: <input data-bind="value:user.email" /> </label> </div> <div> <input type="submit" value="Submit" /> </div> </form> <script src="Scripts/jquery-1.7.1.js"></script> <script src="Scripts/knockout-2.1.0.js"></script> <script> var viewModel = { user: { userName: ko.observable(), email: ko.observable() }, submit: function () { $.post("/api/users", ko.toJS(this.user)); } }; ko.applyBindings(viewModel); </script> </body> </html> The form above is using Knockout to bind the form fields to a view model. When you submit the form, the view model is submitted to an ASP.NET Web API action on the server. Here’s the server-side ASP.NET Web API controller and model class: public class UsersController : ApiController { public HttpResponseMessage Post(UserViewModel user) { var userName = user.UserName; return Request.CreateResponse(HttpStatusCode.OK); } } public class UserViewModel { public string UserName { get; set; } public string Email { get; set; } } If you submit the HTML form, you don’t get an error. The “potentially dangerous” content is passed to the server without any exception being thrown. In the screenshot below, you can see that I was able to post a username form field with the value “<script>alert(‘boo’)</script”. So what this means is that you do not get automatic Request Validation in the case of a Single Page App. You need to be extra careful in a Single Page App about ensuring that you do not display untrusted content because you don’t have the Request Validation safety net which you have in a traditional server-side ASP.NET app. Protecting Going Out (Automatic HTML Encoding) Server-side ASP.NET also protects you from XSS attacks when you render content. By default, all content rendered by the razor view engine is HTML encoded. For example, the following razor view displays the text “<b>Hello!</b>” instead of the text “Hello!” in bold: @{ var message = "<b>Hello!</b>"; } @message   If you don’t want to render content as HTML encoded in razor then you need to take the extra step of using the @Html.Raw() helper. In a Web Form page, if you use <%: %> instead of <%= %> then you get automatic HTML Encoding: <%@ Page Language="C#" %> <% var message = "<b>Hello!</b>"; %> <%: message %> This automatic HTML Encoding will prevent many types of XSS attacks. It prevents <script> tags from being rendered and only allows &lt;script&gt; tags to be rendered which are useless for executing JavaScript. (This automatic HTML encoding does not protect you from all forms of XSS attacks. For example, you can assign the value “javascript:alert(‘evil’)” to the Hyperlink control’s NavigateUrl property and execute the JavaScript). The situation with Knockout is more complicated. If you use the Knockout TEXT binding then you get HTML encoded content. On the other hand, if you use the HTML binding then you do not: <!-- This JavaScript DOES NOT execute --> <div data-bind="text:someProp"></div> <!-- This Javacript DOES execute --> <div data-bind="html:someProp"></div> <script src="Scripts/jquery-1.7.1.js"></script> <script src="Scripts/knockout-2.1.0.js"></script> <script> var viewModel = { someProp : "<script>alert('Evil!')<" + "/script>" }; ko.applyBindings(viewModel); </script>   So, in the page above, the DIV element which uses the TEXT binding is safe from XSS attacks. According to the Knockout documentation: “Since this binding sets your text value using a text node, it’s safe to set any string value without risking HTML or script injection.” Just like server-side HTML encoding, Knockout does not protect you from all types of XSS attacks. For example, there is nothing in Knockout which prevents you from binding JavaScript to a hyperlink like this: <a data-bind="attr:{href:homePageUrl}">Go</a> <script src="Scripts/jquery-1.7.1.min.js"></script> <script src="Scripts/knockout-2.1.0.js"></script> <script> var viewModel = { homePageUrl: "javascript:alert('evil!')" }; ko.applyBindings(viewModel); </script> In the page above, the value “javascript:alert(‘evil’)” is bound to the HREF attribute using Knockout. When you click the link, the JavaScript executes. Cross-Site Request Forgery (CSRF) Attacks Cross-Site Request Forgery (CSRF) attacks rely on the fact that a session cookie does not expire until you close your browser. In particular, if you visit and login to MajorBank.com and then you navigate to Hackers.com then you will still be authenticated against MajorBank.com even after you navigate to Hackers.com. Because MajorBank.com cannot tell whether a request is coming from MajorBank.com or Hackers.com, Hackers.com can submit requests to MajorBank.com pretending to be you. For example, Hackers.com can post an HTML form from Hackers.com to MajorBank.com and change your email address at MajorBank.com. Hackers.com can post a form to MajorBank.com using your authentication cookie. After your email address has been changed, by using a password reset page at MajorBank.com, a hacker can access your bank account. To prevent CSRF attacks, you need some mechanism for detecting whether a request is coming from a page loaded from your website or whether the request is coming from some other website. The recommended way of preventing Cross-Site Request Forgery attacks is to use the “Synchronizer Token Pattern” as described here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet When using the Synchronizer Token Pattern, you include a hidden input field which contains a random token whenever you display an HTML form. When the user opens the form, you add a cookie to the user’s browser with the same random token. When the user posts the form, you verify that the hidden form token and the cookie token match. Preventing Cross-Site Request Forgery Attacks with ASP.NET MVC ASP.NET gives you a helper and an action filter which you can use to thwart Cross-Site Request Forgery attacks. For example, the following razor form for creating a product shows how you use the @Html.AntiForgeryToken() helper: @model MvcApplication2.Models.Product <h2>Create Product</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken(); <div> @Html.LabelFor( p => p.Name, "Product Name:") @Html.TextBoxFor( p => p.Name) </div> <div> @Html.LabelFor( p => p.Price, "Product Price:") @Html.TextBoxFor( p => p.Price) </div> <input type="submit" /> } The @Html.AntiForgeryToken() helper generates a random token and assigns a serialized version of the same random token to both a cookie and a hidden form field. (Actually, if you dive into the source code, the AntiForgeryToken() does something a little more complex because it takes advantage of a user’s identity when generating the token). Here’s what the hidden form field looks like: <input name=”__RequestVerificationToken” type=”hidden” value=”NqqZGAmlDHh6fPTNR_mti3nYGUDgpIkCiJHnEEL59S7FNToyyeSo7v4AfzF2i67Cv0qTB1TgmZcqiVtgdkW2NnXgEcBc-iBts0x6WAIShtM1″ /> And here’s what the cookie looks like using the Google Chrome developer toolbar: You use the [ValidateAntiForgeryToken] action filter on the controller action which is the recipient of the form post to validate that the token in the hidden form field matches the token in the cookie. If the tokens don’t match then validation fails and you can’t post the form: public ActionResult Create() { return View(); } [ValidateAntiForgeryToken] [HttpPost] public ActionResult Create(Product productToCreate) { if (ModelState.IsValid) { // save product to db return RedirectToAction("Index"); } return View(); } How does this all work? Let’s imagine that a hacker has copied the Create Product page from MajorBank.com to Hackers.com – the hacker grabs the HTML source and places it at Hackers.com. Now, imagine that the hacker trick you into submitting the Create Product form from Hackers.com to MajorBank.com. You’ll get the following exception: The Cross-Site Request Forgery attack is blocked because the anti-forgery token included in the Create Product form at Hackers.com won’t match the anti-forgery token stored in the cookie in your browser. The tokens were generated at different times for different users so the attack fails. Preventing Cross-Site Request Forgery Attacks with a Single Page App In a Single Page App, you can’t prevent Cross-Site Request Forgery attacks using the same method as a server-side ASP.NET MVC app. In a Single Page App, HTML forms are not generated on the server. Instead, in a Single Page App, forms are loaded dynamically in the browser. Phil Haack has a blog post on this topic where he discusses passing the anti-forgery token in an Ajax header instead of a hidden form field. He also describes how you can create a custom anti-forgery token attribute to compare the token in the Ajax header and the token in the cookie. See: http://haacked.com/archive/2011/10/10/preventing-csrf-with-ajax.aspx Also, take a look at Johan’s update to Phil Haack’s original post: http://johan.driessen.se/posts/Updated-Anti-XSRF-Validation-for-ASP.NET-MVC-4-RC (Other server frameworks such as Rails and Django do something similar. For example, Rails uses an X-CSRF-Token to prevent CSRF attacks which you generate on the server – see http://excid3.com/blog/rails-tip-2-include-csrf-token-with-every-ajax-request/#.UTFtgDDkvL8 ). For example, if you are creating a Durandal app, then you can use the following razor view for your one and only server-side page: @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> @Html.AntiForgeryToken() <div id="applicationHost"> Loading app.... </div> @Scripts.Render("~/scripts/vendor") <script type="text/javascript" src="~/App/durandal/amd/require.js" data-main="/App/main"></script> </body> </html> Notice that this page includes a call to @Html.AntiForgeryToken() to generate the anti-forgery token. Then, whenever you make an Ajax request in the Durandal app, you can retrieve the anti-forgery token from the razor view and pass the token as a header: var csrfToken = $("input[name='__RequestVerificationToken']").val(); $.ajax({ headers: { __RequestVerificationToken: csrfToken }, type: "POST", dataType: "json", contentType: 'application/json; charset=utf-8', url: "/api/products", data: JSON.stringify({ name: "Milk", price: 2.33 }), statusCode: { 200: function () { alert("Success!"); } } }); Use the following code to create an action filter which you can use to match the header and cookie tokens: using System.Linq; using System.Net.Http; using System.Web.Helpers; using System.Web.Http.Controllers; namespace MvcApplication2.Infrastructure { public class ValidateAjaxAntiForgeryToken : System.Web.Http.AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext actionContext) { var headerToken = actionContext .Request .Headers .GetValues("__RequestVerificationToken") .FirstOrDefault(); ; var cookieToken = actionContext .Request .Headers .GetCookies() .Select(c => c[AntiForgeryConfig.CookieName]) .FirstOrDefault(); // check for missing cookie or header if (cookieToken == null || headerToken == null) { return false; } // ensure that the cookie matches the header try { AntiForgery.Validate(cookieToken.Value, headerToken); } catch { return false; } return base.IsAuthorized(actionContext); } } } Notice that the action filter derives from the base AuthorizeAttribute. The ValidateAjaxAntiForgeryToken only works when the user is authenticated and it will not work for anonymous requests. Add the action filter to your ASP.NET Web API controller actions like this: [ValidateAjaxAntiForgeryToken] public HttpResponseMessage PostProduct(Product productToCreate) { // add product to db return Request.CreateResponse(HttpStatusCode.OK); } After you complete these steps, it won’t be possible for a hacker to pretend to be you at Hackers.com and submit a form to MajorBank.com. The header token used in the Ajax request won’t travel to Hackers.com. This approach works, but I am not entirely happy with it. The one thing that I don’t like about this approach is that it creates a hard dependency on using razor. Your single page in your Single Page App must be generated from a server-side razor view. A better solution would be to generate the anti-forgery token in JavaScript. Unfortunately, until all browsers support a way to generate cryptographically strong random numbers – for example, by supporting the window.crypto.getRandomValues() method — there is no good way to generate anti-forgery tokens in JavaScript. So, at least right now, the best solution for generating the tokens is the server-side solution with the (regrettable) dependency on razor. Conclusion The goal of this blog entry was to explore some ways in which you need to handle security differently in the case of a Single Page App than in the case of a traditional server app. In particular, I focused on how to prevent Cross-Site Scripting and Cross-Site Request Forgery attacks in the case of a Single Page App. I want to emphasize that I am not suggesting that Single Page Apps are inherently less secure than server-side apps. Whatever type of web application you build – regardless of whether it is a Single Page App, an ASP.NET MVC app, an ASP.NET Web Forms app, or a Rails app – you must constantly guard against security vulnerabilities.

    Read the article

  • weighted RNG speed problem in C++

    - by supert
    I have a (fast) bit of C++ code that samples cards from a 52 card deck: void sample_allcards(int table[5], int holes[], int players) { int temp[5 + 2 * players]; bool try_again; int c, n, i; for (i = 0; i < 5 + 2 * players; i++) { try_again = true; while (try_again == true) { try_again = false; c = fast_rand52(); // reject collisions for (n = 0; n < i + 1; n++) { try_again = (temp[n] == c) || try_again; } temp[i] = c; } } copy_cards(table, temp, 5); copy_cards(holes, temp + 5, 2 * players); } I am implementing code to sample the hole cards according to a known distribution (stored as a 2d table). My code for this looks like: void sample_allcards_weighted(double weights[][HOLE_CARDS], int table[5], int holes[], int players) { // weights are distribution over hole cards int temp[5 + 2 * players]; int n, i; // table cards for (i = 0; i < 5; i++) { bool try_again = true; while (try_again == true) { try_again = false; int c = fast_rand52(); // reject collisions for (n = 0; n < i + 1; n++) { try_again = (temp[n] == c) || try_again; } temp[i] = c; } } for (int player = 0; player < players; player++) { // hole cards according to distribution i = 5 + 2 * player; bool try_again = true; while (try_again == true) { try_again = false; // weighted-sample c1 and c2 at once double w[1326]; memcpy(w, weights[player], sizeof(w)); // h is a number < 1325 int h = weighted_randi(w, HOLE_CARDS); // i2h uses h and sets temp[i] to the 2 cards implied by h i2h(&temp[i], h); // reject collisions for (n = 0; n < i; n++) { try_again = (temp[n] == temp[i]) || (temp[n] == temp[i+1]) || try_again; } } } copy_cards(table, temp, 5); copy_cards(holes, temp + 5, 2 * players); } My problem? The weighted sampling algorithm is a factor of 10 slower. Speed is very important for my application. Is there a way to improve the speed of my algorithm to something more reasonable? Am I doing something wrong in my implementation? Thanks.

    Read the article

  • What could be causing this long waiting time on page load?

    - by Andrew Findlay
    What could be causing a 1.18s wait time when my page loads? Just to make sure I did not have any conflicting or parallel scripts loading, I completely deleted all the script on my home page and ran the speed test again. Although I had a blank website and 5kb file size, there was still a 900ms "waiting" time. I'm wondering if it could be my server? Any other thoughts or suggestions as it doesn't seem to be scripts. EDIT - Just ran a DNS test on pingdom and here are my results. Does this tell me anything? No nameservers found at child?

    Read the article

  • Speed up the loop operation in R

    - by Kay
    Hi, i have a big performance problem in R. I wrote a function that iterates over an data.frame object. It simply adds a new col to a data.frame and accumulate sth. (simple operation). The data.frame has round about 850.000 rows. My PC is still working about 10h now and i have no idea about the runtime. dayloop2 <- function(temp){ for (i in 1:nrow(temp)){ temp[i,10] <- i if (i > 1) { if ((temp[i,6] == temp[i-1,6]) & (temp[i,3] == temp[i-1,3])) { temp[i,10] <- temp[i,9] + temp[i-1,10] } else { temp[i,10] <- temp[i,9] } } else { temp[i,10] <- temp[i,9] } } names(temp)[names(temp) == "V10"] <- "Kumm." return(temp) } Any ideas how to speed up this operation ?

    Read the article

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