Daily Archives

Articles indexed Sunday November 4 2012

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

  • client-side vs server-side

    - by amalafrida
    In general, should one design in order to place processing load on client-side? More specifically, a search engine to locate subscriber information requires a fair amount of parsing (multiple phone numbers to sort and format, hour of day, timezone, comparisons for possible substitutions of user information, etc.). Again, in general, is it preferred that one have client-side do the work? It seems to me 'yes' in a situation in which one will have many thousands of hits per minute. Use php for quick database queries ... process retrieved data client-side. yes ... no?

    Read the article

  • Won't connect to the database

    - by user1657958
    I'm confused...I'm using the same code in a different document and in there it's not a problem to get a connection to the database. But in the new document it's just not working...(password, username, database name...all is checked and correct) :-/ <?php define ("DB_HOST", "db1234567.db.hello.com"); // set database host define ("DB_USER", "db1234567"); // set database user define ("DB_PASS","password123"); // set database password define ("DB_NAME","db1234567"); // set database name $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection."); $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database"); ?> In the browser I get this: "Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'db1234567'@'123.123.12.12 (using password: YES) in /homepages/12/1234567/test/test.php on line 8 Couldn't make connection." Would be cool if someone could help me :) I'm not seeing any error... Thx!

    Read the article

  • print a linear linked list into a table

    - by user1796970
    I am attempting to print some values i have stored into a LLL into a readable table. The data i have stored is the following : DEBBIE STARR F 3 W 1000.00 JOAN JACOBUS F 9 W 925.00 DAVID RENN M 3 H 4.75 ALBERT CAHANA M 3 H 18.75 DOUGLAS SHEER M 5 W 250.00 SHARI BUCHMAN F 9 W 325.00 SARA JONES F 1 H 7.50 RICKY MOFSEN M 6 H 12.50 JEAN BRENNAN F 6 H 5.40 JAMIE MICHAELS F 8 W 150.00 i have stored each firstname, lastname, gender, tenure, payrate, and salary into their own List. And would like to be able to print them out in the same format that they are viewed on the text file i read them in from. i have messed around with a few methods that allow me to traverse and print the Lists, but i end up with ugly output. . . here is my code for the storage of the text file and the format i would like to print out: public class Payroll { private LineWriter lw; private ObjectList output; ListNode input; private ObjectList firstname, lastname, gender, tenure, rate, salary; public Payroll(LineWriter lw) { this.lw = lw; this.firstname = new ObjectList(); this.lastname = new ObjectList(); this.gender = new ObjectList(); this.tenure = new ObjectList(); this.rate = new ObjectList(); this.salary = new ObjectList(); this.output = new ObjectList(); this.input = new ListNode(); } public void readfile() { File file = new File("payfile.txt"); try{ Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s+"); while(lineScanner.hasNext()) { firstname.insert1(lineScanner.next()); lastname.insert1(lineScanner.next()); gender.insert1(lineScanner.next()); tenure.insert1(lineScanner.next()); rate.insert1(lineScanner.next()); salary.insert1(lineScanner.next()); } } }catch(FileNotFoundException e) {e.printStackTrace();} } public void printer(LineWriter lw) { String msg = " FirstName " + " LastName " + " Gender " + " Tenure " + " Pay Rate " + " Salary "; output.insert1(msg); System.out.println(output.getFirst()); System.out.println(" " + firstname.getFirst() + " " + lastname.getFirst() + "\t" + gender.getFirst() + "\t" + tenure.getFirst() + "\t" + rate.getFirst() + "\t" + salary.getFirst()); } }

    Read the article

  • Make array from $_POST values

    - by cbarg
    Let's start telling that I'm passing an x amount of variables via post from a form. Let's name them menu_category_1, menu_category_2, ..., menu_category_x, plus, maybe, menu_category_new (I'm using an if empty to check this last one variable). To make things easier I'm also sending the parameter $key (amount of variables starting from 0). Now I need to set them into a new variable $menu_category (array), which is going to be imploded and then update my database. How do I set up that new $menu_category variable to be an array containing all my variables named in the beginning? I was thinking of using a for loop but I can't come up with something useful. Thanks!!!

    Read the article

  • find if list 1 is a sequence of list 2 in haskell

    - by Isaak Wahb
    im trying to check if a given list is a subsequence of another list: here are example of lists which gives true: subseq "" "w" subseq "w" "w" subseq "ab" "cab" subseq "cb" "cab" subseq "aa" "xaxa" not (subseq "aa" "xax") not (subseq "ab" "ba") i just come to this but in some cases it gives a wrong result subseq :: Eq a => [a] -> [a] -> Bool subseq [] [] = True subseq [] ys = True subseq xs [] = False subseq (x:xs) (y:ys) = x == y || subseq xs ( 1 `drop` ys )

    Read the article

  • Need help to solve sharedPreference probem

    - by HFherasen
    I am working on this app where I have one EditText field where you can write somthing and then it get saved and added to a list(TextView). I save the content of the EditText in this way : saved += "*" + editTextFelt.getText().toString() + ". \n"; saved is a String. Everything works fine, I can even reload the app and it's still displayed in the TextView, but if i try to write somthing and save it everything that was there, now dissapear. anyone know why ? It's kind of confusing, and I have to get it to work! Thank's!! CODE: init Mehtod() sp = getSharedPreferences(fileName, 0); betaView = (TextView)findViewById(R.id.betaTextView); Ive got a button to send the text, and this is like: p ublic void onClick(View v) { switch(v.getId()){ case R.id.btnSend: saved += "*" + editTextFelt.getText().toString() + ". \n"; SharedPreferences.Editor editor = sp.edit(); editor.putString("SAVED", saved); editor.commit(); betaView.setText(sp.getString("SAVED", "Empty"));

    Read the article

  • NullPointerException with Servlet

    - by RonaDona
    I am calling a Servlet using its URL address. This is the URL I am typing http://localhost:7001/ryan/olympics?action=selectCatalog&id=1 This is the Servlet's URL for sure; if I change the address I get page not found This is the code for the Servlet. public class Servlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { private static final long serialVersionUID = 1L; public Servlet() { super(); } public void init(ServletConfig config) throws ServletException { System.out.println("*** initializing controller servlet."); super.init(config); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (action.equals("selectCatalog")) { String categoryId = request.getParameter("id"); ProductModelDAO dao4 = new ProductModelDAOImpl("jpac"); if (categoryId != null && !categoryId.trim().equals("")) { CategoryDAO dao1 = new CategoryDAOImpl("jpac"); try { Category category = dao1.getCategoryName(categoryId); request.setAttribute("category", category); } catch (Exception e) { e.printStackTrace(); } } try { @SuppressWarnings("unchecked") List<Product> products = dao4 .getProductsByCategory(categoryId); request.setAttribute("products", products); } catch (Exception e) { e.printStackTrace(); } url = "SelectCatalog.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(url); requestDispatcher.forward(request, response); I get the NullPointerException pointing to the RequestDispatcher's line. Any help?

    Read the article

  • how can resize the page?

    - by Ryliatron
    im designing a website and i have screen resolution problem. I want to scale my page but i cant do it. Its my website and 21.5 inc mac screen: (its done, no problem) Its my laptop screen 1366 x 768 px resolution; I tryed this on css; body, html {height:100%;} and this on html; <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1"> <link rel="stylesheet" href="css/style.css" type="text/css" media="all" /> Doctype is: XHTML 1.0 Transitional but doesnt work. How can i do it? Thanks!

    Read the article

  • Javascript Replace Child/Loop issue

    - by Charles John Thompson III
    I have this really bizarre issue where I have a forloop that is supposed to replace all divs with the class of "original" to text inputs with a class of "new". When I run the loop, it only replaces every-other div with an input, but if I run the loop to just replace the class of the div and not change the tag to input, it does every single div, and doesn't only do every-other. Here is my loop code, and a link to the live version: live version here function divChange() { var divs = document.getElementsByTagName("div"); for (var i=0; i<divs.length; i++) { if (divs[i].className == 'original') { var textInput = document.createElement('input'); textInput.className = 'new'; textInput.type = 'text'; textInput.value = divs[i].innerHTML; var parent = divs[i].parentNode; parent.replaceChild(textInput, divs[i]); } } }

    Read the article

  • Ajax return string links not working

    - by Andreas Lympouras
    I have this ajax function: function getSearchResults(e) { var searchString = e.value; /*var x = e.keyCode; var searchString = String.fromCharCode(x);*/ if (searchString == "") { document.getElementById("results").innerHTML = ""; return; } var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("results").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "<%=Page.ResolveUrl("~/template/searchHelper.aspx?searchString=")%>"+searchString, true); xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"); //solve any AJAX caching problem(not refreshing) xmlhttp.send(); } and here is when I call it: <input class="text-input" value="SEARCH" id="searchbox" onkeyup="javascript:getSearchResults(this);" maxlength="50" runat="server" /> and all my links in the searchHelper.aspx file(which retruns them as a string) are like this: <a class="item" href='../src/actors.aspx?id=77&name=dasdassss&type=a' > <span class="item">dasdassss</span></a> When I click this link I want my website to go to ../src/actors.aspx?id=77&name=dasdassss&type=a but nothing happens. When I hover over the link, it also shows me where the link is about to redirect! any help?

    Read the article

  • displaying structs in an array using enumerator

    - by Mostaguen
    In an object I have : public IEnumerable<voiture> recup_voitures() { foreach (voiture v in _arrVCollection) { yield return (v); } } voiture being a struct and _arrVCollection being an array containing some struct voiture. In my main class I have : foreach (CarCollection.voiture o in collection.recup_voitures()) { //some code to display the content of each struct } What is happening is that if I have an array of length 5 and only 1 struct voiture in it, it will do the displaying code 5 times instead of only 1. What am I doing wrong?

    Read the article

  • Generate SVG in Javascript

    - by Shadowbob
    I'm trying to load a SVG with Javascript. I did it quite often with success, but this time it has a strange return. Here is my JS var xmlns = 'http://www.w3.org/2000/svg'; var container = document.getElementById('svgContainer'); var svg = document.createElementNS(xmlns, 'svg'); svg.setAttribute('xmlns', xmlns); svg.setAttribute('version', '1.2'); var defs = document.createElementNS(xmlns, 'defs'); var lg = document.createElementNS(xmlns, 'linearGradient'); lg.setAttribute('id', 'lg'); defs.appendChild(lg); var stop1 = document.createElementNS(xmlns, 'stop'); stop1.setAttribute('offset', '0'); stop1.setAttribute('style', 'stop-color:#ffffff;stop-opacity:1'); lg.appendChild(stop1); var stop2 = document.createElementNS(xmlns, 'stop'); stop2.setAttribute('offset', '1'); stop2.setAttribute('style', 'stop-color:#000000;stop-opacity:1'); lg.appendChild(stop2); var rg = document.createElementNS(xmlns, 'radialGradient'); rg.setAttribute('cx', '171.20810'); rg.setAttribute('cy', '196.85463'); rg.setAttribute('r', '200.00000'); rg.setAttribute('fx', '171.20810'); rg.setAttribute('fy', '196.85463'); rg.setAttribute('id', 'rg'); rg.setAttribute('xlink:href', '#lg'); rg.setAttribute('gradientUnits', 'userSpaceOnUse'); rg.setAttribute('gradientTransform', 'matrix(1.040418,0.796229,-0.814518,1.064316,153.4218,-150.4353)'); defs.appendChild(rg); svg.appendChild(defs); var g = document.createElementNS (xmlns, 'g'); g.setAttribute('transform', 'scale(0.2,0.2)'); svg.appendChild(g); container.appendChild(svg); var path = document.createElementNS (xmlns, 'path'); path.setAttribute('d', 'M 450.00000 255.00000 A 200.00000 205.00000 0 1 1 50.000000,255.00000 A 200.00000 205.00000 0 1 1 450.00000 255.00000 z'); path.setAttribute('style', 'opacity:1.0000000;fill:url(#rg);fill-opacity:1.0000000;fill-rule:evenodd;stroke:none;stroke-width:8.0000000;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1'); g.appendChild(path); So it generates the perfect HTML DOM elements in the proper order, but it doesn't show anything. When I copy the HTML from the source and paste it, it renders the HTML but not the Javascript, but it's the exact same code. You can see the source here. The weird thing is that when I put the radialGradient in the DOM, it works. You can see it in here. So how should I do this? This problem is on all browsers. Thank you for your help.

    Read the article

  • $("body").scrollTop() doesn't update in safari

    - by Kristoffer Nolgren
    I'm working on a website: http://beta.projektopia.se/ the body has several background-images that are updated on scroll like this: $(document).ready(function(){ $(document).scroll(function(){ var scrollfactor=$("body").scrollTop()*0.2; var centerscrollpos =scrollfactor+613; var docheight = $(document).height(); var windowheight = $(window).height(); var bottompos = (docheight-980)-((docheight-windowheight)*0.2)+scrollfactor; var scrollpos = 'center '+scrollfactor+'px,center '+bottompos+'px, center '+ centerscrollpos+'px,center 0px'; $("body").css("background-position", scrollpos); }); }); Lots of calculations, but the important thing is that a scrollpos is created that should change the position of the background when you scroll, to create a parallax-effect. It works great in chrome, but in firefox, the variable scrollfactor, that is suppose to get the current scroll-position, doesn't update. ps, some people have this issue due to lack of correct doctype. I believe i have declared it correctly like this: <!DOCTYPE html>

    Read the article

  • batch: replace a line in a text file

    - by sasamimasas
    I'm trying to replace this line: # forward-socks5 / 127.0.0.1:9050 . with this one: forward-socks5 / 127.0.0.1:9050 . this line belongs to a config file that has to be enabled (UN-commented) by deleting the # sign from the beginning and I could not thought of a better way other than replacing the line with another without the # sign. any other thoughts or ways would be very useful. btw, the spaces before the text are there also.I have pasted the text as it was in the original file. thanks in advance EDIT: I have somehow managed to do the line addition and removing using two peaces of code that I've found. my only problem is that the following code removes every bit of exclamation in the output file! @echo off :Variables SETLOCAL ENABLEDELAYEDEXPANSION set InputFile=config.txt set OutputFile=config-new.txt set _strFind=# forward-socks5 / 127.0.0.1:9050 . set _strInsert= forward-socks5 / 127.0.0.1:9050 . set i=0 :Replace for /f "usebackq tokens=1 delims=[]" %%A in (`find /n "%_strFind%" "%InputFile%"`) do (set _strNum=%%A) for /f "usebackq delims=" %%A in ("%InputFile%") do ( set /a i = !i! + 1 echo %%A>>"%OutputFile%" if [!i!] == [%_strNum%] (echo %_strInsert%>>"%OutputFile%") ) type %OutputFile% | findstr /i /v /c:"%_strFind%">config-new2.txt I was wondering if there is any way to do both the find/delete/add line in one step (not two steps as mine)...

    Read the article

  • How to apply images conditionally using entries and categories?

    - by Sergio Acosta
    Using version 2.5.3 of ExpressionEngine, I have a list of products displayed by category, but I need the premium products among this list being featured with a small star image. How do you call conditionally this little stars besides the {title}? At the moment this code shows stars for all products and that is not ideal. <ol class="voices-list"> {exp:channel:entries channel="product" orderby="title" sort="asc" category="2&6" dynamic="no"} <li><a href="{page_url}">{title}<img class="feature_icon medium" src="{root_url}img/audio/smallstar.png" alt="star"></a></li> {/exp:channel:entries} </ol> I need your help, please.

    Read the article

  • Printing elements of array using ERB

    - by Keva161
    I'm trying to print a simple array defined in my controller into my view with a new line for each element. But what it's doing is printing the whole array on one line. Here's my controller: class TodosController < ApplicationController def index @todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ] end end Here's my view: <%= @todo_array.each do |t| %> <%= puts t %><\br> <% end %> Here's the result: <\br> <\br> <\br> <\br> ["Buy Milk", "Buy Soap", "Pay bill", "Draw Money"]

    Read the article

  • Url mod_rewrite for static chained pages

    - by user1121487
    How can I achieve this with mod_rewrite? from: .com/index.php?menu=home to: .com/home AND from: .com/index.php?menu=home&list=hello to: .com/home/hello ALSO (without the folder hierarki) from: .com/index.php?menu=home&list=hello to: .com/hello I'm using this for the first one: RewriteRule ^([^/\.]+)/?$ index.php?menu=$1 [L] But how to I connect them if there are multiple variables? Tried this: RewriteRule ^([^/]*)/([^/]*)?$ index.php?home=$1&list=$2

    Read the article

  • Android using ksoap calling PHP SOAP webservice fails: 'procedure 'CheckLogin' not found

    - by AmazingDreams
    I'm trying to call a PHP SOAP webservice. I know my webservice functions correctly because I use it in a WPF project succesfully. I'm also building an app in android, using the same webservice. The WSDL file can be found here: http://www.wegotcha.nl/servicehandler/service.wsdl This is my code in the android app: String SOAP_ACTION = "http://www.wegotcha.nl/servicehandler/CheckLogin"; String NAMESPACE = "http://www.wegotcha.nl/servicehandler"; String METHOD_NAME = "CheckLogin"; String URL = "http://www.wegotcha.nl/servicehandler/servicehandler.php"; String resultData = ""; SoapSerializationEnvelope soapEnv = new SoapSerializationEnvelope(SoapEnvelope.VER11); SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapObject UserCredentials = new SoapObject("Types", "UserCredentials6"); UserCredentials.addProperty("mail", params[0]); UserCredentials.addProperty("password", md5(params[1])); request.addSoapObject(UserCredentials); soapEnv.setOutputSoapObject(request); HttpTransportSE http = new HttpTransportSE(URL); http.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); http.debug = true; try { http.call(SOAP_ACTION, soapEnv); } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } SoapObject results = null; results = (SoapObject)soapEnv.bodyOut; if(results != null) resultData = results.getProperty(0).toString(); return resultData; Using fiddler I got the following: Android request: <?xml version="1.0" encoding="utf-8"?> <v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"><v:Header /> <v:Body> <n0:CheckLogin id="o0" c:root="1" xmlns:n0="http://www.wegotcha.nl/servicehandler"> <n1:UserCredentials6 i:type="n1:UserCredentials6" xmlns:n1="Types"> <mail i:type="d:string">myemail</mail> <password i:type="d:string">myhashedpass</password> </n1:UserCredentials6> </n0:CheckLogin> </v:Body> </v:Envelope> Getting the following response: Procedure 'CheckLogin' not present My request produced by my WPF app looks completely different: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <UserCredentials6 xmlns="Types"> <mail>mymail</mail> <password>mypassword</password> </UserCredentials6> </s:Body> </s:Envelope> After googling my ass off I was not able to solve this problem by myself. It may be possible there are some weird things in my Java code because I changed a lot since. I hope you guys will be able to help me, thanks. EDIT: My webservice is of document/literal encoding style, after doing some research I found I should be able to use SoepEnvelope Instead of SoapSerializationEnvelope Though when I replace this I get an error before the try cache block, causing my app to crash. Error: 11-04 16:23:26.786: E/AndroidRuntime(26447): Caused by: java.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be cast to org.kxml2.kdom.Node Which is caused by these lines: request.addSoapObject(UserCredentials); soapEnv.setOutputSoapObject(request); This may be a solution though, how do I go about this? I found nothing about using a SoapEnvelope instead of a SoapSerializationEnvelope except for this awesome tutorial: http://ksoap.objectweb.org/project/mailingLists/ksoap/msg00849.html

    Read the article

  • tsql replace value on select

    - by Zelter Ady
    I have a column (SERVICE_ID) in my table where I can have only 3 values: 0, 1 and 2. I'd like on select, on displayed result table, to change those value with some english words. select client, SERVICE_ID from customers displays now: -------------------------- | John | 1 | Mike | 0 | Jordan | 1 | Oren | 2 -------------------------- I'd like to change the query to get: -------------------------- | John | QA | Mike | development | Jordan | QA | Oren | management -------------------------- There is any way to do this using only the select?

    Read the article

  • How to use the watchdog timer in a RTOS?

    - by user946230
    Assume I have a cooperative scheduler in an embedded environment. I have many processes running. I want to utilize the watchdog timer so that I can detect when a process has stopped behaving for any reason and reset the processor. In simpler applications with no RTOS I would always touch the watchdog from the main loop and this was always adequate. However, here, there are many processes that could potentially hang. What is a clean method to touch the watchdog timer periodically while ensuring that each process is in good health? I was thinking that I could provide a callback function to each process so that it could let another function, which oversees all, know it is still alive. The callback would pass a parameter which would be the tasks unique id so the overseer could determine who was calling back.

    Read the article

  • MongoDB query against geospatial index with maxDistance fails from node.js client

    - by user1735497
    I want to query against a geospatial index in mongo-db (designed after this tutorial http://www.mongodb.org/display/DOCS/Geospatial+Indexing). So when I execute this from the shell everything works fine: db.sellingpoints.find(( { location : { $near: [48.190120, 16.270895], $maxDistance: 7 / 111.2 } } ); but the same query from my nodejs application (using mongoskin or mongoose), won't return any results until i set the distance-value to a very high number (5690) db.collection('sellingpoints') .find({ location: { $near: [lat,lng], $maxDistance: distance / 111.2} }) .limit(limit) .toArray(callback); Has someone any idea how to fix that?

    Read the article

  • LLBLGen Pro and JSON serialization

    - by FransBouma
    I accidentally removed a reply from my previous blogpost, and as this blog-engine here at weblogs.asp.net is apparently falling apart, I can't re-add it as it thought it would be wise to disable comment controls on all posts, except new ones. So I'll post the reply here as a quote and reply on it. 'Steven' asks: What would the future be for LLBLGen Pro to support JSON for serialization? Would it be worth the effort for a LLBLGenPro user to bother creating some code templates to produce additional JSON serializable classes? Or just create some basic POCO classes which could be used for exchange of client/server data and use DTO to map these back to LLBGenPro ones? If I understand the work around, it is at the expense of losing xml serialization. Well, as described in the previous post, to enable JSON serialization, you can do that with a couple of lines and some attribute assignments. However, indeed, the attributes might make the XML serialization not working, as described in the previous blogpost. This is the case if the service you're using serializes objects using the DataContract serializer: this serializer will give up to serialize the entity objects to XML as the entity objects implement IXmlSerializable and this is a no-go area for the DataContract serializer. However, if your service doesn't use a DataContract serializer, or you serialize the objects manually to Xml using an xml serializer, you're fine. When you want to switch to Xml serializing again, instead of JSON in WebApi, and you have decorated the entity classes with the data-contract attributes, you can switch off the DataContract serializer, by setting a global configuration setting: var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true; This will make the WebApi use the XmlSerializer, and run the normal IXmlSerializable interface implementation.

    Read the article

  • Understanding C# async / await (1) Compilation

    - by Dixin
    Now the async / await keywords are in C#. Just like the async and ! in F#, this new C# feature provides great convenience. There are many nice documents talking about how to use async / await in specific scenarios, like using async methods in ASP.NET 4.5 and in ASP.NET MVC 4, etc. In this article we will look at the real code working behind the syntax sugar. According to MSDN: The async modifier indicates that the method, lambda expression, or anonymous method that it modifies is asynchronous. Since lambda expression / anonymous method will be compiled to normal method, we will focus on normal async method. Preparation First of all, Some helper methods need to make up. internal class HelperMethods { internal static int Method(int arg0, int arg1) { // Do some IO. WebClient client = new WebClient(); Enumerable.Repeat("http://weblogs.asp.net/dixin", 10) .Select(client.DownloadString).ToArray(); int result = arg0 + arg1; return result; } internal static Task<int> MethodTask(int arg0, int arg1) { Task<int> task = new Task<int>(() => Method(arg0, arg1)); task.Start(); // Hot task (started task) should always be returned. return task; } internal static void Before() { } internal static void Continuation1(int arg) { } internal static void Continuation2(int arg) { } } Here Method() is a long running method doing some IO. Then MethodTask() wraps it into a Task and return that Task. Nothing special here. Await something in async method Since MethodTask() returns Task, let’s try to await it: internal class AsyncMethods { internal static async Task<int> MethodAsync(int arg0, int arg1) { int result = await HelperMethods.MethodTask(arg0, arg1); return result; } } Because we used await in the method, async must be put on the method. Now we get the first async method. According to the naming convenience, it is called MethodAsync. Of course a async method can be awaited. So we have a CallMethodAsync() to call MethodAsync(): internal class AsyncMethods { internal static async Task<int> CallMethodAsync(int arg0, int arg1) { int result = await MethodAsync(arg0, arg1); return result; } } After compilation, MethodAsync() and CallMethodAsync() becomes the same logic. This is the code of MethodAsyc(): internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MethodAsync(int arg0, int arg1) { MethodAsyncStateMachine methodAsyncStateMachine = new MethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; methodAsyncStateMachine.Builder.Start(ref methodAsyncStateMachine); return methodAsyncStateMachine.Builder.Task; } } It just creates and starts a state machine MethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Result; private TaskAwaiter<int> awaitor; void IAsyncStateMachine.MoveNext() { try { if (this.State != 0) { this.awaitor = HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaitor.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaitor, ref this); return; } } else { this.State = -1; } this.Result = this.awaitor.GetResult(); } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); return; } this.State = -2; this.Builder.SetResult(this.Result); } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0) { this.Builder.SetStateMachine(param0); } } The generated code has been cleaned up so it is readable and can be compiled. Several things can be observed here: The async modifier is gone, which shows, unlike other modifiers (e.g. static), there is no such IL/CLR level “async” stuff. It becomes a AsyncStateMachineAttribute. This is similar to the compilation of extension method. The generated state machine is very similar to the state machine of C# yield syntax sugar. The local variables (arg0, arg1, result) are compiled to fields of the state machine. The real code (await HelperMethods.MethodTask(arg0, arg1)) is compiled into MoveNext(): HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter(). CallMethodAsync() will create and start its own state machine CallMethodAsyncStateMachine: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(CallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> CallMethodAsync(int arg0, int arg1) { CallMethodAsyncStateMachine callMethodAsyncStateMachine = new CallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; callMethodAsyncStateMachine.Builder.Start(ref callMethodAsyncStateMachine); return callMethodAsyncStateMachine.Builder.Task; } } CallMethodAsyncStateMachine has the same logic as MethodAsyncStateMachine above. The detail of the state machine will be discussed soon. Now it is clear that: async /await is a C# level syntax sugar. There is no difference to await a async method or a normal method. A method returning Task will be awaitable. State machine and continuation To demonstrate more details in the state machine, a more complex method is created: internal class AsyncMethods { internal static async Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; } } In this method: There are multiple awaits. There are code before the awaits, and continuation code after each await After compilation, this multi-await method becomes the same as above single-await methods: internal class CompiledAsyncMethods { [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, Builder = AsyncTaskMethodBuilder<int>.Create(), State = -1 }; multiCallMethodAsyncStateMachine.Builder.Start(ref multiCallMethodAsyncStateMachine); return multiCallMethodAsyncStateMachine.Builder.Task; } } It creates and starts one single state machine, MultiCallMethodAsyncStateMachine: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { public int State; public AsyncTaskMethodBuilder<int> Builder; public int Arg0; public int Arg1; public int Arg2; public int Arg3; public int ResultOfAwait1; public int ResultOfAwait2; public int ResultToReturn; private TaskAwaiter<int> awaiter; void IAsyncStateMachine.MoveNext() { try { switch (this.State) { case -1: HelperMethods.Before(); this.awaiter = AsyncMethods.MethodAsync(this.Arg0, this.Arg1).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 0; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 0: this.ResultOfAwait1 = this.awaiter.GetResult(); HelperMethods.Continuation1(this.ResultOfAwait1); this.awaiter = AsyncMethods.MethodAsync(this.Arg2, this.Arg3).GetAwaiter(); if (!this.awaiter.IsCompleted) { this.State = 1; this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this); } break; case 1: this.ResultOfAwait2 = this.awaiter.GetResult(); HelperMethods.Continuation2(this.ResultOfAwait2); this.ResultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; this.State = -2; this.Builder.SetResult(this.ResultToReturn); break; } } catch (Exception exception) { this.State = -2; this.Builder.SetException(exception); } } [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { this.Builder.SetStateMachine(stateMachine); } } The above code is already cleaned up, but there are still a lot of things. More clean up can be done, and the state machine can be very simple: [CompilerGenerated] [StructLayout(LayoutKind.Auto)] internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine { // State: // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End public int State; public TaskCompletionSource<int> ResultToReturn; // int resultToReturn ... public int Arg0; // int Arg0 public int Arg1; // int arg1 public int Arg2; // int arg2 public int Arg3; // int arg3 public int ResultOfAwait1; // int resultOfAwait1 ... public int ResultOfAwait2; // int resultOfAwait2 ... private Task<int> currentTaskToAwait; /// <summary> /// Moves the state machine to its next state. /// </summary> void IAsyncStateMachine.MoveNext() { try { switch (this.State) { // Orginal code is splitted by "case"s: // case -1: // HelperMethods.Before(); // MethodAsync(Arg0, arg1); // case 0: // int resultOfAwait1 = await ... // HelperMethods.Continuation1(resultOfAwait1); // MethodAsync(arg2, arg3); // case 1: // int resultOfAwait2 = await ... // HelperMethods.Continuation2(resultOfAwait2); // int resultToReturn = resultOfAwait1 + resultOfAwait2; // return resultToReturn; case -1: // -1 is begin. HelperMethods.Before(); // Code before 1st await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg0, this.Arg1); // 1st task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 0. this.State = 0; IAsyncStateMachine this1 = this; // Cannot use "this" in lambda so create a local variable. this.currentTaskToAwait.ContinueWith(_ => this1.MoveNext()); // Callback break; case 0: // Now 1st await is done. this.ResultOfAwait1 = this.currentTaskToAwait.Result; // Get 1st await's result. HelperMethods.Continuation1(this.ResultOfAwait1); // Code after 1st await and before 2nd await. this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg2, this.Arg3); // 2nd task to await // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 1. this.State = 1; IAsyncStateMachine this2 = this; // Cannot use "this" in lambda so create a local variable. this.currentTaskToAwait.ContinueWith(_ => this2.MoveNext()); // Callback break; case 1: // Now 2nd await is done. this.ResultOfAwait2 = this.currentTaskToAwait.Result; // Get 2nd await's result. HelperMethods.Continuation2(this.ResultOfAwait2); // Code after 2nd await. int resultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; // Code after 2nd await. // End with resultToReturn. this.State = -2; // -2 is end. this.ResultToReturn.SetResult(resultToReturn); break; } } catch (Exception exception) { // End with exception. this.State = -2; // -2 is end. this.ResultToReturn.SetException(exception); } } /// <summary> /// Configures the state machine with a heap-allocated replica. /// </summary> /// <param name="stateMachine">The heap-allocated replica.</param> [DebuggerHidden] void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { // No core logic. } } Only Task and TaskCompletionSource are involved in this version. And MultiCallMethodAsync() can be simplified to: [DebuggerStepThrough] [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async internal static /*async*/ Task<int> MultiCallMethodAsync_(int arg0, int arg1, int arg2, int arg3) { MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine() { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, ResultToReturn = new TaskCompletionSource<int>(), // -1: Begin // 0: 1st await is done // 1: 2nd await is done // ... // -2: End State = -1 }; (multiCallMethodAsyncStateMachine as IAsyncStateMachine).MoveNext(); // Original code are in this method. return multiCallMethodAsyncStateMachine.ResultToReturn.Task; } Now the whole state machine becomes very clear - it is about callback: Original code are split into pieces by “await”s, and each piece is put into each “case” in the state machine. Here the 2 awaits split the code into 3 pieces, so there are 3 “case”s. The “piece”s are chained by callback, that is done by Builder.AwaitUnsafeOnCompleted(callback), or currentTaskToAwait.ContinueWith(callback) in the simplified code. A previous “piece” will end with a Task (which is to be awaited), when the task is done, it will callback the next “piece”. The state machine’s state works with the “case”s to ensure the code “piece”s executes one after another. Callback Since it is about callback, the simplification  can go even further – the entire state machine can be completely purged. Now MultiCallMethodAsync() becomes: internal static Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3) { TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(); try { // Oringinal code begins. HelperMethods.Before(); MethodAsync(arg0, arg1).ContinueWith(await1 => { int resultOfAwait1 = await1.Result; HelperMethods.Continuation1(resultOfAwait1); MethodAsync(arg2, arg3).ContinueWith(await2 => { int resultOfAwait2 = await2.Result; HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; // Oringinal code ends. taskCompletionSource.SetResult(resultToReturn); }); }); } catch (Exception exception) { taskCompletionSource.SetException(exception); } return taskCompletionSource.Task; } Please compare with the original async / await code: HelperMethods.Before(); int resultOfAwait1 = await MethodAsync(arg0, arg1); HelperMethods.Continuation1(resultOfAwait1); int resultOfAwait2 = await MethodAsync(arg2, arg3); HelperMethods.Continuation2(resultOfAwait2); int resultToReturn = resultOfAwait1 + resultOfAwait2; return resultToReturn; Yeah that is the magic of C# async / await: Await is literally pretending to wait. In a await expression, a Task object will be return immediately so that caller is not blocked. The continuation code is compiled as that Task’s callback code. When that task is done, continuation code will execute. Please notice that many details inside the state machine are omitted for simplicity, like context caring, etc. If you want to have a detailed picture, please do check out the source code of AsyncTaskMethodBuilder and TaskAwaiter.

    Read the article

  • Windows Server 2003 (w/Exchange) move to new machine

    - by James Booker
    I have an ageing domain controller (the only one on a 10-pc network) which needs rebooting often. I have a Dell Poweredge 2850 server doing nothing, so I'd like to move the DC to that, but here's the catch - I don't have Win2k Server Std install media any more as it's been lost. I purchased "Easus Todo Backup Advanced Server" which claims to be able to recover to dissimilar metal, but it's not quite working (although I don't think it's the product's fault) I know the server and PERC RAID card are good because I installed Ubuntu on the logical drive (4 x 72GB disks RAID 5) no problems. I've booted frmo the Easus Todo backup CD (which is WinPE based) and recovered to the logical disk on the RAID (after installing driver inside the WinPE environment from a NAS drive) The problem is when I boot the server, I can get the OS selection menu, but any option results in a blank screen, with no errors. I figure this is probably because the driver wasn't installed on the old machine (which is IDE-based (i know, i know!) and doesn;t have a RAID controller) I've booted from the CD and copied the mraid35x.sys file to the c:\windows\system32\drivers folder on the recovered system, but it makes no difference. I made a boot.ini with rdisks 0-10 defined, and booting from each of these resulted in a file error (i.e. 'this isn't a real disk') - the only disk that gets any response (the blank screen) is multi(0)disk(0)rdisk(0)partition(1) which just gives me the blank black screen and no disk activity. Is there any way I can force the drvier to be installed on the source system (so i can do a full backup again), i've tried right-clicking the oemsetup.inf and clicking install, but it didn't actually do anything. I attempted to force it with the 'Add new hardware' wizard and forcing with the 'have disk' option but it still gave me no hardware to select. Also I've got an identical machine running WinXP which uses the PERC driver successfully (which was obviously done at install time) and the boot.ini settings are the same : multi(0)disk(0)rdisk(0)partition(1) Any ideas would be appreciated.

    Read the article

  • Nginx order of servers

    - by scrat
    I have 3 sites on my server. All are running on gunicorn and use unix sockets to communicate with nginx which routes requests. I got three records in nginx.conf like: server { listen 80; server_name site1.com; location / { proxy_pass http://unix:/tmp/site1.sock; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } For site1, site2, site3. If they are ordered as config for site1 goes first, and then goes config for site2 and site3 everything works good. But when I change the order for example to site2, site1, site3, then site1 becomes routed to site2. What am I doing wrong? Full server nginx.conf before servers configs: user www-data; worker_processes 4; pid /var/run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_types text/css application/x-javascript text/x-component text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;

    Read the article

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