Search Results

Search found 2408 results on 97 pages for 'uri herrera'.

Page 16/97 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Making your WCF Web Apis to speak in multiple languages

    - by cibrax
    One of the key aspects of how the web works today is content negotiation. The idea of content negotiation is based on the fact that a single resource can have multiple representations, so user agents (or clients) and servers can work together to chose one of them. The http specification defines several “Accept” headers that a client can use to negotiate content with a server, and among all those, there is one for restricting the set of natural languages that are preferred as a response to a request, “Accept-Language”. For example, a client can specify “es” in this header for specifying that he prefers to receive the content in spanish or “en” in english. However, there are certain scenarios where the “Accept-Language” header is just not enough, and you might want to have a way to pass the “accepted” language as part of the resource url as an extension. For example, http://localhost/ProductCatalog/Products/1.es” returns all the descriptions for the product with id “1” in spanish. This is useful for scenarios in which you want to embed the link somewhere, such a document, an email or a page.  Supporting both scenarios, the header and the url extension, is really simple in the new WCF programming model. You only need to provide a processor implementation for any of them. Let’s say I have a resource implementation as part of a product catalog I want to expose with the WCF web apis. [ServiceContract][Export]public class ProductResource{ IProductRepository repository;  [ImportingConstructor] public ProductResource(IProductRepository repository) { this.repository = repository; }  [WebGet(UriTemplate = "{id}")] public Product Get(string id, HttpResponseMessage response) { var product = repository.GetById(int.Parse(id)); if (product == null) { response.StatusCode = HttpStatusCode.NotFound; response.Content = new StringContent(Messages.OrderNotFound); }  return product; }} The Get method implementation in this resource assumes the desired culture will be attached to the current thread (Thread.CurrentThread.Culture). Another option is to pass the desired culture as an additional argument in the method, so my processor implementation will handle both options. This method is also using an auto-generated class for handling string resources, Messages, which is available in the different cultures that the service implementation supports. For example, Messages.resx contains “OrderNotFound”: “Order Not Found” Messages.es.resx contains “OrderNotFound”: “No se encontro orden” The processor implementation bellow tackles the first scenario, in which the desired language is passed as part of the “Accept-Language” header. public class CultureProcessor : Processor<HttpRequestMessage, CultureInfo>{ string defaultLanguage = null;  public CultureProcessor(string defaultLanguage = "en") { this.defaultLanguage = defaultLanguage; this.InArguments[0].Name = HttpPipelineFormatter.ArgumentHttpRequestMessage; this.OutArguments[0].Name = "culture"; }  public override ProcessorResult<CultureInfo> OnExecute(HttpRequestMessage request) { CultureInfo culture = null; if (request.Headers.AcceptLanguage.Count > 0) { var language = request.Headers.AcceptLanguage.First().Value; culture = new CultureInfo(language); } else { culture = new CultureInfo(defaultLanguage); }  Thread.CurrentThread.CurrentCulture = culture; Messages.Culture = culture;  return new ProcessorResult<CultureInfo> { Output = culture }; }}   As you can see, the processor initializes a new CultureInfo instance with the value provided in the “Accept-Language” header, and set that instance to the current thread and the auto-generated resource class with all the messages. In addition, the CultureInfo instance is returned as an output argument called “culture”, making possible to receive that argument in any method implementation   The following code shows the implementation of the processor for handling languages as url extensions.   public class CultureExtensionProcessor : Processor<HttpRequestMessage, Uri>{ public CultureExtensionProcessor() { this.OutArguments[0].Name = HttpPipelineFormatter.ArgumentUri; }  public override ProcessorResult<Uri> OnExecute(HttpRequestMessage httpRequestMessage) { var requestUri = httpRequestMessage.RequestUri.OriginalString;  var extensionPosition = requestUri.LastIndexOf(".");  if (extensionPosition > -1) { var extension = requestUri.Substring(extensionPosition + 1);  var query = httpRequestMessage.RequestUri.Query;  requestUri = string.Format("{0}?{1}", requestUri.Substring(0, extensionPosition), query); ;  var uri = new Uri(requestUri);  httpRequestMessage.Headers.AcceptLanguage.Clear();  httpRequestMessage.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(extension));  var result = new ProcessorResult<Uri>();  result.Output = uri;  return result; }  return new ProcessorResult<Uri>(); }} The last step is to inject both processors as part of the service configuration as it is shown bellow, public void RegisterRequestProcessorsForOperation(HttpOperationDescription operation, IList<Processor> processors, MediaTypeProcessorMode mode){ processors.Insert(0, new CultureExtensionProcessor()); processors.Add(new CultureProcessor());} Once you configured the two processors in the pipeline, your service will start speaking different languages :). Note: Url extensions don’t seem to be working in the current bits when you are using Url extensions in a base address. As far as I could see, ASP.NET intercepts the request first and tries to route the request to a registered ASP.NET Http Handler with that extension. For example, “http://localhost/ProductCatalog/products.es” does not work, but “http://localhost/ProductCatalog/products/1.es” does.

    Read the article

  • Android Maps Back Button

    - by aaronr
    I'm developing an application that shows a path on a map, determined by a KML file. Specifically, in the MapActivity that is starting the map: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MapView mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); Uri uri = Uri.parse("geo:0,0?q=http://urltokml"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri); mapIntent.setData(uri); startActivity(Intent.createChooser(mapIntent, kmlFile)); finish(); } The map loads fine and after a few seconds the path described by the KML shows up. The problem is, when I press the "Back" button, it does not return to the previous screen but instead just hides the KML overlay. If the "Back" button is pressed again, it will return to the previous screen. Any ideas of how to solve this?

    Read the article

  • How to make regex variables to capture of routes

    - by Zephiro
    anyone can help me with this problem. example $uri = '/username/carlos'; => $routes[] = '/username/@name'; @name convert in variable $name capturing string "carlos" $routes[] = '/list/edit/@id:[0-9]{3}'; $routes[] = '/username/@name'; $routes[] = '/archive/*'; $routes[] = '/'; $uri = '/username/carlos'; foreach ( $routes as $pattern ) { if ( preg_match( '#^' . preg_replace( '#(?:{{)?@(\w+\b)(?:}})?#i', '(?P<\1>[\w\-\.!~\*\'"(),\s]+)', str_replace( '\*', '(.*)', preg_quote( $pattern, '/' ) ) ) . '\/?$#i', $uri, $matchs ) ) { //how to make regex for this to work : echo $name; // carlos =>$uri = '/username/carlos'; or matt => $uri = '/username/matt'; } } thanks for reading

    Read the article

  • How to use strange characters in a query string

    - by peter
    I am using silverlight / ASP .NET and C#. What if I want to do this from silverlight for instance, // I have left out the quotes to show you literally what the characters // are that I want to use string password = vtakyoj#"5 string encodedPassword = HttpUtility.UrlEncode(encryptedPassword, Encoding.UTF8); // encoded password now = vtakyoj%23%225 URI uri = new URI("http://www.url.com/page.aspx@password=vtakyoj%23%225"); HttpPage.Window.Navigate(uri); If I debug and look at the value of uri it shows up as this (we are still inside the silverlight app), http://www.url.com?password=vtakyoj%23"5 So the %22 has become a quote for some reason. If I then debug inside the page.aspx code (which of course is ASP .NET) the value of Request["pasword"] is actually this, vtakyoj#"5 Which is the original value. How does that work? I would have thought that I would have to go, HttpUtility.UrlDecode(Request["pswd"], Encoding.UTF8) To get the original value. Hope this makes sense? Thanks.

    Read the article

  • Import Contacts from .vcf file in Android 2.1

    - by Prateek Jain
    Hi All, I am able to retrieve all contacts from android in .vcf file using following code. ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); System.out.println("The value is " + cr.getType(uri)); AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); I don't know how to use this .vcf file to import all these contacts using code. The .vcf file contains all the details of all contacts including photos etc. Cheers, Prateek

    Read the article

  • How to get video file details eg. duration in Android?

    - by spirytus
    I struggle to get specific video file details so duration etc. from the file the files recorded earlier. All I can currently do is to get cursor with all the files, then loop one by one. Cursor cursor = MediaStore.Video.query(getContext().getContentResolver(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Video.VideoColumns.DURATION,MediaStore.Video.VideoColumns.DATE_TAKEN,MediaStore.Video.VideoColumns.RESOLUTION,MediaStore.Video.VideoColumns.DISPLAY_NAME}); if(cursor.moveToFirst()) while(!cursor.isLast()){ if(cursor.getString(3)==fight.filename) { // do something here } cursor.moveToNext(); } I need however to access details of specific files so I tried to create URI but no luck as cursor returned is always null. Where do I go wrong? Uri uri = Uri.parse(Environment.DIRECTORY_DCIM+"/FightAll_BJJ_Scoring/"+(fight.filename)); Cursor cursor = MediaStore.Video.query(getContext().getContentResolver(), uri, new String[]{MediaStore.Video.VideoColumns.DURATION,MediaStore.Video.VideoColumns.DATE_TAKEN,MediaStore.Video.VideoColumns.RESOLUTION,MediaStore.Video.VideoColumns.DISPLAY_NAME}); // cursor is always null here

    Read the article

  • Google Site Data fetching

    - by inTagger
    Hail! I want to fetch image from NOT PUBLIC Google Site's page. I'm using WebClient for this purposes. var uri = new Uri("http://sites.google.com/a/MYDOMAIN.COM/SITENAME/" + "_/rsrc/1234567890/MYIMAGE.jpg"); string fileName = "d:\\!temp\\MYIMAGE.jpg"; if (File.Exists(fileName)) File.Delete(fileName); using (var webClient = new WebClient()) { var networkCredential = new NetworkCredential("USERNAME", "PASSWORD"); var credentialCache = new CredentialCache { {new Uri("sites.google.com"), "Basic", networkCredential}, {new Uri("www.google.com"), "Basic", networkCredential} }; webClient.Credentials = credentialCache; webClient.DownloadFile(uri, fileName); } It doesn't download image, but html file with login form is downloaded. If i open this link in browser it shows me login form then i enter username and password and then i can see the image. How i must use my credentials to download file with WebClient or HttpWebRequest?

    Read the article

  • Errors when connecting to HTTPS using HTTP::Net routines (Ruby on Rails)

    - by jaycode
    Hi all, the code below explains the problem in detail #this returns error Net::HTTPBadResponse url = URI.parse('https://sitename.com') response = Net::HTTP.start(url.host, url.port) {|http| http.get('/remote/register_device') } #this works url = URI.parse('http://sitename.com') response = Net::HTTP.start(url.host, url.port) {|http| http.get('/remote/register_device') } #this returns error Net::HTTPBadResponse response = Net::HTTP.post_form(URI.parse('https://sitename.com/remote/register_device'), {:text => 'hello world'}) #this returns error Errno::ECONNRESET (Connection reset by peer) response = Net::HTTP.post_form(URI.parse('https://sandbox.itunes.apple.com/verifyReceipt'), {:text => 'hello world'}) #this works response = Net::HTTP.post_form(URI.parse('http://sitename.com/remote/register_device'), {:text => 'hello world'}) So... how do I send POST parameters to https://sitename.com or https://sandbox.itunes.apple.com/verifyReceipt in this example? Further information, I am trying to get this working in Rails: http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/StoreKitGuide/VerifyingStoreReceipts/VerifyingStoreReceipts.html#//apple_ref/doc/uid/TP40008267-CH104-SW1

    Read the article

  • RMI java doesn't create skeleton class

    - by pavithra
    I wrote a remote service MyremoteImpl.java and used following command after compiled it. rmic MyRemoteImpl I learned that this method suppose to create stub class and a skeleton class but I can only see the stub class, why is that? The other problem I faced after run rmiregistry I started the service but it gives following error, I doubt I get this error as I'm missing skeleton class? java.net.MalformedURLException: invalid URL String: Remote Hello at java.rmi.Naming.parseURL(Unknown Source) at java.rmi.Naming.rebind(Unknown Source) at RMIservice.MyRemoteImpl.main(MyRemoteImpl.java:22) Caused by: java.net.URISyntaxException: Illegal character in path at index 6: Remote Hello at java.net.URI$Parser.fail(Unknown Source) at java.net.URI$Parser.checkChars(Unknown Source) at java.net.URI$Parser.parseHierarchical(Unknown Source) at java.net.URI$Parser.parse(Unknown Source) at java.net.URI.<init>(Unknown Source) at java.rmi.Naming.intParseURL(Unknown Source) ... 3 more Please help me to solve this, Thanx in advance!!!

    Read the article

  • Starting a browser from a textbox via Intent - Is http:// required?

    - by VitalyB
    Hi, I have the following code: /** Open a browser on the URL specified in the text box */ private void openBrowser() { Uri uri = Uri.parse(urlText.getText().toString()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } When I input "http://www.google.com" to the textbox, it works fine. However, when I try something like "www.google.com" it crashes with: No Activity found to handle Intent { act=android.intent.action.VIEW dat=www.google.com } Am I using Uri wrong? Is there a way to extract full address from it? Or am I supposed to write code that adds http manually? e.g, if not starts with http://, add http://. Thanks!

    Read the article

  • How to I fix software center after installing the Linux Mint MATE desktop?

    - by tinuz
    I installed the MATE desktop using this manual but now i can't open my Ubuntu Software Center and can't open the settings from the update manager. I removed mate desktop but it doesn't fix the problem, i also reinstalled the software center, software-properties-gtk and software-properties-common using: sudo apt-get update; sudo apt-get --purge --reinstall install software-center software-properties-common software-properties-gtk. But when using this line i get the following error: Reading package lists... Done Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 3 reinstalled, 0 to remove and 0 not upgraded. Need to get 0 B/735 kB of archives. After this operation, 0 B of additional disk space will be used. (Reading database ... 304824 files and directories currently installed.) Preparing to replace software-center 5.0.2 (using .../software-center_5.0.2_all.deb) ... Unpacking replacement software-center ... Preparing to replace software-properties-common 0.81.13.1 (using .../software-properties-common_0.81.13.1_all.deb) ... Unpacking replacement software-properties-common ... Preparing to replace software-properties-gtk 0.81.13.1 (using .../software-properties-gtk_0.81.13.1_all.deb) ... Unpacking replacement software-properties-gtk ... Processing triggers for desktop-file-utils ... Processing triggers for gnome-menus ... Processing triggers for bamfdaemon ... Rebuilding /usr/share/applications/bamf.index... Processing triggers for hicolor-icon-theme ... Processing triggers for man-db ... Processing triggers for shared-mime-info ... Unknown media type in type 'all/all' Unknown media type in type 'all/allfiles' Unknown media type in type 'uri/mms' Unknown media type in type 'uri/mmst' Unknown media type in type 'uri/mmsu' Unknown media type in type 'uri/pnm' Unknown media type in type 'uri/rtspt' Unknown media type in type 'uri/rtspu' Unknown media type in type 'interface/x-winamp-skin' Setting up software-center (5.0.2) ... Traceback (most recent call last): File "/usr/sbin/update-software-center", line 38, in <module> from softwarecenter.db.update import rebuild_database File "/usr/share/software-center/softwarecenter/db/update.py", line 59, in <module> from softwarecenter.db.database import parse_axi_values_file File "/usr/share/software-center/softwarecenter/db/database.py", line 26, in <module> from softwarecenter.db.application import Application File "/usr/share/software-center/softwarecenter/db/application.py", line 25, in <module> from softwarecenter.backend.channel import is_channel_available File "/usr/share/software-center/softwarecenter/backend/channel.py", line 25, in <module> from softwarecenter.distro import get_distro File "/usr/share/software-center/softwarecenter/distro/__init__.py", line 165, in <module> distro_instance=_get_distro() File "/usr/share/software-center/softwarecenter/distro/__init__.py", line 148, in _get_distro module = __import__(distro_id, globals(), locals(), [], -1) ImportError: No module named LinuxMint Setting up software-properties-common (0.81.13.1) ... Setting up software-properties-gtk (0.81.13.1) ... $ Is there a way to fix this problem without having to reinstall Ubuntu 11.10?? thanks in advance tinuz

    Read the article

  • How to remove the Mint stuff from my system after installing MATE desktop using MINT repository

    - by tinuz
    I installed the MATE desktop using this manual http://www.unixmen.com/linux-tutorials/linux-distributions/linux-distributions4-ubuntu/1975-install-linuxmint12-extensions-mate-a-mgse-in-ubuntu-1110- but now i can't open my Ubuntu Software Center and can't open the settings from the update manager. I removed mate desktop but it doesn't fix the problem, i also reinstalled the software center, software-properties-gtk and software-properties-common using: sudo apt-get update; sudo apt-get --purge --reinstall install software-center software-properties-common software-properties-gtk. But when using this line i get the following error: Reading package lists... Done Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 3 reinstalled, 0 to remove and 0 not upgraded. Need to get 0 B/735 kB of archives. After this operation, 0 B of additional disk space will be used. (Reading database ... 304824 files and directories currently installed.) Preparing to replace software-center 5.0.2 (using .../software-center_5.0.2_all.deb) ... Unpacking replacement software-center ... Preparing to replace software-properties-common 0.81.13.1 (using .../software-properties-common_0.81.13.1_all.deb) ... Unpacking replacement software-properties-common ... Preparing to replace software-properties-gtk 0.81.13.1 (using .../software-properties-gtk_0.81.13.1_all.deb) ... Unpacking replacement software-properties-gtk ... Processing triggers for desktop-file-utils ... Processing triggers for gnome-menus ... Processing triggers for bamfdaemon ... Rebuilding /usr/share/applications/bamf.index... Processing triggers for hicolor-icon-theme ... Processing triggers for man-db ... Processing triggers for shared-mime-info ... Unknown media type in type 'all/all' Unknown media type in type 'all/allfiles' Unknown media type in type 'uri/mms' Unknown media type in type 'uri/mmst' Unknown media type in type 'uri/mmsu' Unknown media type in type 'uri/pnm' Unknown media type in type 'uri/rtspt' Unknown media type in type 'uri/rtspu' Unknown media type in type 'interface/x-winamp-skin' Setting up software-center (5.0.2) ... Traceback (most recent call last): File "/usr/sbin/update-software-center", line 38, in <module> from softwarecenter.db.update import rebuild_database File "/usr/share/software-center/softwarecenter/db/update.py", line 59, in <module> from softwarecenter.db.database import parse_axi_values_file File "/usr/share/software-center/softwarecenter/db/database.py", line 26, in <module> from softwarecenter.db.application import Application File "/usr/share/software-center/softwarecenter/db/application.py", line 25, in <module> from softwarecenter.backend.channel import is_channel_available File "/usr/share/software-center/softwarecenter/backend/channel.py", line 25, in <module> from softwarecenter.distro import get_distro File "/usr/share/software-center/softwarecenter/distro/__init__.py", line 165, in <module> distro_instance=_get_distro() File "/usr/share/software-center/softwarecenter/distro/__init__.py", line 148, in _get_distro module = __import__(distro_id, globals(), locals(), [], -1) ImportError: No module named LinuxMint Setting up software-properties-common (0.81.13.1) ... Setting up software-properties-gtk (0.81.13.1) ... $ Is there a way to fix this problem without having to reinstall Ubuntu 11.10?? thanks in advance tinuz

    Read the article

  • WCF Service : WSHttpBinding

    - by jitm
    Hello, I've created the test self-hosted wcf application and tried to add support https. Code of server application is: using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; namespace SelfHost { class Program { static void Main(string[] args) { string addressHttp = String.Format("http://{0}:8002/hello", System.Net.Dns.GetHostEntry("").HostName); Uri baseAddress = new Uri(addressHttp); WSHttpBinding b = new WSHttpBinding(); b.Security.Mode = SecurityMode.Transport; b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; Uri a = new Uri(addressHttp); Uri[] baseAddresses = new Uri[] { a }; ServiceHost sh = new ServiceHost(typeof(HelloWorldService), baseAddresses); Type c = typeof(IHelloWorldService); sh.AddServiceEndpoint(c, b, "hello"); sh.Credentials.ServiceCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName,"myCert"); sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; try { sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; Console.WriteLine("Listening @ {0}", address); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); sh.Close(); } catch (CommunicationException ce) { Console.WriteLine("A commmunication error occurred: {0}", ce.Message); Console.WriteLine(); } catch (System.Exception exc) { Console.WriteLine("An unforseen error occurred: {0}", exc.Message); Console.ReadLine(); } } } [ServiceContract] public interface IHelloWorldService { [OperationContract] string SayHello(string name); } public class HelloWorldService : IHelloWorldService { public string SayHello(string name) { return string.Format("Hello, {0}", name); } } } What name(address) should I out into line sh.AddServiceEndpoint(c, b, "hello"); because "hello" is incorrect ? Thanks.

    Read the article

  • How to Global onRouteRequest directly to onBadRequest?

    - by virtualeyes
    EDIT Came up with this to sanitize URI date params prior to passing off to Play router val ymdMatcher = "\\d{8}".r // matcher for yyyyMMdd URI param val ymdFormat = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd") def ymd2Date(ymd: String) = ymdFormat.parseDateTime(ymd) override def onRouteRequest(r: RequestHeader): Option[Handler] = { import play.api.i18n.Messages ymdMatcher.findFirstIn(r.uri) map{ ymd=> try { ymd2Date( ymd); super.onRouteRequest(r) } catch { case e:Exception => // kick to "bad" action handler on invalid date Some(controllers.Application.bad(Messages("bad.date.format"))) } } getOrElse(super.onRouteRequest(r)) } ORIGINAL Let's say I want to return a BadRequest result type for all /foo URIs: override def onBadRequest(r: RequestHeader, error: String) = { BadRequest("Bad Request: " + error) } override def onRouteRequest(r: RequestHeader): Option[Handler] = { if(r.uri.startsWith("/foo") onBadRequest("go away") else super.onRouteRequest(r) } Of course does not work, since the expected return type is Option[play.api.mvc.Handler] What's the idiomatic way to deal with this, create a default Application controller method to handle filtered bad requests? Ideally, since I know in onRouteRequest that /foo is in fact a BadRequest, I'd like to call onBadRequest directly. Should note that this is a contrived example, am actually verifying a URI yyyyMMdd date param, and BadRequest-ing if it does not parse to a JodaTime instance -- basically a catch-all filter to sanitize a given date param rather than handling on every single controller method call, not to mention, avoiding cluttering up application log with useless stack traces re: invalid date parse conversions (have several MBs of these junk trace entries accruing daily due to users pointlessly manipulating the uri date in attempts to get at paid subscriber content)

    Read the article

  • Please help with my JSP Internationalization problem

    - by wokena
    I have problem with I18N in JSP, specifically, with forms. When I enter some Czech characters (e.g., "ešcržýá...") into my page one form, into the field "fieldOne", and then show text from that field on page two, instead of Czech characters I see this as "čč". (Note, the second page gets the Czech characters with "request.getProperty("fieldOne")") Here is the source code: Page one: <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %> <html> <head></head> <body> <form action="druha.jsp" method="post"> <input type="textarea" name="fieldOne"> <input type="submit"> </form> </body> </html> Page two: <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %> <html> <head></head> <body> <h1>The text: </h1> <%=request.getProperty("fieldOne")%> </body> </html> Thanks for help...

    Read the article

  • Media query from a specific folder

    - by sensei
    I would like to understand how I can use a cursor to jpg files in a folder specified in the sdcard. I'm trying to select with a cursor the jpg files in a specific folder, and I tried this: This is the code: public static Uri getRandomImage(ContentResolver resolver) { String[] projection = new String[] { BaseColumns._ID, }; String folder = "/sdcard/DCIM/Wallpaper/"; folder = folder + "%"; Uri uri = Media.EXTERNAL_CONTENT_URI; String[] whereArgs = new String[]{folder}; Cursor cursor = resolver.query(uri, projection, null, whereArgs, MediaColumns._ID); if (cursor == null || cursor.getCount() <= 0) { return null; } cursor.moveToPosition(new Random().nextInt(cursor.getCount())); return Uri.withAppendedPath(uri, cursor.getString(0)); } but this code gives me error here is the logcat: E/AndroidRuntime(11986): FATAL EXCEPTION: main E/AndroidRuntime(11986): android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x26a490 E/AndroidRuntime(11986): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158) E/AndroidRuntime(11986): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114) E/AndroidRuntime(11986): at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330) E/AndroidRuntime(11986): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366) E/AndroidRuntime(11986): at android.content.ContentResolver.query(ContentResolver.java:245) E/AndroidRuntime(11986): at it.bisemanuDEV.slidepuzzle.SelectImagePreference.getRandomImage(SelectImagePreference.java:126) E/AndroidRuntime(11986): at it.bisemanuDEV.slidepuzzle.TileView.newGame(TileView.java:156) E/AndroidRuntime(11986): at it.bisemanuDEV.slidepuzzle.SlidePuzzleActivity.onOptionsItemSelected(SlidePuzzleActivity.java:377) E/AndroidRuntime(11986): at android.app.Activity.onMenuItemSelected(Activity.java:2762) E/AndroidRuntime(11986): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730) E/AndroidRuntime(11986): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143) E/AndroidRuntime(11986): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855) E/AndroidRuntime(11986): at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532) E/AndroidRuntime(11986): at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122) E/AndroidRuntime(11986): at android.view.View$PerformClick.run(View.java:8819) E/AndroidRuntime(11986): at android.os.Handler.handleCallback(Handler.java:603) E/AndroidRuntime(11986): at android.os.Handler.dispatchMessage(Handler.java:92) E/AndroidRuntime(11986): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime(11986): at android.app.ActivityThread.main(ActivityThread.java:4627) E/AndroidRuntime(11986): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(11986): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime(11986): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) E/AndroidRuntime(11986): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) E/AndroidRuntime(11986): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • 404 when getting private YouTube video even when logged in with the owner's account using gdata-pyth

    - by Gonzalo
    If a YouTube video is set as private and I try to fetch it using the gdata Python API a 404 RequestError is raised, even though I have done a programmatic login with the account that owns that video: from gdata.youtube import service yt_service = service.YouTubeService(email=my_email, password=my_password, client_id=my_client_id, source=my_source, developer_key=my_developer_key) yt_service.ProgrammaticLogin() yt_service.GetYouTubeVideoEntry(video_id='IcVqemzfyYs') --------------------------------------------------------------------------- RequestError Traceback (most recent call last) <ipython console> /usr/lib/python2.4/site-packages/gdata/youtube/service.pyc in GetYouTubeVideoEntry(self, uri, video_id) 203 elif video_id and not uri: 204 uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id) --> 205 return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString) 206 207 def GetYouTubeContactFeed(self, uri=None, username='default'): /usr/lib/python2.4/site-packages/gdata/service.pyc in Get(self, uri, extra_headers, redirects_remaining, encoding, converter) 1100 'body': result_body} 1101 else: -> 1102 raise RequestError, {'status': server_response.status, 1103 'reason': server_response.reason, 'body': result_body} 1104 RequestError: {'status': 404, 'body': 'Video not found', 'reason': 'Not Found'} This happens every time, unless I go into my YouTube account (through the YouTube website) and set it public, after that I can set it as private and back to public using the Python API. Am I missing a step or is there another (or any) way to fetch a YouTube video set as private from the API? Thanks in advance.

    Read the article

  • Rich faces3.3.2 is not working in WebSphear 7

    - by palakolanusrinu
    Hi, I'm new to this rich faces and JSF i have developed one sample app and its working fine in tomcat6 now same app i have moved to WebSphear7 here i'm facing the problem. Exception on console: Unable to locate the tag library for uri //richfaces.org/rich" List of jars in build path: Commons-beanutils-1.8.3.jar commons-codec-1.4.jar commons-collections-3.2.1.jar commons-digester-2.0.jar commons-discovery-0.4.jar conmmons-logging.jar jsf-api.jar jsf-impl.jar jstl-1.2.jar jstl-api-1.2.jar jst-impl-1.2.jar richfaces-api-3.3.2.SR1.jar richfaces-impl-3.3.2.SR1.jar richfaces-ui-3.3.2.SR1.jar Web.xml is http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5" bbh index.html index.htm index.jsp default.html default.htm default.jsp Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet *.jsf State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2 javax.faces.STATE_SAVING_METHOD client javax.servlet.jsp.jstl.fmt.localizationContext resources.application com.sun.faces.config.ConfigureListener Faces Servlet *.faces <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>blueSky</param-value> </context-param> <filter> <display-name>RichFaces Filter</display-name> <filter-name>richfaces</filter-name> <filter-class>org.ajax4jsf.Filter</filter-class> <init-param> <param-name>createTempFiles</param-name> true maxRequestSize 2000000 richfaces Faces Servlet REQUEST FORWARD INCLUDE My JSP including the tag libs are like <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"% <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"% <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"% <%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"% <%@ taglib uri="http://richfaces.org/rich" prefix="rich"% Please Help me and thx in advance

    Read the article

  • Persistant Http client connections in java

    - by Akusete
    I am trying to write a simple Http client application in Java and am a bit confused by the seemingly different ways to establish Http client connections, and efficiently re-use the objects. Current I am using the following steps (I have left out exception handling for simplicity) Iterator<URI> uriIterator = someURIs(); HttpClient client = new DefaultHttpClient(); while (uriIterator.hasNext()) { URI uri = uriIterator.next(); HttpGet request = new HttpGet(uri); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); InputStream s = entity.getContent(); processStream (); s.close(); } In regard to the code above, my questions is: Assuming all URI's are pointing to the same host (but different resources on that host). What is the recommended way to use a single http connection for all requests? And how do you close the connection after the last request? --edit: Also what is the difference between using uri.openConnection(), versus HttpClient? Which is preferable, and what other methods exist?

    Read the article

  • Javascript errors on internet explorer with jQuery but working fine on Firefox

    - by user994319
    A quick question I'm hoping someone can help me out with. On firefox our jQuery slider is working perfectly, however on viewing with internet explorer there are some javascript errors occurring. The website is http://foscam-uk.com/index.php Hoping there is a possible solution to this. Kind Regards and Thank You! Errors: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3) Timestamp: Wed, 6 Jun 2012 22:36:43 UTC Message: Object doesn't support this property or method Line: 5653 Char: 9 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 5988 Char: 5 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 2 Char: 5 Code: 0 URI: http://foscam-uk.com/skin/frontend/default/theme316/js/scripts.js Message: Object doesn't support this property or method Line: 5736 Char: 7 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 5988 Char: 5 Code: 0 URI: http://foscam-uk.com/js/prototype/prototype.js Message: Object doesn't support this property or method Line: 73 Char: 11 Code: 0 URI: http://foscam-uk.com/index.php

    Read the article

  • Just need someone familiar with HTTPClient to check over a piece of code

    - by jax
    here are two little helper methods I have made for downloading files. I have had to mix and match different tutorials of the web to get what I have here. Now is there anything that I have done blatantly wrong here? public static InputStream simplePostRequest(URL url, List<NameValuePair> postData) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost postMethod=new HttpPost(url.toExternalForm()); postMethod.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8)); HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); return entity.getContent(); } public static InputStream simpleGetRequest(URL url, List<NameValuePair> queryString) throws ClientProtocolException, IOException { Uri.Builder uri = new Uri.Builder(); uri.path(url.getPath()); for(NameValuePair nvp: queryString) { uri.appendQueryParameter(nvp.getName(), nvp.getValue()); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpHost host = new HttpHost(url.getHost()); HttpResponse response = httpClient.execute(host, new HttpGet(uri.build().toString())); HttpEntity entity = response.getEntity(); return entity.getContent(); }

    Read the article

  • Entity Framework Code-First, OData & Windows Phone Client

    - by Jon Galloway
    Entity Framework Code-First is the coolest thing since sliced bread, Windows  Phone is the hottest thing since Tickle-Me-Elmo and OData is just too great to ignore. As part of the Full Stack project, we wanted to put them together, which turns out to be pretty easy… once you know how.   EF Code-First CTP5 is available now and there should be very few breaking changes in the release edition, which is due early in 2011.  Note: EF Code-First evolved rapidly and many of the existing documents and blog posts which were written with earlier versions, may now be obsolete or at least misleading.   Code-First? With traditional Entity Framework you start with a database and from that you generate “entities” – classes that bridge between the relational database and your object oriented program. With Code-First (Magic-Unicorn) (see Hanselman’s write up and this later write up by Scott Guthrie) the Entity Framework looks at classes you created and says “if I had created these classes, the database would have to have looked like this…” and creates the database for you! By deriving your entity collections from DbSet and exposing them via a class that derives from DbContext, you "turn on" database backing for your POCO with a minimum of code and no hidden designer or configuration files. POCO == Plain Old CLR Objects Your entity objects can be used throughout your applications - in web applications, console applications, Silverlight and Windows Phone applications, etc. In our case, we'll want to read and update data from a Windows Phone client application, so we'll expose the entities through a DataService and hook the Windows Phone client application to that data via proxies.  Piece of Pie.  Easy as cake. The Demo Architecture To see this at work, we’ll create an ASP.NET/MVC application which will act as the host for our Data Service.  We’ll create an incredibly simple data layer using EF Code-First on top of SQLCE4 and we’ll expose the data in a WCF Data Service using the oData protocol.  Our Windows Phone 7 client will instantiate  the data context via a URI and load the data asynchronously. Setting up the Server project with MVC 3, EF Code First, and SQL CE 4 Create a new application of type ASP.NET MVC 3 and name it DeadSimpleServer.  We need to add the latest SQLCE4 and Entity Framework Code First CTP's to our project. Fortunately, NuGet makes that really easy. Open the Package Manager Console (View / Other Windows / Package Manager Console) and type in "Install-Package EFCodeFirst.SqlServerCompact" at the PM> command prompt. Since NuGet handles dependencies for you, you'll see that it installs everything you need to use Entity Framework Code First in your project. PM> install-package EFCodeFirst.SqlServerCompact 'SQLCE (= 4.0.8435.1)' not installed. Attempting to retrieve dependency from source... Done 'EFCodeFirst (= 0.8)' not installed. Attempting to retrieve dependency from source... Done 'WebActivator (= 1.0.0.0)' not installed. Attempting to retrieve dependency from source... Done You are downloading SQLCE from Microsoft, the license agreement to which is available at http://173.203.67.148/licenses/SQLCE/EULA_ENU.rtf. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'SQLCE 4.0.8435.1' You are downloading EFCodeFirst from Microsoft, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=206497. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'EFCodeFirst 0.8' Successfully installed 'WebActivator 1.0.0.0' You are downloading EFCodeFirst.SqlServerCompact from Microsoft, the license agreement to which is available at http://173.203.67.148/licenses/SQLCE/EULA_ENU.rtf. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'EFCodeFirst.SqlServerCompact 0.8' Successfully added 'SQLCE 4.0.8435.1' to EfCodeFirst-CTP5 Successfully added 'EFCodeFirst 0.8' to EfCodeFirst-CTP5 Successfully added 'WebActivator 1.0.0.0' to EfCodeFirst-CTP5 Successfully added 'EFCodeFirst.SqlServerCompact 0.8' to EfCodeFirst-CTP5 Note: We're using SQLCE 4 with Entity Framework here because they work really well together from a development scenario, but you can of course use Entity Framework Code First with other databases supported by Entity framework. Creating The Model using EF Code First Now we can create our model class. Right-click the Models folder and select Add/Class. Name the Class Person.cs and add the following code: using System.Data.Entity; namespace DeadSimpleServer.Models { public class Person { public int ID { get; set; } public string Name { get; set; } } public class PersonContext : DbContext { public DbSet<Person> People { get; set; } } } Notice that the entity class Person has no special interfaces or base class. There's nothing special needed to make it work - it's just a POCO. The context we'll use to access the entities in the application is called PersonContext, but you could name it anything you wanted. The important thing is that it inherits DbContext and contains one or more DbSet which holds our entity collections. Adding Seed Data We need some testing data to expose from our service. The simplest way to get that into our database is to modify the CreateCeDatabaseIfNotExists class in AppStart_SQLCEEntityFramework.cs by adding some seed data to the Seed method: protected virtual void Seed( TContext context ) { var personContext = context as PersonContext; personContext.People.Add( new Person { ID = 1, Name = "George Washington" } ); personContext.People.Add( new Person { ID = 2, Name = "John Adams" } ); personContext.People.Add( new Person { ID = 3, Name = "Thomas Jefferson" } ); personContext.SaveChanges(); } The CreateCeDatabaseIfNotExists class name is pretty self-explanatory - when our DbContext is accessed and the database isn't found, a new one will be created and populated with the data in the Seed method. There's one more step to make that work - we need to uncomment a line in the Start method at the top of of the AppStart_SQLCEEntityFramework class and set the context name, as shown here, public static class AppStart_SQLCEEntityFramework { public static void Start() { DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); // Sets the default database initialization code for working with Sql Server Compact databases // Uncomment this line and replace CONTEXT_NAME with the name of your DbContext if you are // using your DbContext to create and manage your database DbDatabase.SetInitializer(new CreateCeDatabaseIfNotExists<PersonContext>()); } } Now our database and entity framework are set up, so we can expose data via WCF Data Services. Note: This is a bare-bones implementation with no administration screens. If you'd like to see how those are added, check out The Full Stack screencast series. Creating the oData Service using WCF Data Services Add a new WCF Data Service to the project (right-click the project / Add New Item / Web / WCF Data Service). We’ll be exposing all the data as read/write.  Remember to reconfigure to control and minimize access as appropriate for your own application. Open the code behind for your service. In our case, the service was called PersonTestDataService.svc so the code behind class file is PersonTestDataService.svc.cs. using System.Data.Services; using System.Data.Services.Common; using System.ServiceModel; using DeadSimpleServer.Models; namespace DeadSimpleServer { [ServiceBehavior( IncludeExceptionDetailInFaults = true )] public class PersonTestDataService : DataService<PersonContext> { // This method is called only once to initialize service-wide policies. public static void InitializeService( DataServiceConfiguration config ) { config.SetEntitySetAccessRule( "*", EntitySetRights.All ); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; config.UseVerboseErrors = true; } } } We're enabling a few additional settings to make it easier to debug if you run into trouble. The ServiceBehavior attribute is set to include exception details in faults, and we're using verbose errors. You can remove both of these when your service is working, as your public production service shouldn't be revealing exception information. You can view the output of the service by running the application and browsing to http://localhost:[portnumber]/PersonTestDataService.svc/: <service xml:base="http://localhost:49786/PersonTestDataService.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app"> <workspace> <atom:title>Default</atom:title> <collection href="People"> <atom:title>People</atom:title> </collection> </workspace> </service> This indicates that the service exposes one collection, which is accessible by browsing to http://localhost:[portnumber]/PersonTestDataService.svc/People <?xml version="1.0" encoding="iso-8859-1" standalone="yes"?> <feed xml:base=http://localhost:49786/PersonTestDataService.svc/ xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom"> <title type="text">People</title> <id>http://localhost:49786/PersonTestDataService.svc/People</id> <updated>2010-12-29T01:01:50Z</updated> <link rel="self" title="People" href="People" /> <entry> <id>http://localhost:49786/PersonTestDataService.svc/People(1)</id> <title type="text"></title> <updated>2010-12-29T01:01:50Z</updated> <author> <name /> </author> <link rel="edit" title="Person" href="People(1)" /> <category term="DeadSimpleServer.Models.Person" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> <content type="application/xml"> <m:properties> <d:ID m:type="Edm.Int32">1</d:ID> <d:Name>George Washington</d:Name> </m:properties> </content> </entry> <entry> ... </entry> </feed> Let's recap what we've done so far. But enough with services and XML - let's get this into our Windows Phone client application. Creating the DataServiceContext for the Client Use the latest DataSvcUtil.exe from http://odata.codeplex.com. As of today, that's in this download: http://odata.codeplex.com/releases/view/54698 You need to run it with a few options: /uri - This will point to the service URI. In this case, it's http://localhost:59342/PersonTestDataService.svc  Pick up the port number from your running server (e.g., the server formerly known as Cassini). /out - This is the DataServiceContext class that will be generated. You can name it whatever you'd like. /Version - should be set to 2.0 /DataServiceCollection - Include this flag to generate collections derived from the DataServiceCollection base, which brings in all the ObservableCollection goodness that handles your INotifyPropertyChanged events for you. Here's the console session from when we ran it: <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}" SelectionChanged="MainListBox_SelectionChanged"> Next, to keep things simple, change the Binding on the two TextBlocks within the DataTemplate to Name and ID, <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}" SelectionChanged="MainListBox_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="0,0,0,17" Width="432"> <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" /> <TextBlock Text="{Binding ID}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Getting The Context In the code-behind you’ll first declare a member variable to hold the context from the Entity Framework. This is named using convention over configuration. The db type is Person and the context is of type PersonContext, You initialize it by providing the URI, in this case using the URL obtained from the Cassini web server, PersonContext context = new PersonContext( new Uri( "http://localhost:49786/PersonTestDataService.svc/" ) ); Create a second member variable of type DataServiceCollection<Person> but do not initialize it, DataServiceCollection<Person> people; In the constructor you’ll initialize the DataServiceCollection using the PersonContext, public MainPage() { InitializeComponent(); people = new DataServiceCollection<Person>( context ); Finally, you’ll load the people collection using the LoadAsync method, passing in the fully specified URI for the People collection in the web service, people.LoadAsync( new Uri( "http://localhost:49786/PersonTestDataService.svc/People" ) ); Note that this method runs asynchronously and when it is finished the people  collection is already populated. Thus, since we didn’t need or want to override any of the behavior we don’t implement the LoadCompleted. You can use the LoadCompleted event if you need to do any other UI updates, but you don't need to. The final code is as shown below: using System; using System.Data.Services.Client; using System.Windows; using System.Windows.Controls; using DeadSimpleServer.Models; using Microsoft.Phone.Controls; namespace WindowsPhoneODataTest { public partial class MainPage : PhoneApplicationPage { PersonContext context = new PersonContext( new Uri( "http://localhost:49786/PersonTestDataService.svc/" ) ); DataServiceCollection<Person> people; // Constructor public MainPage() { InitializeComponent(); // Set the data context of the listbox control to the sample data // DataContext = App.ViewModel; people = new DataServiceCollection<Person>( context ); people.LoadAsync( new Uri( "http://localhost:49786/PersonTestDataService.svc/People" ) ); DataContext = people; this.Loaded += new RoutedEventHandler( MainPage_Loaded ); } // Handle selection changed on ListBox private void MainListBox_SelectionChanged( object sender, SelectionChangedEventArgs e ) { // If selected index is -1 (no selection) do nothing if ( MainListBox.SelectedIndex == -1 ) return; // Navigate to the new page NavigationService.Navigate( new Uri( "/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative ) ); // Reset selected index to -1 (no selection) MainListBox.SelectedIndex = -1; } // Load data for the ViewModel Items private void MainPage_Loaded( object sender, RoutedEventArgs e ) { if ( !App.ViewModel.IsDataLoaded ) { App.ViewModel.LoadData(); } } } } With people populated we can set it as the DataContext and run the application; you’ll find that the Name and ID are displayed in the list on the Mainpage. Here's how the pieces in the client fit together: Complete source code available here

    Read the article

  • Keep website and webservices warm with zero coding

    - by oazabir
    If you want to keep your websites or webservices warm and save user from seeing the long warm up time after an application pool recycle, or IIS restart or new code deployment or even windows restart, you can use the tinyget command line tool, that comes with IIS Resource Kit, to hit the site and services and keep them warm. Here’s how: First get tinyget from here. Download and install the IIS 6.0 Resource Kit on some PC. Then copy the tinyget.exe from “c:\program files…\IIS 6.0 ResourceKit\Tools'\tinyget” to the server where your IIS 6.0 or IIS 7 is running. Then create a batch file that will hit the pages and webservices. Something like this: SET TINYGET=C:\Program Files (x86)\IIS Resources\TinyGet\tinyget.exe"%TINYGET%" -srv:dropthings.omaralzabir.com -uri:http://dropthings.omaralzabir.com/ -status:200"%TINYGET%" -srv:dropthings.omaralzabir.com -uri:http://dropthings.omaralzabir.com/WidgetService.asmx?WSDL - status:200 First I am hitting the homepage to keep the webpage warm. Then I am hitting the webservice URL with ?WSDL parameter, which allows ASP.NET to compile the service if not already compiled and walk through all the operations and reflect on them and thus loading all related DLLs into memory and reducing the warmup time when hit. Tinyget gets the servers name or IP in the –srv parameter and then the actual URI in the –uri. I have specified what’s the HTTP response code to expect in –status parameter. It ensures the site is alive and is returning http 200 code. Besides just warming up a site, you can do some load test on the site. Tinyget can run in multiple threads and run loops to hit some URL. You can literally blow up a site with commands like this: "%TINYGET%" -threads:30 -loop:100 -srv:google.com -uri:http://www.google.com/ -status:200 Tinyget is also pretty useful to run automated tests. You can record http posts in a text file and then use it to make http posts to some page. Then you can put matching clause to check for certain string in the output to ensure the correct response is given. Thus with some simple command line commands, you can warm up, do some transactions, validate the site is giving off correct response as well as run a load test to ensure the server performing well. Very cheap way to get a lot done.

    Read the article

  • OAuth with RestSharp in Windows Phone

    - by midoBB
    Nearly every major API provider uses OAuth for the user authentication and while it is easy to understand the concept, using it in a Windows Phone app isn’t pretty straightforward. So for this quick tutorial we will be using RestSharp for WP7 and the API from getglue.com (an entertainment site) to authorize the user. So the first step is to get the OAuth request token and then we redirect our browserControl to the authorization URL private void StartLogin() {   var client = new RestClient("https://api.getglue.com/"); client.Authenticator = OAuth1Authenticator.ForRequestToken("ConsumerKey", "ConsumerSecret"); var request = new RestRequest("oauth/request_token"); client.ExecuteAsync(request, response => { _oAuthToken = GetQueryParameter(response.Content, "oauth_token"); _oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"); string authorizeUrl = "http://getglue.com/oauth/authorize" + "?oauth_token=" + _oAuthToken + "&style=mobile"; Dispatcher.BeginInvoke(() => { browserControl.Navigate(new Uri(authorizeUrl)); }); }); } private static string GetQueryParameter(string input, string parameterName) { foreach (string item in input.Split('&')) { var parts = item.Split('='); if (parts[0] == parameterName) { return parts[1]; } } return String.Empty; } Then we listen to the browser’s Navigating Event private void Navigating(Microsoft.Phone.Controls.NavigatingEventArgs e) { if (e.Uri.AbsoluteUri.Contains("oauth_callback")) { var arguments = e.Uri.AbsoluteUri.Split('?'); if (arguments.Length < 1) return; GetAccessToken(arguments[1]); } } private void GetAccessToken(string uri) { var requestToken = GetQueryParameter(uri, "oauth_token"); var client = new RestClient("https://api.getglue.com/"); client.Authenticator = OAuth1Authenticator.ForAccessToken(ConsumerKey, ConsumerSecret, _oAuthToken, _oAuthTokenSecret); var request = new RestRequest("oauth/access_token"); client.ExecuteAsync(request, response => { AccessToken = GetQueryParameter(response.Content, "oauth_token"); AccessTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"); UserId = GetQueryParameter(response.Content, "glue_userId"); }); } Now to test it we can access the user’s friends list var client = new RestClient("http://api.getglue.com/v2"); client.Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, GAccessToken, AccessTokenSecret); var request = new RestRequest("/user/friends"); request.AddParameter("userId", UserId,ParameterType.GetOrPost); // request.AddParameter("category", "all",ParameterType.GetOrPost); client.ExecuteAsync(request, response => { TreatFreindsList(); }); And that’s it now we can access all OAuth methods using RestSharp.

    Read the article

  • Interfacing HTTPBuilder and HTMLUnit... some code

    - by Misha Koshelev
    Ok, this isn't even a question: import com.gargoylesoftware.htmlunit.HttpMethod import com.gargoylesoftware.htmlunit.WebClient import com.gargoylesoftware.htmlunit.WebResponseData import com.gargoylesoftware.htmlunit.WebResponseImpl import com.gargoylesoftware.htmlunit.util.Cookie import com.gargoylesoftware.htmlunit.util.NameValuePair import static groovyx.net.http.ContentType.TEXT import java.io.File import java.util.logging.Logger import org.apache.http.impl.cookie.BasicClientCookie /** * HTTPBuilder class * * Allows Javascript processing using HTMLUnit * * @author Misha Koshelev */ class HTTPBuilder { /** * HTTP Builder - implement this way to avoid underlying logging output */ def httpBuilder /** * Logger */ def logger /** * Directory for storing HTML files, if any */ def saveDirectory=null /** * Index of current HTML file in directory */ def saveIdx=1 /** * Current page text */ def text=null /** * Response for processJavascript (Complex Version) */ def resp=null /** * URI for processJavascript (Complex Version) */ def uri=null /** * HttpMethod for processJavascript (Complex Version) */ def method=null /** * Default constructor */ public HTTPBuilder() { // New HTTPBuilder httpBuilder=new groovyx.net.http.HTTPBuilder() // Logging logger=Logger.getLogger(this.class.name) } /** * Constructor that allows saving output files for testing */ public HTTPBuilder(saveDirectory,saveIdx) { this() this.saveDirectory=saveDirectory this.saveIdx=saveIdx } /** * Save text and return corresponding XmlSlurper object */ public saveText() { if (saveDirectory) { def file=new File(saveDirectory.toString()+File.separator+saveIdx+".html") logger.finest "HTTPBuilder.saveText: file=\""+file.toString()+"\"" file<<text saveIdx++ } new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text) } /** * Wrapper around supertype get method */ public Object get(Map<String,?> args) { logger.finer "HTTPBuilder.get: args=\""+args+"\"" args.contentType=TEXT httpBuilder.get(args) { resp,reader-> text=reader.text this.resp=resp this.uri=args.uri this.method=HttpMethod.GET saveText() } } /** * Wrapper around supertype post method */ public Object post(Map<String,?> args) { logger.finer "HTTPBuilder.post: args=\""+args+"\"" args.contentType=TEXT httpBuilder.post(args) { resp,reader-> text=reader.text this.resp=resp this.uri=args.uri this.method=HttpMethod.POST saveText() } } /** * Load cookies from specified file */ def loadCookies(file) { logger.finer "HTTPBuilder.loadCookies: file=\""+file.toString()+"\"" file.withObjectInputStream { ois-> ois.readObject().each { cookieMap-> def cookie=new BasicClientCookie(cookieMap.name,cookieMap.value) cookieMap.remove("name") cookieMap.remove("value") cookieMap.entrySet().each { entry-> cookie."${entry.key}"=entry.value } httpBuilder.client.cookieStore.addCookie(cookie) } } } /** * Save cookies to specified file */ def saveCookies(file) { logger.finer "HTTPBuilder.saveCookies: file=\""+file.toString()+"\"" def cookieMaps=new ArrayList(new LinkedHashMap()) httpBuilder.client.cookieStore.getCookies().each { cookie-> def cookieMap=[:] cookieMap.version=cookie.version cookieMap.name=cookie.name cookieMap.value=cookie.value cookieMap.domain=cookie.domain cookieMap.path=cookie.path cookieMap.expiryDate=cookie.expiryDate cookieMaps.add(cookieMap) } file.withObjectOutputStream { oos-> oos.writeObject(cookieMaps) } } /** * Process Javascript using HTMLUnit (Simple Version) */ def processJavascript() { logger.finer "HTTPBuilder.processJavascript (Simple)" def webClient=new WebClient() def tempFile=File.createTempFile("HTMLUnit","") tempFile<<text def page=webClient.getPage("file://"+tempFile.toString()) webClient.waitForBackgroundJavaScript(10000) text=page.asXml() webClient.closeAllWindows() tempFile.delete() saveText() } /** * Process Javascript using HTMLUnit (Complex Version) * Closure, if specified, used to determine presence of necessary elements */ def processJavascript(closure) { logger.finer "HTTPBuilder.processJavascript (Complex)" // Convert response headers def headers=new ArrayList() resp.allHeaders.each() { header-> headers.add(new NameValuePair(header.name,header.value)) } def responseData=new WebResponseData(text.bytes,resp.statusLine.statusCode,resp.statusLine.toString(),headers) def response=new WebResponseImpl(responseData,uri.toURL(),method,0) // Transfer cookies def webClient=new WebClient() httpBuilder.client.cookieStore.getCookies().each { cookie-> webClient.cookieManager.addCookie(new Cookie(cookie.domain,cookie.name,cookie.value,cookie.path,cookie.expiryDate,cookie.isSecure())) } def page=webClient.loadWebResponseInto(response,webClient.getCurrentWindow()) // Wait for condition if (closure) { for (i in 1..20) { if (closure(page)) { break; } synchronized(page) { page.wait(500); } } } // Return text text=page.asXml() webClient.closeAllWindows() saveText() } } Allows one to interface HTTPBuilder with HTMLUnit! Enjoy Misha

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >