Search Results

Search found 12933 results on 518 pages for 'wikipedia api'.

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

  • Android Google-Shopping API force closes while parsing

    - by Sam Jackson
    I'm trying to send a request to the Google-Shopping API with the following static method which I think is working: public static String GET_TITLE(String url) throws JSONException { InputStream is = null; String result = ""; JSONObject jArray = null; // http post try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection "+e.toString()); } The URL I'm passing is this BTW: https://www.googleapis.com/shopping/search/v1/public/products/country=US&q=shirts&alt=json &rankBy=relevancy&key=AIzaSyDRKgGmJrdG6pV6DIg2m-nmIbXydxvpjww Next I try to parse this response (where I think the problem comes in) in the same method: try { jArray = new JSONObject(result); } catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } JSONObject itemObject = jArray.getJSONObject("items"); JSONObject productObject = itemObject.getJSONObject("product"); String attributeGoogleId = productObject.getString("googleId"); String attributeProviderId = productObject.getString("providerId"); String attributeTitle = productObject.getString("title");*/ String attributePrice = productObject.getString("price"); JSONObject popupObject = productObject.getJSONObject("popup"); return attributeTitle; } This has been so frustrating, I know it should be simple but everywhere I look I just can't quite get it to work, I'm not exactly sure what the error is since I'm testing it on my HTC Desire because my emulator gives an 'invalid command-line parameter' error when starting, but that's a different issue, anyway, thanks in advance! EDIT: The first one makes it look like there's a problem with the URL, should I change it and see if it makes a difference? 04-01 12:09:05.142: ERROR/log_tag(24968): Error in http connection java.net.UnknownHostException: www.googleapis.com 04-01 12:09:05.142: ERROR/log_tag(24968): Error converting result java.lang.NullPointerException 04-01 12:09:05.142: ERROR/log_tag(24968): Error parsing data org.json.JSONException: End of input at character 0 of 04-01 12:09:05.142: DEBUG/AndroidRuntime(24968): Shutting down VM 04-01 12:09:05.142: WARN/dalvikvm(24968): threadid=1: thread exiting with uncaught exception (group=0x400259f8) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): FATAL EXCEPTION: main 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }} to activity {com.spectrum.stock/com.spectrum.stock.CaptureActivity}: java.lang.NullPointerException 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.ActivityThread.deliverResults(ActivityThread.java:3734) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.ActivityThread.access$2800(ActivityThread.java:135) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2166) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.os.Handler.dispatchMessage(Handler.java:99) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.os.Looper.loop(Looper.java:144) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.ActivityThread.main(ActivityThread.java:4937) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at java.lang.reflect.Method.invokeNative(Native Method) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at java.lang.reflect.Method.invoke(Method.java:521) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at dalvik.system.NativeStart.main(Native Method) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): Caused by: java.lang.NullPointerException 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at com.spectrum.stock.JSONResponse.GET_TITLE(JSONResponse.java:61) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at com.spectrum.stock.CaptureActivity.onActivityResult(CaptureActivity.java:78) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.Activity.dispatchActivityResult(Activity.java:3931) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): at android.app.ActivityThread.deliverResults(ActivityThread.java:3730) 04-01 12:09:05.152: ERROR/AndroidRuntime(24968): ... 11 more 04-01 12:09:05.162: WARN/ActivityManager(96): Force finishing activity com.spectrum.stock/.CaptureActivity

    Read the article

  • Redirected wikipedia request

    - by Le_Coeur
    Hi people, i need to write a program, that can redirect's http://localhost:8080 to en.wikipedia.org, it seems to be easy, but i have some problems(only with wikipedia with another sites works good). I make url to wikipedia: URL url = new URL("http", "en.wikipedia.org", 80, "/wiki"); than URLConnection, extract headers, and when i want connection.getInputStream(), i received message 404 Not Found. So i have tried some hack for host header, because in this way host header is localhost:8080, therefor i have tried to change host header to wikipedia, and it works, but after request in browser http://localhost:8080 wikipedia opens, but url in browser changes to en.wikipedia.org, but i want proceed with localhost :)

    Read the article

  • When to use HTTP status code 404 in an API

    - by Sybiam
    I am working on a project and after arguing with people at work for about more than a hour. I decided to know what people on stack-exchange might say. We're writing an API for a system, there is a query that should return a tree of Organization or a tree of Goals. The tree of Organization is the organization in which the user is present, In other words, this tree should always exists. In the organization, a tree of goal should be always present. (that's where the argument started). In case where the tree doesn't exist, my co-worker decided that it would be right to answer response with status code 200. And then started asking me to fix my code because the application was falling apart when there is no tree. I'll try to spare flames and fury. I suggested to raise a 404 error when there is no tree. It would at least let me know that something is wrong. When using 200, I have to add special check to my response in the success callback to handle errors. I'm expecting to receive an object, but I may actually receive an empty response because nothing is found. It sounds totally fair to mark the response as a 404. And then war started and I got the message that I didn't understand HTTP status code schema. So I'm here and asking what's wrong with 404 in this case? I even got the argument "It found nothing, so it's right to return 200". I believe that it's wrong since the tree should be always present. If we found nothing and we are expecting something, it should be a 404. More info, I forgot to add the urls that are fetched. Organizations /OrgTree/Get Goals /GoalTree/GetByDate?versionDate=... /GoalTree/GetById?versionId=... My mistake, both parameters are required. If any versionDate that can be parsed to a date is provided, it will return the closes revision. If you enter something in the past, it will return the first revision. If by Id with a id that doesn't exists, I suspect it's going to return an empty response with 200. Extra Also, I believe the best answer to the problem is to create default objects when organizations are created, having no tree shouldn't be a valid case and should be seen as an undefined behavior. There is no way an account can be used without both trees. For that reasons, they should be always present. also I got linked this (one similar but I can't find it) http://viswaug.files.wordpress.com/2008/11/http-headers-status1.png

    Read the article

  • Should I use my own public API on my site (via JS)?

    - by newboyhun
    First of all, this question is far more different other 'public api questions' like this: Should a website use its own public API?, second, sorry for my English. You can find the question summarized at the bottom of this question. What I want to achieve is a big website with a public api, so who like programming (like me) and likes my website, can replicate my website's data with a much better approach (of course with some restrictions). Almost everything could be used by the public API. Because of this, I was thinking about making the whole website AJAX driven. There would be parts of the API which would be limited only to my website (domain), like login, registering. There would be only an INTERFACE on the client side, which would use the public and private API to make this interface working. The website would be ONLY CLIENT SIDE, well, I mean, the website would only use AJAX to use the api. How do I imagine this? The website would be like a mobile application, the application only sending a request to a webserver, which returns a json, the application parses it, and uses it to advance in the application. (e.g.: login) My thoughts: Pros: The whole website is built up by javascript, this means I don't need to transfer the html to the client, saving bandwidth. (I hope so) Anyone can use up the data of my website to make their own cool things. (Is this a con or pro? O_O) The public API is always in use, so I can see if there are any error. Cons: Without Javascript the website is unusable. The bad guys easily can load the server with requesting too much data (like Request Per Second 10000), but this can be countered via limiting this with some PHP code and logging. Probably much more work So the question in some words is: Should I build my website around my own api? Is it good to work only on the client side? Is this good for a big website? (e.x.: facebook, yeah facebook is a different story, but could it run with an 'architecture' like this?)

    Read the article

  • Is there a codeigniter api reference?

    - by ajsie
    whenever using a framework it's so good with a api reference so you could lookup the classes' methods and properties, which class they extend from and so on. is there a api reference for codeigniter similar to yii's excellent api referenc? http://www.yiiframework.com/doc/api/ how else could you know more about the details about the classes if there isn't a good api reference. java's api reference is also great: http://java.sun.com/j2se/1.4.2/docs/api/ why can't i find codeigniter's. thanks.

    Read the article

  • Implementing synchronous MediaTypeFormatters in ASP.NET Web API

    - by cibrax
    One of main characteristics of MediaTypeFormatter’s in ASP.NET Web API is that they leverage the Task Parallel Library (TPL) for reading or writing an model into an stream. When you derive your class from the base class MediaTypeFormatter, you have to either implement the WriteToStreamAsync or ReadFromStreamAsync methods for writing or reading a model from a stream respectively. These two methods return a Task, which internally does all the serialization work, as it is illustrated bellow. public abstract class MediaTypeFormatter { public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext); public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger); }   .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } However, most of the times, serialization is a safe operation that can be done synchronously. In fact, many of the serializer classes you will find in the .NET framework only provide sync methods. So the question is, how you can transform that synchronous work into a Task ?. Creating a new task using the method Task.Factory.StartNew for doing all the serialization work would be probably the typical answer. That would work, as a new task is going to be scheduled. However, that might involve some unnecessary context switches, which are out of our control and might be affect performance on server code specially.   If you take a look at the source code of the MediaTypeFormatters shipped as part of the framework, you will notice that they actually using another pattern, which uses a TaskCompletionSource class. public Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) {   var tsc = new TaskCompletionSource<AsyncVoid>(); tsc.SetResult(default(AsyncVoid));   //Do all the serialization work here synchronously   return tsc.Task; }   /// <summary> /// Used as the T in a "conversion" of a Task into a Task{T} /// </summary> private struct AsyncVoid { } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } They are basically doing all the serialization work synchronously and using a TaskCompletionSource for returning a task already done. To conclude this post, this is another approach you might want to consider when using serializers that are not compatible with an async model. Update: Henrik Nielsen from the ASP.NET team pointed out the existence of a built-in media type formatter for writing sync formatters. BufferedMediaTypeFormatter http://t.co/FxOfeI5x

    Read the article

  • Pan point on Google Map to specific pixel position on screen (API v3)

    - by Jake
    When overlay is a Google maps overlay and offsetx, offsety is the pixel distance from the maps center that I want to pan latlong to, the following works. var projection = overlay.getProjection(); var pxlocation = projection.fromLatLngToContainerPixel(latlong); map.panTo(projection.fromContainerPixelToLatLng(new google.maps.Point(pxlocation.x+offsetx,pxlocation.y+offsety))); However, I don't always have an overlay on the map and map.getProjection() returns a projection, not a MapCanvasProjection which does not have the methods I need. Is there a way to do this without making an overlay specificaly for it?

    Read the article

  • gdata api + javascript library for accessing documents?

    - by user246114
    Hi, I wanted to do the following with the gdata javascript library: get a list of a user's documents. read the contents of a chosen document. edit its contents, update the document. If I'm reading correctly, this is not supported by the javascript library? I got this to work with the java library, but would like to push this functionality to the client. Is it possible? If not, are there any ways around it? Thank you

    Read the article

  • Using Gdata Calendar API for PHP App to create a calender system with event ownership

    - by linuxlover101
    Hello, I'm working on a PHP app, and I'm trying to find the best way to set up a calendar system. First let me describe the intended function of the system: The application has multiple users who can login simultaneously. Each user should be able to add their own events and display them on their "profile." Also, on another page, the events should be able to be shown all together (from all users) and from each individual users exclusively. Since Google Calendar has a nice calendar-looking interface, I thought I would work with the GData APIs. Originally, I thought this would make things easier. But then it seems that if I want to represent event ownership, either each user would have to have a google account or somehow they all would each have to have a separate calendar. Thus, the application would have to create the calendar (if it does not exist) and be able to edit only their calendar. Two questions: Can I somehow use the GData APIs to accomplish my goal? (Mainly event ownership.) Should I just create my own calendar like application? Thanks!

    Read the article

  • youtube python api gdata.service. requesterror

    - by nashr rafeeg
    i have the following code which is trying to add a set of videos into a youtube play list import urllib,re import gdata.youtube import gdata.youtube.service class reddit(): def __init__(self, rssurl ='http://www.reddit.com/r/chillmusic.rss' ): self.URL = rssurl self._downloadrss() def _downloadrss(self): if self.URL.endswith('.rss'): # Downloadd the RSS feed of the subreddit - save as "feed.rss" try: print "Downloading rss from reddit..." urllib.urlretrieve (URL, "feed.rss") except Exception as e: print e def clean(self): playList = open("feed.rss").read() links = re.findall(r'(http?://www.youtube.com\S+)', playList) for link in links: firstPass = link.replace('&quot;&gt;[link]&lt;/a&gt;', '') secondPass = firstPass.replace('&amp;amp;fmt=18', '') thirdpass = secondPass.replace('&amp;amp;feature=related', '') finalPass = thirdpass.replace('http://www.youtube.com/watch?v=', '') print thirdpass, "\t Extracted: ", finalPass return finalPass class google(): def __init__(self, username, password): self.Username = username self.password = password #do not change any of the following self.key = 'AI39si5DDjGYhG_1W-8n_amjgEjbOU27sa0aw2RQI5gOaoK5KqCD2Fzffbkh8oqGu7CqFQLLQ7N7wK0gz7lrTQbd70srC72Niw' self.appname = 'Reddit playlist maker' self.service = gdata.youtube.service.YouTubeService() def authenticate(self): self.service.email = self.Username self.service.password = self.password self.service.developer_key = self.key self.service.client_id = self.appname self.service.source = self.appname self.service.ssl = False self.service.ProgrammaticLogin() def get_playlists(self): y_playlist = self.service.GetYouTubePlaylistFeed(username='default') l = [] k = [] for p in y_playlist.entry: k=[] k=[p.link[1].href, p.title.text] l.append(k) return l def get_playlist_id_from_url(self, href): #quick and dirty method to get the playList id's return href.replace('http://www.youtube.com/view_play_list?p=','') def creat_playlist(self, name="Reddit list", disc ="videos from reddit"): playlistentry = self.service.AddPlaylist(name, disc) if isinstance(playlistentry, gdata.youtube.YouTubePlaylistEntry): print 'New playlist added' return playlistentry.link[1].href def add_video_to_playlist(self,playlist_uri,video): video_entry = self.service.AddPlaylistVideoEntryToPlaylist( playlist_uri, video) if isinstance(video_entry, gdata.youtube.YouTubePlaylistVideoEntry): print 'Video added' URL = "http://www.reddit.com/r/chillmusic.rss" r = reddit(URL) g = google('[email protected]', 'xxxx') g.authenticate() def search_playlist(playlist="Reddit list3"): pl_id = None for pl in g.get_playlists(): if pl[1] == playlist: pl_id = pl[0] print pl_id break if pl_id == None: pl_id = g.creat_playlist(name=playlist) return pl_id pls = search_playlist() for video_id in r.clean(): g.add_video_to_playlist(pls, video_id) when i run the code i am geting the following error message gdata.service.RequestError: {'status': 303, 'body': '', 'reason': 'See Other'} any one have any idea why i am getting this error cheers Nash

    Read the article

  • google maps api v2 - tens of thousands of markers

    - by Adam
    Hello, my problem is with XXk (aka XX000) markers, atm I have 7k markers and will be more, and more, problem is in marker database, because atm this is 4MB (link to my DB http://tinyurl.com/ybau9ce) and problem is, how load that fast? for example DOWNLOAD only this what are show now, DOWNLOAD because load I have with ClusterMarker and problem is not with java but with download that database I think...

    Read the article

  • gdata youtube api 302 'The document has moved'

    - by zalew
    I'm trying to get YouTube feeds with the python gdata library. Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, and any other) I get: RequestError: {'status': 302, 'body': '<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE></HEAD><BODY>\n<H1>302 Moved</H1>\nThe document has moved\n<A HREF="http://www.google.com">here</A>.\r\n</BODY></HTML>\r\n', 'reason': 'Redirect received, but redirects_remaining <= 0'} 302 to 'google.com'??? I've even tried to do something from the google online tutorials and I get the same error. What's going on?

    Read the article

  • Google Maps iPhone API Terrain View

    - by Adam
    We're using MapKit on an iPhone app to display a Google Map with terrain view. However, the terrain view only shows when the user has an active Internet connection, the moment the user's Internet is off, the terrain on the map disappears and it appears flat. Is there any way to keep the terrain view on even when the user isn't on an active internet connection? Thanks! Adam

    Read the article

  • Google Place API marker issue

    - by user2959740
    I am creating itinerary planner like http://www.plnnr.com I want to create Google Place marker by direction(North,East,west,south) for e.g. When people select 4 day it should show attraction for 1st day all north location 2nd day east location then south and west. How to i do the auto marker. I am not sure how plnnr.com works how they are generating the lines based on direction. Please anyone help me on this.

    Read the article

  • Google Maps API v3 - Directions/Paths breaking KML Overlay Infowindows

    - by Douglas
    I'm in the end stages before content filling and then production on the Google Maps project I've been working on. A number of bugs and such have been thwarted, but this latest one has me relatively stumped. The demo map can be viewed here: http://dougglover.com/samples/finalProduct/ Everything works fine until you create a path using the Directions section(not to be confused with Get Directions). To reproduce the problem, play around with the map, click on a building or two, just to see the functionality. After ensuring that clicking on a building works(brings up an infowindow), choose two buildings to get directions to in the Directions area. It works great with the routing algorithm I've implemented, and the paths show up nicely, and intelligently. The problem being that you can't click buildings anymore to see their info. I'm assuming it has something to do with the z-index error popping up in the console, but I'm not sure how to handle that if it is the problem. Any guidance is greatly appreciated. :)

    Read the article

  • Faster, Simpler access to Azure Tables with Enzo Azure API

    - by Herve Roggero
    After developing the latest version of Enzo Cloud Backup I took the time to create an API that would simplify access to Azure Tables (the Enzo Azure API). At first, my goal was to make the code simpler compared to the Microsoft Azure SDK. But as it turns out it is also a little faster; and when using the specialized methods (the fetch strategies) it is much faster out of the box than the Microsoft SDK, unless you start creating complex parallel and resilient routines yourself. Last but not least, I decided to add a few extension methods that I think you will find attractive, such as the ability to transform a list of entities into a DataTable. So let’s review each area in more details. Simpler Code My first objective was to make the API much easier to use than the Azure SDK. I wanted to reduce the amount of code necessary to fetch entities, remove the code needed to add automatic retries and handle transient conditions, and give additional control, such as a way to cancel operations, obtain basic statistics on the calls, and control the maximum number of REST calls the API generates in an attempt to avoid throttling conditions in the first place (something you cannot do with the Azure SDK at this time). Strongly Typed Before diving into the code, the following examples rely on a strongly typed class called MyData. The way MyData is defined for the Azure SDK is similar to the Enzo Azure API, with the exception that they inherit from different classes. With the Azure SDK, classes that represent entities must inherit from TableServiceEntity, while classes with the Enzo Azure API must inherit from BaseAzureTable or implement a specific interface. // With the SDK public class MyData1 : TableServiceEntity {     public string Message { get; set; }     public string Level { get; set; }     public string Severity { get; set; } } //  With the Enzo Azure API public class MyData2 : BaseAzureTable {     public string Message { get; set; }     public string Level { get; set; }     public string Severity { get; set; } } Simpler Code Now that the classes representing an Azure Table entity are defined, let’s review the methods that the Azure SDK would look like when fetching all the entities from an Azure Table (note the use of a few variables: the _tableName variable stores the name of the Azure Table, and the ConnectionString property returns the connection string for the Storage Account containing the table): // With the Azure SDK public List<MyData1> FetchAllEntities() {      CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);      CloudTableClient tableClient = storageAccount.CreateCloudTableClient();      TableServiceContext serviceContext = tableClient.GetDataServiceContext();      CloudTableQuery<MyData1> partitionQuery =         (from e in serviceContext.CreateQuery<MyData1>(_tableName)         select new MyData1()         {            PartitionKey = e.PartitionKey,            RowKey = e.RowKey,            Timestamp = e.Timestamp,            Message = e.Message,            Level = e.Level,            Severity = e.Severity            }).AsTableServiceQuery<MyData1>();        return partitionQuery.ToList();  } This code gives you automatic retries because the AsTableServiceQuery does that for you. Also, note that this method is strongly-typed because it is using LINQ. Although this doesn’t look like too much code at first glance, you are actually mapping the strongly-typed object manually. So for larger entities, with dozens of properties, your code will grow. And from a maintenance standpoint, when a new property is added, you may need to change the mapping code. You will also note that the mapping being performed is optional; it is desired when you want to retrieve specific properties of the entities (not all) to reduce the network traffic. If you do not specify the properties you want, all the properties will be returned; in this example we are returning the Message, Level and Severity properties (in addition to the required PartitionKey, RowKey and Timestamp). The Enzo Azure API does the mapping automatically and also handles automatic reties when fetching entities. The equivalent code to fetch all the entities (with the same three properties) from the same Azure Table looks like this: // With the Enzo Azure API public List<MyData2> FetchAllEntities() {        AzureTable at = new AzureTable(_accountName, _accountKey, _ssl, _tableName);        List<MyData2> res = at.Fetch<MyData2>("", "Message,Level,Severity");        return res; } As you can see, the Enzo Azure API returns the entities already strongly typed, so there is no need to map the output. Also, the Enzo Azure API makes it easy to specify the list of properties to return, and to specify a filter as well (no filter was provided in this example; the filter is passed as the first parameter).  Fetch Strategies Both approaches discussed above fetch the data sequentially. In addition to the linear/sequential fetch methods, the Enzo Azure API provides specific fetch strategies. Fetch strategies are designed to prepare a set of REST calls, executed in parallel, in a way that performs faster that if you were to fetch the data sequentially. For example, if the PartitionKey is a GUID string, you could prepare multiple calls, providing appropriate filters ([‘a’, ‘b’[, [‘b’, ‘c’[, [‘c’, ‘d[, …), and send those calls in parallel. As you can imagine, the code necessary to create these requests would be fairly large. With the Enzo Azure API, two strategies are provided out of the box: the GUID and List strategies. If you are interested in how these strategies work, see the Enzo Azure API Online Help. Here is an example code that performs parallel requests using the GUID strategy (which executes more than 2 t o3 times faster than the sequential methods discussed previously): public List<MyData2> FetchAllEntitiesGUID() {     AzureTable at = new AzureTable(_accountName, _accountKey, _ssl, _tableName);     List<MyData2> res = at.FetchWithGuid<MyData2>("", "Message,Level,Severity");     return res; } Faster Results With Sequential Fetch Methods Developing a faster API wasn’t a primary objective; but it appears that the performance tests performed with the Enzo Azure API deliver the data a little faster out of the box (5%-10% on average, and sometimes to up 50% faster) with the sequential fetch methods. Although the amount of data is the same regardless of the approach (and the REST calls are almost exactly identical), the object mapping approach is different. So it is likely that the slight performance increase is due to a lighter API. Using LINQ offers many advantages and tremendous flexibility; nevertheless when fetching data it seems that the Enzo Azure API delivers faster.  For example, the same code previously discussed delivered the following results when fetching 3,000 entities (about 1KB each). The average elapsed time shows that the Azure SDK returned the 3000 entities in about 5.9 seconds on average, while the Enzo Azure API took 4.2 seconds on average (39% improvement). With Fetch Strategies When using the fetch strategies we are no longer comparing apples to apples; the Azure SDK is not designed to implement fetch strategies out of the box, so you would need to code the strategies yourself. Nevertheless I wanted to provide out of the box capabilities, and as a result you see a test that returned about 10,000 entities (1KB each entity), and an average execution time over 5 runs. The Azure SDK implemented a sequential fetch while the Enzo Azure API implemented the List fetch strategy. The fetch strategy was 2.3 times faster. Note that the following test hit a limit on my network bandwidth quickly (3.56Mbps), so the results of the fetch strategy is significantly below what it could be with a higher bandwidth. Additional Methods The API wouldn’t be complete without support for a few important methods other than the fetch methods discussed previously. The Enzo Azure API offers these additional capabilities: - Support for batch updates, deletes and inserts - Conversion of entities to DataRow, and List<> to a DataTable - Extension methods for Delete, Merge, Update, Insert - Support for asynchronous calls and cancellation - Support for fetch statistics (total bytes, total REST calls, retries…) For more information, visit http://www.bluesyntax.net or go directly to the Enzo Azure API page (http://www.bluesyntax.net/EnzoAzureAPI.aspx). About Herve Roggero Herve Roggero, Windows Azure MVP, is the founder of Blue Syntax Consulting, a company specialized in cloud computing products and services. Herve's experience includes software development, architecture, database administration and senior management with both global corporations and startup companies. Herve holds multiple certifications, including an MCDBA, MCSE, MCSD. He also holds a Master's degree in Business Administration from Indiana University. Herve is the co-author of "PRO SQL Azure" from Apress and runs the Azure Florida Association (on LinkedIn: http://www.linkedin.com/groups?gid=4177626). For more information on Blue Syntax Consulting, visit www.bluesyntax.net.

    Read the article

  • Web Crawler for Learnign Topics on Wikipedia

    - by Chris Okyen
    When I want to learn a vast topic on wikipedia, I don't know where to start. For instance say I want to learn about Binary Stars, I then have to know other things linked on that pages and linked pages on all the linked pages and so on for the specified number of levels. I want to write a web crawler like HTTracker or something similiar, that will display a heiarchy of the links on a certain page and the links on those linked pages.I wish to use as much prewritten code as possible. Here is an example: Pretending we are bending the rules by grabing links from only the first sentence of each pages The example archives and "processes" two levels deep The page is Ternary operation The First Level In mathematics a ternary operation is an N-ary operation The Second Level Under Mathmatics: Mathematics (from Greek µ???µa máthema, “knowledge, study, learning”) is the abstract study of topics encompassing quantity, structure, space, change and others; it has no generally accepted definition. Under N-ary In logic,mathematics, and computer science, the arity i/'ær?ti/ of a function or operation is the number of arguments or operands that the function takes Under Operation In its simplest meaning in mathematics and logic, an operation is an action or procedure which produces a new value from one or more input values ------------------------------------------------------------------------- I need some way to determine what oder to approach all these wiki pages to learn the concept ( in this case ternary operations )... Following along with this exmpakle, one way to show the path to read would a printout flowout like so: This shows that the first sentence of the Mathematics page doesn't link to the first sentence of pages linked on ternary page two levels deep. (Please tell me how I should explain this ) --- In otherwords, the child node of the top pages first sentence, ternary_operation, does not have any child nodes that reference the children of the top pages other children nodes- N-ary and operation. Thus it is safe to read this first. Since N-ary has a link to operations we shoudl read the operation page second and finally read the N-ary page last. Again, I wish to use as much prewritten code as possible, and was wondering what language to use and what would be the simpliest way to go about doing this if there isn't already somethign out there? Thank You!

    Read the article

  • Doing unit and integration tests with the Web API HttpClient

    - by cibrax
    One of the nice things about the new HttpClient in System.Net.Http is the support for mocking responses or handling requests in a http server hosted in-memory. While the first option is useful for scenarios in which we want to test our client code in isolation (unit tests for example), the second one enables more complete integration testing scenarios that could include some more components in the stack such as model binders or message handlers for example.   The HttpClient can receive a HttpMessageHandler as argument in one of its constructors. public class HttpClient : HttpMessageInvoker { public HttpClient(); public HttpClient(HttpMessageHandler handler); public HttpClient(HttpMessageHandler handler, bool disposeHandler); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } For the first scenario, you can create a new HttpMessageHandler that fakes the response, which you can use in your unit test. The only requirement is that you somehow inject an HttpClient with this custom handler in the client code. public class FakeHttpMessageHandler : HttpMessageHandler { HttpResponseMessage response; public FakeHttpMessageHandler(HttpResponseMessage response) { this.response = response; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } In an unit test, you can do something like this. var fakeResponse = new HttpResponse(); var fakeHandler = new FakeHttpMessageHandler(fakeResponse); var httpClient = new HttpClient(fakeHandler); var customerService = new CustomerService(httpClient); // Do something // Asserts .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } CustomerService in this case is the class under test, and the one that receives an HttpClient initialized with our fake handler. For the second scenario in integration tests, there is a In-Memory host “System.Web.Http.HttpServer” that also derives from HttpMessageHandler and you can use with a HttpClient instance in your test. This has been discussed already in these two great posts from Pedro and Filip. 

    Read the article

  • Eloqua API Full Code Example in JAVA

    - by Shawn Spencer
    Is there anyone out there who has mastered to retrieve some data programmatically from Eloqua? First of all, I'm more or less a newbie, as far as JAVA. I can follow tutorials, take directions and will Google till my fingers bleed. I understand the basics and am slightly familiar with OOP. My main problem is that I have a Friday deadline (and tomorrow is Thanksgiving). At any rate, all the Eloqua code snippets (that I've been able to find) illustrate one aspect of a specific issue, and that's it. In my case, I would greatly appreciate a JAVA project of some sort, with all the necessary files to do web services (WSDL, SOAP and perhaps WSIT) and the main class and all that included. No, I don't want you to do my work for me! Just give me enough to find my way around, enter the information I need to retrieve and all that. I'll take it from there. Any pointers, links or suggestions?

    Read the article

  • Searching for an online shop accessible via API

    - by Simon A. Eugster
    I need an online shop with a custom interface (customizing items with Ajax, with a preview included). Writing it myself does not make too much sense (implementing all the payment options etc.), so I would like to use an existing online shop (OpenSource). I would like to build my own UI which, for example, tells the shop to add an item to its cart -- i.e. without using the online shop's native UI. More precisely, it should be an online gallery where the user can directly order an image if he likes it. The final checkout/payment page can be native again. Is there a shop system that supports this? Or is it still faster to write it on my own? Or are there better options?

    Read the article

  • Web api authentication techniques

    - by Steve
    We have a asp.net MVC web service framework for serving out xml/json for peoples Get requests but are struggling to figure out the best way (fast, easy, trivial for users coding with javascript or OO languages) to authenticate users. It's not that our data is sensitive or anything, we just want users to register so we can have their email address to notify them of changes and track usage. In our previous attempt we had the username in the URI and would just make sure that username existed and increment db tables with usage. This was super basic but we'd notice people using demo as a username etc so we need it to be a little more sophisticated. What authentication techniques are available? What do the major players use/do.

    Read the article

  • Using Dynamic LINQ to get a filter for my Web API

    - by Espo
    We are considering using the Dynamic.CS linq-sample included in the "Samples" directory of visual studio 2008 for our WebAPI project to allow clients to query our data. The interface would be something like this (In addition to the normal GET-methods): public HttpResponseMessage List(string filter = null); The plan is to use the dynamic library to parse the "filter"-variable and then execute the query agains the DB. Any thoughts if this is a good idea? Is it a security problem?

    Read the article

  • How to learn an API

    - by inovaovao
    When I find some interesting project (e.g. on GitHub) I often would like to use it and try it out to see how it works, but if there isn't a good documentation or some kind of tutorial it's hard to figure out how to use it. So my question is: how do you approach such a situation? How do you figure out which classes are important and how to chain them to put them to use? What would you look at first? An advice I found is to look at the tests (if there are any). But if there are unit tests for every class, how do you know which ones to look at first?

    Read the article

  • Wikipedia A* pathfinding algorithm takes a lot of time

    - by Vee
    I've successfully implemented A* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same. The map is 80x80, and there are 10-11 nodes. I took the pseudocode from here Wikipedia And this is my implementation: public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd) { mMap.ClearNodes(); mMap.GetTile(mStart.X, mStart.Y).Value = 0; mMap.GetTile(mEnd.X, mEnd.Y).Value = 0; List<PGNode> openNodes = new List<PGNode>(); List<PGNode> closedNodes = new List<PGNode>(); List<PGNode> solutionNodes = new List<PGNode>(); mStart.G = 0; mStart.H = GetManhattanHeuristic(mStart, mEnd); solutionNodes.Add(mStart); solutionNodes.Add(mEnd); openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list. while (openNodes.Count > 0) // 2) Repeat the following: { openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F)); PGNode current = openNodes[0]; // a) We refer to this as the current square.) if (current == mEnd) { while (current != null) { solutionNodes.Add(current); current = current.Parent; } return solutionNodes; } openNodes.Remove(current); closedNodes.Add(current); // b) Switch it to the closed list. List<PGNode> neighborNodes = current.GetNeighborNodes(); double cost = 0; bool isCostBetter = false; for (int i = 0; i < neighborNodes.Count; i++) { PGNode neighbor = neighborNodes[i]; cost = current.G + 10; isCostBetter = false; if (neighbor.Passable == false || closedNodes.Contains(neighbor)) continue; // If it is not walkable or if it is on the closed list, ignore it. if (openNodes.Contains(neighbor) == false) { openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list. isCostBetter = true; } else if (cost < neighbor.G) { isCostBetter = true; } if (isCostBetter) { neighbor.Parent = current; // Make the current square the parent of this square. neighbor.G = cost; neighbor.H = GetManhattanHeuristic(current, neighbor); } } } return null; } Here's the heuristic I'm using: private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd) { return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y); } What am I doing wrong? It's an entire day I keep looking at the same code.

    Read the article

  • Bitbucket API authentication with Python's HTTPBasicAuthHandler

    - by jbochi
    I'm trying to get the list of issues on a private repository using bitbucket's API. I have confirmed that HTTP Basic authentication works with hurl, but I am unable to authenticate in Python. Adapting the code from this tutorial, I have written the following script. import cookielib import urllib2 class API(): api_url = 'http://api.bitbucket.org/1.0/' def __init__(self, username, password): self._opener = self._create_opener(username, password) def _create_opener(self, username, password): cj = cookielib.LWPCookieJar() cookie_handler = urllib2.HTTPCookieProcessor(cj) password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, self.api_url, username, password) auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(cookie_handler, auth_handler) return opener def get_issues(self, username, repository): query_url = self.api_url + 'repositories/%s/%s/issues/' % (username, repository) try: handler = self._opener.open(query_url) except urllib2.HTTPError, e: print e.headers raise e return handler.read() api = API(username='my_username', password='XXXXXXXX') api.get_issues('my_username', 'my_repository') results in: >>> Server: nginx/0.7.62 Date: Mon, 19 Apr 2010 16:15:06 GMT Content-Type: text/plain Connection: close Vary: Authorization,Cookie Content-Length: 9 Traceback (most recent call last): File "C:/USERS/personal/bitbucket-burndown/bitbucket-api.py", line 29, in <module> print api.get_issues('my_username', 'my_repository') File "C:/USERS/personal/bitbucket-burndown/bitbucket-api.py", line 25, in get_issues raise e HTTPError: HTTP Error 401: UNAUTHORIZED api.get_issues('jespern', 'bitbucket') works like a charm. What's wrong with my code?

    Read the article

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