Daily Archives

Articles indexed Tuesday September 11 2012

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

  • How Can i click on this element using XPATH in Web driver?

    - by Mike
    Here is the html..... <li> <input type="checkbox" checked="" name="selectedMstrPrivGroupList[9].mstrAuthorities[0].status"/> Add Dexter </li> How will I be able to click on this element. It is a check box. And I want to use XPath as I have close to 30+ checkboxes in the page, so that I can create a generic method and pass only the Webelement.. I tried the following but didn't work. Driver.findElement(By.xpath("//input[contains(.,'Add Dexter')]")).click(); Please help!! Thanks, Mike

    Read the article

  • ASP.net MVC3 howto edit sql database

    - by user1662380
    MovieStoreEntities MovieDb = new MovieStoreEntities(); public ActionResult Edit(int id) { //var EditMovie1 = MovieDb AddMovieModel EditMovie = (from M in MovieDb.Movies from C in MovieDb.Categories where M.CategoryId == C.Id where M.Id == id select new AddMovieModel { Name = M.Name, Director = M.Director, Country = M.Country, categorie = C.CategoryName, Category = M.CategoryId }).FirstOrDefault(); //AddMovieModel EditMovie1 = MovieDb.Movies.Where(m => m.Id == id).Select(m => new AddMovieModel {m.Id }).First(); List<CategoryModel> categories = MovieDb.Categories .Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id }) .ToList(); ViewBag.Category = new SelectList(categories, "Id", "Category"); return View(EditMovie); } // // POST: /Default1/Edit/5 [HttpPost] public ActionResult Edit(AddMovieModel Model2) { List<CategoryModel> categories = MovieDb.Categories .Select(category => new CategoryModel { Category = category.CategoryName, id = category.Id }) .ToList(); ViewBag.Category = new SelectList(categories, "Id", "Category"); if (ModelState.IsValid) { //MovieStoreEntities model = new MovieStoreEntities(); MovieDb.SaveChanges(); return View("Thanks2", Model2); } else return View(); } This is the Code that I have wrote to edit Movie details and update database in the sql server. This dont have any compile errors, But It didnt update sql server database.

    Read the article

  • hibernate not picking sessionFactory

    - by Satya
    My application-context.xml is <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/myDB</value></property> <property name="username"><value>myUser</value></property> <property name="password"><value>myUser</value></property> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="mappingResources"> <property name="dataSource"><ref bean="myDataSource"/></property> <list> <value>com/x/model/config/hibernate/user.hbm.xml</value> </list> </property> <property name="hibernateProperties" > <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect </value> </property> </bean> <bean id="userdao" class="com.x.y.z.UserDao"> <property name="sessionFactory"><ref bean="mySessionFactory"/></property> </bean> </beans> user.hbm.xml is <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.cpt.model"> <class name="User" table="user"> <id name="userId" column="id"> <generator class="native"/> </id> <property name="firstname" column="firstName" /> <property name="lastName" column="lastName"/> <property name="login" column="login"/> <property name="pass" column="pass"/> <property name="superemail" column="superEmail"/> </class> </hibernate-mapping> and the UserDao is package com.x.y.z; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate.support.HibernateDaoSupport; import org.springframework.stereotype.Component; import com.x.model.User; @Component public class UserDao { private SessionFactory sessionFactory; public void addUser(User user) { Session session; try { try { session = getSessionFactory().openSession(); // session = sessionFactory.openSession(); session.save(user); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (HibernateException e) { // TODO Auto-generated catch block System.out.println("printing in the catch"); e.printStackTrace(); } } public SessionFactory getSessionFactory() { System.out.println("returning session factory ::: sessionFactory == null :: "+sessionFactory.openSession()); return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { System.out.println("this is setting session factory" + sessionFactory.getClass()); System.out.println("setting session factory ::: sessionFactory == null :: "+sessionFactory==null); this.sessionFactory = sessionFactory; System.out.println("setting session factory ::: sessionFactory == null :: "+this.sessionFactory.openSession().getClass()); System.out.println(getSessionFactory().openSession().isOpen()); } } However, I keep getting 14:45:09,929 INFO [org.hibernate.impl.SessionFactoryImpl] building session fact ory 14:45:09,933 WARN [net.sf.ehcache.config.Configurator] No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: vfs:/C:/jb /server/default/deploy/C.war/WEB-INF/lib/ehcache-1.1.jar/ehcache-failsafe.xml 14:45:10,007 INFO [org.hibernate.impl.SessionFactoryObjectFactory] Not binding factory to JNDI, no JNDI name configured 14:45:10,008 INFO [org.hibernate.impl.SessionFactoryImpl] Checking 0 named quer ies 14:45:10,017 INFO [STDOUT] this is setting session factoryclass $Proxy178 14:45:10,017 INFO [STDOUT] false 14:45:10,019 INFO [STDOUT] setting session factory ::: sessionFactory == null : : class org.hibernate.impl.SessionImpl 14:45:10,020 INFO [STDOUT] returning session factory ::: sessionFactory == null :: org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQue ue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemova ls=[] collectionUpdates=[]]) It is giving sessionFactory null . Any Idea where am I failing ? Thanks

    Read the article

  • How to select product that have the maximum price of each category?

    - by kimleng
    The below is my table that has the item such as: ProductId ProductName Category Price 1 Tiger Beer $12.00 2 ABC Beer $13.99 3 Anchor Beer $9.00 4 Apolo Wine $10.88 5 Randonal Wine $18.90 6 Wisky Wine $30.19 7 Coca Beverage $2.00 8 Sting Beverage $5.00 9 Spy Beverage $4.00 10 Angkor Beer $12.88 And I suppose that I have only three category in this table (I can have a lot of category in this table). And I want to show the maximum product's price of each category in this table.

    Read the article

  • selector for button not working

    - by user1662334
    I want to change the background of the button when the button is unclickable.I have used selector for that but it is not working in the case when the button remains unclickable. This is the selector file: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false" android:drawable="@drawable/button_lightgrey" /> <item android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/button_blue"/> <item android:state_focused="true" android:drawable="@drawable/button_darkgreen" /> <item android:drawable="@drawable/button_lightgreen" /> </selector> This is the button where i am using this selector file: <Button android:id="@+id/PrevButton" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" android:layout_marginLeft="5.0dip" android:layout_weight="1.0" android:background="@drawable/ibtn" android:onClick="onPrevButtonClick" android:text="Prev" /> Please help me.All other functions are working in the selector file but only the unclickable button case is not working.Thanks

    Read the article

  • Why does Java ArrayList use per-element casting instead of per-array casting?

    - by user1111929
    What happens inside Java's ArrayList<T> (and probably many other classes) is that there is an internal Object[] array = new Object[n];, to which T Objects are written. Whenever an element is read from it, a cast return (T) array[i]; is done. So, a cast on every single read. I wonder why this is done. To me, it seems like they're just doing unnecessary casts. Wouldn't it be more logical and also slightly faster to just create a T[] array = (T[]) new Object[n]; and then just return array[i]; without cast? This is only one cast per array creation, which is usually far less than the number of reads. Why is their method to be preferred? I fail to see why my idea isn't strictly better?

    Read the article

  • iPhone - How to import native calendar events to my iphone app?

    - by sachi
    I am doing one simple application using iPhone calendar, where I need to import the iPhone native calendar events into my iPhone app. How can I do this. I have a piece of code but it doesn't seems to be working. I have added some events into my iPhone native calendar. But when i retrieve it's not fetching anything. Here is the piece of code. -(IBAction)importCalEvents:(id)sender { NSArray *caleandarsArray = [[NSArray alloc] init]; caleandarsArray = [[eventStore calendars] retain]; NSLog(@"Calendars from Array : %@", caleandarsArray); for (EKCalendar *CalendarEK in caleandarsArray) { NSLog(@"Calendar Title : %@", CalendarEK.title); } }

    Read the article

  • Android 4.0.3 OpengL ES 2.0 issue

    - by user1662184
    i develop live wallpapers using Opengl ES 2.0 engine. My wallapapers run smooth on 2.x Android Devices , but in 4.03 i see some strange things. 1st seconds (maybe a minute max) lwp runs smooth , but after that starts dropping frames especially when objects passing near camera allmost crashes. But no error on eclipse Log. I watched Eclipse log from the begining of loading the lwp to the point of dropping frames. I ve seen that on My LG optimus 2X , and my Samsung Galaxy S2. Any Idea what to check , or what is going on?? UPDATE i just noticed that changing render mode from dirty to continuously fixed the problem , but until screen orientation changes , or goes of and on. after that renderer freaks out.

    Read the article

  • Can't figure out the color of an svg element

    - by yass
    I have a very simple HTML page, viewable on gh-pages with the following code: <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link href="style.css" media="screen" rel="stylesheet" type="text/css"> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'> </script> </head> <body> <div id="page"> <div id="content"> <div id="heatmap"> <svg style="margin-left: 80px; color: rgb(255, 255, 255);" width="800" height="880"> <g transform="translate(80,80)"> <rect style="color: rgb(255, 255, 255);" height="720" width="720"> </rect> </g> </svg> </div> </div> </div> </body> </html> with the following CSS: body { background-color: #FFFFFF; font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #FFFFFF; } #wrapper { margin: 0 auto; padding: 0; } #page { width: 1000px; margin: 0 auto; padding: 40px 0px 0px 0px; } #content { float: left; width: 660px; padding: 0px 0px 0px 0px; background: #FFFFFF; } I expect the rectangle, 'svg rect' to be the color #FFFFFF, or white. But it shows up as some other color. I opened it up in firebug, and it shows the computed color to be #FFFFF:

    Read the article

  • JavaFX FXML communication between Application and Controller classes

    - by likethesky
    I am trying to get and destroy an external process I've created via ProcessBuilder in my FXML application close, but it's not working. This is based on the helpful advice Sergey Grinev gave me here. I have tried running with/without the "// myController.setApp(this);" and with "// super.stop();" at top of subclass and at bottom (see commented out/in for that line in MyApp), but no combination works. This probably isn't related to FXML or JavaFX, though I imagine this is a common pattern for developing apps on JavaFX. I suppose I'm asking for a Java best practice for closing dependent processes in a UI-based app like this one (in this case: FXML / JavaFX based), where there is a controller class and an application class. Can you explain what I'm doing wrong? Or better: advise what I should be doing instead? Thanks. In my Application I do this: public class MyApp extends Application { @Override public void start(Stage primaryStage) throws Exception { FXMLLoader fxmlLoader = new FXMLLoader(); Scene scene = (Scene)FXMLLoader.load(getClass().getResource("MyApp.fxml")); MyAppController myController = (MyAppController)fxmlLoader.getController(); primaryStage.setScene(scene); primaryStage.show(); // myController.setApp(this); } @Override public void stop() throws Exception { // super.stop(); // this is called on fx app close, you may call it in an action handler too if (MyAppController.getScriptProcess() != null) { MyAppController.getScriptProcess().destroy(); } super.stop(); } public static void main(String[] args) { launch(args); } } In my Controller I do this: public class MyAppController implements Initializable { private Application app; private static Process scriptProcess; public void setApp(Application a) { app = a; } public static Process getScriptProcess() { return scriptProcess; } } The result when I run with the "commented-out setApp()" not commented out (that is, left in the start method), is the following, immediately upon launch (the main Scene flashes, then disappears, then this dialog appears: "JavaFX Launcher Error: Exception while running Application" And it gives an, "Exception in Application start method" in the console as well. The result when I leave out the "commented-out code" in my MyApp above (that is, remove the "setApp()" from the start method), is that my app does indeed close, but gives this error when it closes: Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1440) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28) at javafx.event.Event.fireEvent(Event.java:171) at javafx.scene.Node.fireEvent(Node.java:6863) at javafx.scene.control.Button.fire(Button.java:179) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193) at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336) at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33) at javafx.event.Event.fireEvent(Event.java:171) at javafx.scene.Scene$MouseHandler.process(Scene.java:3324) at javafx.scene.Scene$MouseHandler.process(Scene.java:3164) at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3119) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1559) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2261) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:228) at com.sun.glass.ui.View.handleMouseEvent(View.java:528) at com.sun.glass.ui.View.notifyMouse(View.java:922) at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method) at com.sun.glass.ui.gtk.GtkApplication$3$1.run(GtkApplication.java:82) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435) ... 44 more Caused by: java.lang.NullPointerException at mypackage.MyController.handleCancel(MyController.java:300) ... 49 more Clean up...

    Read the article

  • Excel VBA - export to UTF-8

    - by Tom
    The macro I created works fine, I just need to sort out the saving business. Now I get a popup asking me where to save it, but I would like it to save it under a default name and path AND encoded in UTF-8. This is my full code I use, the bottom part saves the document I presume. Public Sub ExportToTextFile(FName As String, Sep As String, SelectionOnly As Boolean, AppendData As Boolean) Dim WholeLine As String Dim fnum As Integer Dim RowNdx As Long Dim ColNdx As Integer Dim StartRow As Long Dim EndRow As Long Dim StartCol As Integer Dim EndCol As Integer Dim CellValue As String Dim teller As Integer 'Teller aangemaakt ter controle voor het aantal velden 'teller = 1 Application.ScreenUpdating = False On Error GoTo EndMacro: fnum = FreeFile If SelectionOnly = True Then With Selection StartRow = .Cells(1).Row StartCol = .Cells(26).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With Else With ActiveSheet.UsedRange StartRow = .Cells(1).Row StartCol = .Cells(26).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(26).Column End With End If If AppendData = True Then Open FName For Append Access Write As #fnum Else Open FName For Output Access Write As #fnum End If For RowNdx = StartRow To EndRow WholeLine = "" For ColNdx = StartCol To EndCol If Cells(RowNdx, ColNdx).Value = "" Then CellValue = "" Else CellValue = Cells(RowNdx, ColNdx).Value End If WholeLine = WholeLine & CellValue & Sep Next ColNdx WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep)) Print #fnum, WholeLine, "" 'Print #fnum, teller, WholeLine, "" 'teller = teller + 1 Next RowNdx EndMacro: On Error GoTo 0 Application.ScreenUpdating = True Close #fnum End Sub Sub Dump4Mini() Dim FileName As Variant Dim Sep As String FileName = Application.GetSaveAsFilename(InitialFileName:=Blank, filefilter:="Text (*.txt),*.txt") If FileName = False Then Exit Sub End If Sep = "|" If Sep = vbNullString Then Exit Sub End If Debug.Print "FileName: " & FileName, "Separator: " & Sep ExportToTextFile FName:=CStr(FileName), Sep:=CStr(Sep), SelectionOnly:=False, AppendData:=False End Sub

    Read the article

  • c++ builder TClientWinSocket simbol substitution

    - by Vlad
    I have the following problem. I have to send a text telegram over tcp/ip to a host device. Telegram should be terminated using 0x1A (CTRL-Z) character. But when I send it, host told me that there is a wrong symbol in the telegram. When I terminate a telegram with 32 (0x20) everything is ok. I look the transfered data using WireShark and I see that when I send 0x1A it is substituted with 0x16, when I send 32 (0x20) as a terminator it is somehow substituted with 0x1A. Can you explain it please. P.S. I am working on windows 7, using c++builder xe2. Thanks, Vladimir

    Read the article

  • jQuery UI Autocomplete and CodeIgniter

    - by Kere Puki
    I am trying to implement a simple autocomplete script using jQuery UI and CodeIgniter 2 but my model keeps telling me there is an undefined variable so I dont know if my setup is right. My view $(function() { $("#txtUserSuburb").autocomplete({ source: function(request, response){ $.ajax({ url: "autocomplete/suggestions", data: { term: $("#txtUserSuburb").val() }, dataType: "json", type: "POST", success: function(data){ response(data); } }); }, minLength: 2 }); }); My controller function suggestions(){ $this->load->model('autocomplete_model'); $term = $this->input->post('term', TRUE); $rows = $this->autocomplete_model->getAutocomplete($term); echo json_encode($rows); } My Model function getAutocomplete() { $this->db->like('postcode', $term, 'after'); $query = $this->db->get('tbl_postcode'); $keywords = array(); foreach($query->result() as $row){ array_push($keywords, $row->postcode); } return $keywords; } There arent any errors except it doesn't seem to be passing the $term variable to the model.

    Read the article

  • CPU friendly infinite loop

    - by Adi
    Writing an infinite loop is simple: while(true){ //add whatever break condition here } But this will trash the CPU performance. This execution thread will take as much as possible from CPU's power. What is the best way to lower the impact on CPU? Adding some Thread.Sleep(n) should do the trick, but setting a high timeout value for Sleep() method may indicate an unresponsive application to the operating system. Let's say I need to perform a task each minute or so in a console app. I need to keep Main() running in an "infinite loop" while a timer will fire the event that will do the job. I would like to keep Main() with the lowest impact on CPU. What methods do you suggest. Sleep() can be ok, but as I already mentioned, this might indicate an unresponsive thread to the operating system. LATER EDIT: I want to explain better what I am looking for: I need a console app not Windows service. Console apps can simulate the Windows services on Windows Mobile 6.x systems with Compact Framework. I need a way to keep the app alive as long as the Windows Mobile device is running. We all know that the console app runs as long as its static Main() function runs, so I need a way to prevent Main() function exit. In special situations (like: updating the app), I need to request the app to stop, so I need to infinitely loop and test for some exit condition. For example, this is why Console.ReadLine() is no use for me. There is no exit condition check. Regarding the above, I still want Main() function as resource friendly as possible. Let asside the fingerprint of the function that checks for the exit condition.

    Read the article

  • Passing multiple simple POST Values to ASP.NET Web API

    - by Rick Strahl
    A few weeks backs I posted a blog post  about what does and doesn't work with ASP.NET Web API when it comes to POSTing data to a Web API controller. One of the features that doesn't work out of the box - somewhat unexpectedly -  is the ability to map POST form variables to simple parameters of a Web API method. For example imagine you have this form and you want to post this data to a Web API end point like this via AJAX: <form> Name: <input type="name" name="name" value="Rick" /> Value: <input type="value" name="value" value="12" /> Entered: <input type="entered" name="entered" value="12/01/2011" /> <input type="button" id="btnSend" value="Send" /> </form> <script type="text/javascript"> $("#btnSend").click( function() { $.post("samples/PostMultipleSimpleValues?action=kazam", $("form").serialize(), function (result) { alert(result); }); }); </script> or you might do this more explicitly by creating a simple client map and specifying the POST values directly by hand:$.post("samples/PostMultipleSimpleValues?action=kazam", { name: "Rick", value: 1, entered: "12/01/2012" }, $("form").serialize(), function (result) { alert(result); }); On the wire this generates a simple POST request with Url Encoded values in the content:POST /AspNetWebApi/samples/PostMultipleSimpleValues?action=kazam HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: application/json Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Referer: http://localhost/AspNetWebApi/FormPostTest.html Content-Length: 41 Pragma: no-cache Cache-Control: no-cachename=Rick&value=12&entered=12%2F10%2F2011 Seems simple enough, right? We are basically posting 3 form variables and 1 query string value to the server. Unfortunately Web API can't handle request out of the box. If I create a method like this:[HttpPost] public string PostMultipleSimpleValues(string name, int value, DateTime entered, string action = null) { return string.Format("Name: {0}, Value: {1}, Date: {2}, Action: {3}", name, value, entered, action); }You'll find that you get an HTTP 404 error and { "Message": "No HTTP resource was found that matches the request URI…"} Yes, it's possible to pass multiple POST parameters of course, but Web API expects you to use Model Binding for this - mapping the post parameters to a strongly typed .NET object, not to single parameters. Alternately you can also accept a FormDataCollection parameter on your API method to get a name value collection of all POSTed values. If you're using JSON only, using the dynamic JObject/JValue objects might also work. ModelBinding is fine in many use cases, but can quickly become overkill if you only need to pass a couple of simple parameters to many methods. Especially in applications with many, many AJAX callbacks the 'parameter mapping type' per method signature can lead to serious class pollution in a project very quickly. Simple POST variables are also commonly used in AJAX applications to pass data to the server, even in many complex public APIs. So this is not an uncommon use case, and - maybe more so a behavior that I would have expected Web API to support natively. The question "Why aren't my POST parameters mapping to Web API method parameters" is already a frequent one… So this is something that I think is fairly important, but unfortunately missing in the base Web API installation. Creating a Custom Parameter Binder Luckily Web API is greatly extensible and there's a way to create a custom Parameter Binding to provide this functionality! Although this solution took me a long while to find and then only with the help of some folks Microsoft (thanks Hong Mei!!!), it's not difficult to hook up in your own projects. It requires one small class and a GlobalConfiguration hookup. Web API parameter bindings allow you to intercept processing of individual parameters - they deal with mapping parameters to the signature as well as converting the parameters to the actual values that are returned. Here's the implementation of the SimplePostVariableParameterBinding class:public class SimplePostVariableParameterBinding : HttpParameterBinding { private const string MultipleBodyParameters = "MultipleBodyParameters"; public SimplePostVariableParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor) { } /// <summary> /// Check for simple binding parameters in POST data. Bind POST /// data as well as query string data /// </summary> public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // Body can only be read once, so read and cache it NameValueCollection col = TryReadBody(actionContext.Request); string stringValue = null; if (col != null) stringValue = col[Descriptor.ParameterName]; // try reading query string if we have no POST/PUT match if (stringValue == null) { var query = actionContext.Request.GetQueryNameValuePairs(); if (query != null) { var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower()); if (matches.Count() > 0) stringValue = matches.First().Value; } } object value = StringToType(stringValue); // Set the binding result here SetValue(actionContext, value); // now, we can return a completed task with no result TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>(); tcs.SetResult(default(AsyncVoid)); return tcs.Task; } private object StringToType(string stringValue) { object value = null; if (stringValue == null) value = null; else if (Descriptor.ParameterType == typeof(string)) value = stringValue; else if (Descriptor.ParameterType == typeof(int)) value = int.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int32)) value = Int32.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int64)) value = Int64.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(decimal)) value = decimal.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(double)) value = double.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(DateTime)) value = DateTime.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(bool)) { value = false; if (stringValue == "true" || stringValue == "on" || stringValue == "1") value = true; } else value = stringValue; return value; } /// <summary> /// Read and cache the request body /// </summary> /// <param name="request"></param> /// <returns></returns> private NameValueCollection TryReadBody(HttpRequestMessage request) { object result = null; // try to read out of cache first if (!request.Properties.TryGetValue(MultipleBodyParameters, out result)) { // parsing the string like firstname=Hongmei&lastname=Ge result = request.Content.ReadAsFormDataAsync().Result; request.Properties.Add(MultipleBodyParameters, result); } return result as NameValueCollection; } private struct AsyncVoid { } }   The ExecuteBindingAsync method is fired for each parameter that is mapped and sent for conversion. This custom binding is fired only if the incoming parameter is a simple type (that gets defined later when I hook up the binding), so this binding never fires on complex types or if the first type is not a simple type. For the first parameter of a request the Binding first reads the request body into a NameValueCollection and caches that in the request.Properties collection. The request body can only be read once, so the first parameter request reads it and then caches it. Subsequent parameters then use the cached POST value collection. Once the form collection is available the value of the parameter is read, and the value is translated into the target type requested by the Descriptor. SetValue writes out the value to be mapped. Once you have the ParameterBinding in place, the binding has to be assigned. This is done along with all other Web API configuration tasks at application startup in global.asax's Application_Start:GlobalConfiguration.Configuration.ParameterBindingRules .Insert(0, (HttpParameterDescriptor descriptor) => { var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods; // Only apply this binder on POST and PUT operations if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Put)) { var supportedTypes = new Type[] { typeof(string), typeof(int), typeof(decimal), typeof(double), typeof(bool), typeof(DateTime) }; if (supportedTypes.Where(typ => typ == descriptor.ParameterType).Count() > 0) return new SimplePostVariableParameterBinding(descriptor); } // let the default bindings do their work return null; });   The ParameterBindingRules.Insert method takes a delegate that checks which type of requests it should handle. The logic here checks whether the request is POST or PUT and whether the parameter type is a simple type that is supported. Web API calls this delegate once for each method signature it tries to map and the delegate returns null to indicate it's not handling this parameter, or it returns a new parameter binding instance - in this case the SimplePostVariableParameterBinding. Once the parameter binding and this hook up code is in place, you can now pass simple POST values to methods with simple parameters. The examples I showed above should now work in addition to the standard bindings. Summary Clearly this is not easy to discover. I spent quite a bit of time digging through the Web API source trying to figure this out on my own without much luck. It took Hong Mei at Micrsoft to provide a base example as I asked around so I can't take credit for this solution :-). But once you know where to look, Web API is brilliantly extensible to make it relatively easy to customize the parameter behavior. I'm very stoked that this got resolved  - in the last two months I've had two customers with projects that decided not to use Web API in AJAX heavy SPA applications because this POST variable mapping wasn't available. This might actually change their mind to still switch back and take advantage of the many great features in Web API. I too frequently use plain POST variables for communicating with server AJAX handlers and while I could have worked around this (with untyped JObject or the Form collection mostly), having proper POST to parameter mapping makes things much easier. I said this in my last post on POST data and say it again here: I think POST to method parameter mapping should have been shipped in the box with Web API, because without knowing about this limitation the expectation is that simple POST variables map to parameters just like query string values do. I hope Microsoft considers including this type of functionality natively in the next version of Web API natively or at least as a built-in HttpParameterBinding that can be just added. This is especially true, since this binding doesn't affect existing bindings. Resources SimplePostVariableParameterBinding Source on GitHub Global.asax hookup source Mapping URL Encoded Post Values in  ASP.NET Web API© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api  AJAX   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Book Review: Professional WCF 4

    - by Sam Abraham
    My Investigation of WCF internals have set the right stage to revisit Professional WCF 4 by Pablo Cibraro, Kurt Claeys, Fabio Cozzolino and Johann Grabner. In this book, the authors dive deep into all aspects of the WCF API in a reading targeted towards intermediate and advanced developers. Book quality so far as presentation, code completeness, content clarity and organization was superb. The authors have taken a hands-on approach to thoroughly covering the WCF 4.0 API with three chapters totaling 100+ pages completely dedicated to business cases with downloadable source code readily available. Chapter 1 outlines SOA best-practice considerations. Next three chapters take a top-down approach to the WCF API covering service and data contracts, bindings, clients, instancing and Workflow Services followed by another carefully-thought three chapters covering the security options available via the WCF API. In conclusion, Professional WCF 4.0 provides a thorough coverage of the WCF API and is a recommended read for anybody looking to reinforce their understanding of the various features available in the WCF framework. Many thanks to the Wiley/Wrox User Group Program for their support of our West Palm Beach Developers’ Group.   All the best, --Sam

    Read the article

  • What I&rsquo;m Up To: November 2012

    - by Brian T. Jackett
    This is a short personal post to let any regular readers know what I’m up to (and why I’ll be in reduced blogging mode for a bit). Writing 2 chapters for a SharePoint 2013 book (more to announce closer to publish date) Doing research, proof of concepts, and testing for above said writing Developing a SharePoint PowerShell diagnostic script to clean up issues found by the Health Analyzer Prepping for teaching SharePoint 2013 content to customers    There are some other community and personal commitments taking up my time (in addition to normal work responsibilities).  Since the number of hours in a day is limited to 24 hours I’m making a late addition to my goals for 2012 for the year of learning and adopting more personal productivity practices.  Before the end of this year I’ll be posting a couple that I’ve already adopted that are working well for me.  Scott Hanselman posted a great video recently that sparked me down this path.  I highly recommend you watch.   “It’s not what you read it’s what you ignore” video – Scott Hanselman http://www.hanselman.com/blog/ItsNotWhatYouReadItsWhatYouIgnoreVideoOfScottHanselmansPersonalProductivityTips.aspx         -Frog Out

    Read the article

  • How to automatically set default quota limits for users on XFS filesystem, when the new account is created

    - by acidburn2k
    I guess the title explains the problem pretty well. Do you have an idea for a mechanism, which will automatically assign default quota values for every new account created (sort as the skel scheme works, but in this area)? Now, I am looking for a generic clean solution, not some ugly cron based scripts, or wrapper scripts for creating users. I would also like to avoid any external, unmaintained stuff (like forgotten pam modules, and such). Anything what could lead to overhead and extra work in future isn't really the solution, nor is checking for new accounts every minute.

    Read the article

  • How can i set new domains to respond to my server

    - by André
    I would like to create a page for new clients in my hosting. When someone register a domain, sometimes that person don't have a dns, or the hosting didn't created the account. So the page will not respond. Is there any way to set in my primary domain DNS to respond to all domains pointing to me, to a specific new page like home/resseler/public_html/soon.html ? Like a CNAME myserver.com/soon.html CNAME ~~all domains pointing to my ns1 and ns2. A normal default page for news domains pointed to my server without account creation.

    Read the article

  • DegradedArray event on /dev/md0 without actually having a RAID

    - by J. Stoever
    Since I upgraded from Ubuntu LTS 10 to LTS 12, I have been getting error messages like: N 60 mdadm monitoring Mon Sep 3 06:38 31/1022 DegradedArray event on /dev/md2:Ubuntu-1004-lucid-64-minimal N 61 mdadm monitoring Mon Sep 3 06:38 31/1022 DegradedArray event on /dev/md0:Ubuntu-1004-lucid-64-minimal N 62 mdadm monitoring Mon Sep 3 06:38 31/1022 DegradedArray event on /dev/md1:Ubuntu-1004-lucid-64-minimal We do not have a RAID setup, and only have a single hard drive. Ideas ?

    Read the article

  • Enable a program in Windows to run multiple times?

    - by user135490
    I've got this legacy software that only allows you to run one copy at a time, it detects that you have another session opened and it won't allow you to open a second instance. The problem is this is a cpu intensive program and it only use a single core. Is there any hacks or tweaks so I can trick it and open more than one instance? This would allow me to retire about 5 servers... I'm using Windows 2008 R2. I had to use cff explorer to enable the use more than 2GB RAM as the program crashes when it tries to use more than 2GB.

    Read the article

  • Using nginx as a reverse proxy for tomcat results in new jsessionids for every ssl request

    - by user439407
    I am using nginx as a reverse proxy for a tomcat setup, and everything works fine for the MOST part, the only issue I am having is that every request to an http address results in a new JSESSION ID being created(this doesn't happen in http), here is the relevant part of the NGINX configuration: location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_redirect off; proxy_connect_timeout 240; proxy_send_timeout 240; proxy_read_timeout 240; proxy_pass http://localhost:8080; } Any idea why I am constantly genning new jsessionids?

    Read the article

  • Nginx Cache-Control

    - by optixx
    Iam serving my static content with ngnix. location /static { alias /opt/static/blog/; access_log off; etags on; etag_hash on; etag_hash_method md5; expires 1d; add_header Pragma "public"; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } The resulting header looks like this: Cache-Control:public, must-revalidate, proxy-revalidate Cache-Control:max-age=86400 Connection:close Content-Encoding:gzip Content-Type:application/x-javascript; charset=utf-8 Date:Tue, 11 Sep 2012 08:39:05 GMT Etag:e2266fb151337fc1996218fafcf3bcee Expires:Wed, 12 Sep 2012 08:39:05 GMT Last-Modified:Tue, 11 Sep 2012 06:22:41 GMT Pragma:public Server:nginx/1.2.2 Transfer-Encoding:chunked Vary:Accept-Encoding Why is nginx sending 2 Cache-Control entries, could this be a problem for the clients?

    Read the article

  • TFS 2012 or TFS Azure (Preview)

    - by Fore
    We want to migrate our current TFS 2010 solution that's hosted today in one of our own servers to TFS 2012 hosted somewhere else. We don't want to handle the servers any more, and therefor are looking at alternatives. TFS preview / Azure is one alternative, hosted in the cloud, but I'm not that happy with forcing users to use live id, and we don't have an AD. My second thought was to create a Azure virtual mashine, and there install and host TFS 2012. Is there any downsides with this? Compared to the price of bying a VPS this is cheap and feels reliable in Azure? Do you have any other ideas?

    Read the article

  • Apache user owns git project root, with git-http-backend setup, but still having permissions problems

    - by Luke
    I've setup git-http-backend on my vps server (CentOS), under one of its users. The apache user owns the git project root directory - /home/theuser/git/, as below: drwxrwxr-x 3 apache apache The apache user also owns everything inside that directory. But I'm still getting the following error in git when trying to push: error: unpack failed: unpack-objects abnormal exit The apache error log shows the following error: error: insufficient permission for adding an object to repository database ./objects I've tried every combination of user permissions and enabled read/write access, but not getting anywhere. Should the git user own this folder? Can someone explain exactly what user should own this folder, or what steps I might take to fix this problem?

    Read the article

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