Search Results

Search found 242 results on 10 pages for 'urlencode'.

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

  • can't the asp file system object access shares server paths?

    - by sushant
    i am using this code to access files and folders. <%@ Language=VBScript %><% option explicit dim sRoot, sDir, sParent, objFSO, objFolder, objFile, objSubFolder, sSize %> <META content="Microsoft Visual Studio 6.0" name=GENERATOR><!-- Author: Adrian Forbes --> <% sRoot = "D:Raghu" sDir = Request("Dir") sDir = sDir & "\" Response.Write "<h1>" & sDir & "</h1>" & vbCRLF Set objFSO = CreateObject("Scripting.FileSystemObject") on error resume next Set objFolder = objFSO.GetFolder(sRoot & sDir) if err.number <> 0 then Response.Write "Could not open folder" Response.End end if on error goto 0 sParent = objFSO.GetParentFolderName(objFolder.Path) ' Remove the contents of sRoot from the front. This gives us the parent ' path relative to the root folder ' eg. if parent folder is "c:webfilessubfolder1subfolder2" then we just want "subfolder1subfolder2" sParent = mid(sParent, len(sRoot) + 1) Response.Write "<table border=""1"">" ' Give a link to the parent folder. This is just a link to this page only pssing in ' the new folder as a parameter Response.Write "<tr><td colspan=3><a href=""browse.asp?dir=" & Server.URLEncode(sParent) & """>Parent folder</a></td></tr>" & vbCRLF ' Now we want to loop through the subfolders in this folder For Each objSubFolder In objFolder.SubFolders ' And provide a link to them Response.Write "<tr><td colspan=3><a href=""browse.asp?dir=" & Server.URLEncode(sDir & objSubFolder.Name) & """>" & objSubFolder.Name & "</a></td></tr>" & vbCRLF Next ' Now we want to loop through the files in this folder For Each objFile In objFolder.Files if Clng(objFile.Size) < 1024 then sSize = objFile.Size & " bytes" else sSize = Clng(objFile.Size / 1024) & " KB" end if ' And provide a link to view them. This is a link to show.asp passing in the directory and the file ' as parameters Response.Write "<tr><td><a href=""show.asp?file=" & server.URLEncode(objFile.Name) & "&dir=" & server.URLEncode (sDir) & """>" & objFile.Name & "</a></td><td>" & sSize & "</td><td>" & objFile.Type & "</td></tr>" & vbCRLF Next Response.Write "</table>" %> it works fine. but when i try to access something on shred path like: "\\cvrdd0110:share" it gives error. how to access these files? and sorry for formatting issues.

    Read the article

  • can't the asp file system object access shared server paths?

    - by sushant
    i am using this code to access files and folders. <%@ Language=VBScript %><% option explicit dim sRoot, sDir, sParent, objFSO, objFolder, objFile, objSubFolder, sSize %> <META content="Microsoft Visual Studio 6.0" name=GENERATOR><!-- Author: Adrian Forbes --> <% sRoot = "D:Raghu" sDir = Request("Dir") sDir = sDir & "\" Response.Write "<h1>" & sDir & "</h1>" & vbCRLF Set objFSO = CreateObject("Scripting.FileSystemObject") on error resume next Set objFolder = objFSO.GetFolder(sRoot & sDir) if err.number <> 0 then Response.Write "Could not open folder" Response.End end if on error goto 0 sParent = objFSO.GetParentFolderName(objFolder.Path) ' Remove the contents of sRoot from the front. This gives us the parent ' path relative to the root folder ' eg. if parent folder is "c:webfilessubfolder1subfolder2" then we just want "subfolder1subfolder2" sParent = mid(sParent, len(sRoot) + 1) Response.Write "<table border=""1"">" ' Give a link to the parent folder. This is just a link to this page only pssing in ' the new folder as a parameter Response.Write "<tr><td colspan=3><a href=""browse.asp?dir=" & Server.URLEncode(sParent) & """>Parent folder</a></td></tr>" & vbCRLF ' Now we want to loop through the subfolders in this folder For Each objSubFolder In objFolder.SubFolders ' And provide a link to them Response.Write "<tr><td colspan=3><a href=""browse.asp?dir=" & Server.URLEncode(sDir & objSubFolder.Name) & """>" & objSubFolder.Name & "</a></td></tr>" & vbCRLF Next ' Now we want to loop through the files in this folder For Each objFile In objFolder.Files if Clng(objFile.Size) < 1024 then sSize = objFile.Size & " bytes" else sSize = Clng(objFile.Size / 1024) & " KB" end if ' And provide a link to view them. This is a link to show.asp passing in the directory and the file ' as parameters Response.Write "<tr><td><a href=""show.asp?file=" & server.URLEncode(objFile.Name) & "&dir=" & server.URLEncode (sDir) & """>" & objFile.Name & "</a></td><td>" & sSize & "</td><td>" & objFile.Type & "</td></tr>" & vbCRLF Next Response.Write "</table>" %> it works fine. but when i try to access something on shared path like: "\\cvrdd0110:share" it gives error. how to access these files? and sorry for formatting issues.

    Read the article

  • Setting up and using Bing Translate API Service for Machine Translation

    - by Rick Strahl
    Last week I spent quite a bit of time trying to set up the Bing Translate API service. I can honestly say this was one of the most screwed up developer experiences I've had in a long while - specifically related to the byzantine sign up process that Microsoft has in place. Not only is it nearly impossible to find decent documentation on the required signup process, some of the links in the docs are just plain wrong, and some of the account pages you need to access the actual account information once signed up are not linked anywhere from the administration UI. To make things even harder is the fact that the APIs changed a while back, with a completely new authentication scheme that's described and not directly linked documentation topic also made for a very frustrating search experience. It's a bummer that this is the case too, because the actual API itself is easy to use and works very well - fast and reasonably accurate (as accurate as you can expect machine translation to be). But the sign up process is a pain in the ass doubtlessly leaving many people giving up in frustration. In this post I'll try to hit all the points needed to set up to use the Bing Translate API in one place since such a document seems to be missing from Microsoft. Hopefully the API folks at Microsoft will get their shit together and actually provide this sort of info on their site… Signing Up The first step required is to create a Windows Azure MarketPlace account. Go to: https://datamarket.azure.com/ Sign in with your Windows Live Id If you don't have an account you will be taken to a registration page which you have to fill out. Follow the links and complete the registration. Once you're signed in you can start adding services. Click on the Data Link on the main page Select Microsoft Translator from the list This adds the Microsoft Bing Translator to your services. Pricing The page shows the pricing matrix and the free service which provides 2 megabytes for translations a month for free. Prices go up steeply from there. Pricing is determined by actual bytes of the result translations used. Max translations are 1000 characters so at minimum this means you get around 2000 translations a month for free. However most translations are probable much less so you can expect larger number of translations to go through. For testing or low volume translations this should be just fine. Once signed up there are no further instructions and you're left in limbo on the MS site. Register your Application Once you've created the Data association with Translator the next step is registering your application. To do this you need to access your developer account. Go to https://datamarket.azure.com/developer/applications/register Provide a ClientId, which is effectively the unique string identifier for your application (not your customer id!) Provide your name The client secret was auto-created and this becomes your 'password' For the redirect url provide any https url: https://microsoft.com works Give this application a description of your choice so you can identify it in the list of apps Now, once you've registered your application, keep track of the ClientId and ClientSecret - those are the two keys you need to authenticate before you can call the Translate API. Oddly the applications page is hidden from the Azure Portal UI. I couldn't find a direct link from anywhere on the site back to this page where I can examine my developer application keys. To find them you can go to: https://datamarket.azure.com/developer/applications You can come back here to look at your registered applications and pick up the ClientID and ClientSecret. Fun eh? But we're now ready to actually call the API and do some translating. Using the Bing Translate API The good news is that after this signup hell, using the API is pretty straightforward. To use the translation API you'll need to actually use two services: You need to call an authentication API service first, before you can call the actual translator API. These two APIs live on different domains, and the authentication API returns JSON data while the translator service returns XML. So much for consistency. Authentication The first step is authentication. The service uses oAuth authentication with a  bearer token that has to be passed to the translator API. The authentication call retrieves the oAuth token that you can then use with the translate API call. The bearer token has a short 10 minute life time, so while you can cache it for successive calls, the token can't be cached for long periods. This means for Web backend requests you typically will have to authenticate each time unless you build a more elaborate caching scheme that takes the timeout into account (perhaps using the ASP.NET Cache object). For low volume operations you can probably get away with simply calling the auth API for every translation you do. To call the Authentication API use code like this:/// /// Retrieves an oAuth authentication token to be used on the translate /// API request. The result string needs to be passed as a bearer token /// to the translate API. /// /// You can find client ID and Secret (or register a new one) at: /// https://datamarket.azure.com/developer/applications/ /// /// The client ID of your application /// The client secret or password /// public string GetBingAuthToken(string clientId = null, string clientSecret = null) { string authBaseUrl = https://datamarket.accesscontrol.windows.net/v2/OAuth2-13; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) { ErrorMessage = Resources.Resources.Client_Id_and_Client_Secret_must_be_provided; return null; } var postData = string.Format("grant_type=client_credentials&client_id={0}" + "&client_secret={1}" + "&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret)); // POST Auth data to the oauth API string res, token; try { var web = new WebClient(); web.Encoding = Encoding.UTF8; res = web.UploadString(authBaseUrl, postData); } catch (Exception ex) { ErrorMessage = ex.GetBaseException().Message; return null; } var ser = new JavaScriptSerializer(); var auth = ser.Deserialize<BingAuth>(res); if (auth == null) return null; token = auth.access_token; return token; } private class BingAuth { public string token_type { get; set; } public string access_token { get; set; } } This code basically takes the client id and secret and posts it at the oAuth endpoint which returns a JSON string. Here I use the JavaScript serializer to deserialize the JSON into a custom object I created just for deserialization. You can also use JSON.NET and dynamic deserialization if you are already using JSON.NET in your app in which case you don't need the extra type. In my library that houses this component I don't, so I just rely on the built in serializer. The auth method returns a long base64 encoded string which can be used as a bearer token in the translate API call. Translation Once you have the authentication token you can use it to pass to the translate API. The auth token is passed as an Authorization header and the value is prefixed with a 'Bearer ' prefix for the string. Here's what the simple Translate API call looks like:/// /// Uses the Bing API service to perform translation /// Bing can translate up to 1000 characters. /// /// Requires that you provide a CLientId and ClientSecret /// or set the configuration values for these two. /// /// More info on setup: /// http://www.west-wind.com/weblog/ /// /// Text to translate /// Two letter culture name /// Two letter culture name /// Pass an access token retrieved with GetBingAuthToken. /// If not passed the default keys from .config file are used if any /// public string TranslateBing(string text, string fromCulture, string toCulture, string accessToken = null) { string serviceUrl = "http://api.microsofttranslator.com/V2/Http.svc/Translate"; if (accessToken == null) { accessToken = GetBingAuthToken(); if (accessToken == null) return null; } string res; try { var web = new WebClient(); web.Headers.Add("Authorization", "Bearer " + accessToken); string ct = "text/plain"; string postData = string.Format("?text={0}&from={1}&to={2}&contentType={3}", HttpUtility.UrlEncode(text), fromCulture, toCulture, HttpUtility.UrlEncode(ct)); web.Encoding = Encoding.UTF8; res = web.DownloadString(serviceUrl + postData); } catch (Exception e) { ErrorMessage = e.GetBaseException().Message; return null; } // result is a single XML Element fragment var doc = new XmlDocument(); doc.LoadXml(res); return doc.DocumentElement.InnerText; } The first of this code deals with ensuring the auth token exists. You can either pass the token into the method manually or let the method automatically retrieve the auth code on its own. In my case I'm using this inside of a Web application and in that situation I simply need to re-authenticate every time as there's no convenient way to manage the lifetime of the auth cookie. The auth token is added as an Authorization HTTP header prefixed with 'Bearer ' and attached to the request. The text to translate, the from and to language codes and a result format are passed on the query string of this HTTP GET request against the Translate API. The translate API returns an XML string which contains a single element with the translated string. Using the Wrapper Methods It should be pretty obvious how to use these two methods but here are a couple of test methods that demonstrate the two usage scenarios:[TestMethod] public void TranslateBingWithAuthTest() { var translate = new TranslationServices(); string clientId = DbResourceConfiguration.Current.BingClientId; string clientSecret = DbResourceConfiguration.Current.BingClientSecret; string auth = translate.GetBingAuthToken(clientId, clientSecret); Assert.IsNotNull(auth); string text = translate.TranslateBing("Hello World we're back home!", "en", "de",auth); Assert.IsNotNull(text, translate.ErrorMessage); Console.WriteLine(text); } [TestMethod] public void TranslateBingIntegratedTest() { var translate = new TranslationServices(); string text = translate.TranslateBing("Hello World we're back home!","en","de"); Assert.IsNotNull(text, translate.ErrorMessage); Console.WriteLine(text); } Other API Methods The Translate API has a number of methods available and this one is the simplest one but probably also the most common one that translates a single string. You can find additional methods for this API here: http://msdn.microsoft.com/en-us/library/ff512419.aspx Soap and AJAX APIs are also available and documented on MSDN: http://msdn.microsoft.com/en-us/library/dd576287.aspx These links will be your starting points for calling other methods in this API. Dual Interface I've talked about my database driven localization provider here in the past, and it's for this tool that I added the Bing localization support. Basically I have a localization administration form that allows me to translate individual strings right out of the UI, using both Google and Bing APIs: As you can see in this example, the results from Google and Bing can vary quite a bit - in this case Google is stumped while Bing actually generated a valid translation. At other times it's the other way around - it's pretty useful to see multiple translations at the same time. Here I can choose from one of the values and driectly embed them into the translated text field. Lost in Translation There you have it. As I mentioned using the API once you have all the bureaucratic crap out of the way calling the APIs is fairly straight forward and reasonably fast, even if you have to call the Auth API for every call. Hopefully this post will help out a few of you trying to navigate the Microsoft bureaucracy, at least until next time Microsoft upends everything and introduces new ways to sign up again. Until then - happy translating… Related Posts Translation method Source on Github Translating with Google Translate without Google API Keys Creating a data-driven ASP.NET Resource Provider© Rick Strahl, West Wind Technologies, 2005-2013Posted in Localization  ASP.NET  .NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Generate unique hashes for django models

    - by becomingGuru
    I want to use unique hashes for each model rather than ids. I implemented the following function to use it across the board easily. import random,hashlib from base64 import urlsafe_b64encode def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False): while 1: uuid_number = str(random.random())[2:] uuid = hashlib.sha256(uuid_number).hexdigest() if use_sha else uuid_number uuid = uuid[:length] if urlencode: uuid = urlsafe_b64encode(uuid)[:-1] hash_id_dict = {field_name:uuid} try: model_object.__class__.objects.get(**hash_id_dict) except model_object.__class__.DoesNotExist: setattr(model_object,field_name,uuid) return I'm seeking feedback, how else could I do it? How can I improve it? What is good bad and ugly about it?

    Read the article

  • CURL login by script to a Joomla website

    - by Paryeshakaya
    Hello, I need to login by a PHP script that uses CURL to a Joomla website, in order to access to a private page that needs to be processed, but nothwithstanding several attempts I have done, I have always a 403 error. I have done a similar thing with other websites and it worked. Script I use: $uname = "id"; $upswd = "pswd"; $url = "http://www.somewebpage.com"; $agent = "'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6'"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE ); curl_setopt($ch, CURLOPT_COOKIEJAR, './cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, './cookie.txt'); curl_setopt($ch, CURLOPT_USERAGENT, $agent ); curl_setopt($ch, CURLOPT_HEADER, TRUE ); curl_setopt($ch, CURLOPT_REFERER, $url1); // POST fields $postfields = array(); $postfields['username'] = urlencode($uname); $postfields['passwd'] = urlencode($upswd); $postfields['remember'] = 'yes'; $postfields['option'] = 'login'; $postfields['op2'] = 'login'; $postfields['return'] = urlencode($url); $postfields['message'] = '0'; $postfields['force_session'] = '1'; $postfields['j3b00d36f4336137f4f03335c5eee6440'] = '1'; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $ret = curl_exec($ch); The username and password, as well as the website URL I am using are perfectly working. This is the result I get: HTTP/1.1 100 Continue HTTP/1.1 403 Forbidden Date: Sat, 06 Feb 2010 08:29:36 GMT Server: Apache/2.2.13 (Unix) mod_ssl/2.2.13 OpenSSL/0.9.7a DAV/2 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 X-Powered-By: PHP/5.2.10 Connection: close Transfer-Encoding: chunked Content-Type: text/html Is there something wrong in my CURL request? Or is there a limit with Joomla remote login? Thanks for suggestions!

    Read the article

  • python urllib post question

    - by paul
    hello ALL im making some simple python post script but it not working well. there is 2 part to have to login. first login is using 'http://mybuddy.buddybuddy.co.kr/userinfo/UserInfo.asp' this one. and second login is using 'http://user.buddybuddy.co.kr/usercheck/UserCheckPWExec.asp' i can login first login page, but i couldn't login second page website. and return some error 'illegal access' such like . i heard this is related with some cooke but i don't know how to implement to resolve this problem. if anyone can help me much appreciated!! Thanks! import re,sys,os,mechanize,urllib,time import datetime,socket params = urllib.urlencode({'ID':'ph896011', 'PWD':'pk1089' }) rq = mechanize.Request("http://mybuddy.buddybuddy.co.kr/userinfo/UserInfo.asp", params) rs = mechanize.urlopen(rq) data = rs.read() logged_fail = r';history.back();</script>' in data if not logged_fail: print 'login success' try: params = urllib.urlencode({'PASSWORD':'pk1089'}) rq = mechanize.Request("http://user.buddybuddy.co.kr/usercheck/UserCheckPWExec.asp", params ) rs = mechanize.urlopen(rq) data = rs.read() print data except: print 'error'

    Read the article

  • Best practise when using httplib2.Http() object

    - by tomaz
    I'm writing a pythonic web API wrapper with a class like this import httplib2 import urllib class apiWrapper: def __init__(self): self.http = httplib2.Http() def _http(self, url, method, dict): ''' Im using this wrapper arround the http object all the time inside the class ''' params = urllib.urlencode(dict) response, content = self.http.request(url,params,method) as you can see I'm using the _http() method to simplify the interaction with the httplib2.Http() object. This method is called quite often inside the class and I'm wondering what's the best way to interact with this object: create the object in the __init__ and then reuse it when the _http() method is called (as shown in the code above) or create the httplib2.Http() object inside the method for every call of the _http() method (as shown in the code sample below) import httplib2 import urllib class apiWrapper: def __init__(self): def _http(self, url, method, dict): '''Im using this wrapper arround the http object all the time inside the class''' http = httplib2.Http() params = urllib.urlencode(dict) response, content = http.request(url,params,method)

    Read the article

  • Help with OpenSSL request using Python

    - by Ldn
    Hi i'm creating a program that has to make a request and then obtain some info. For doing that the website had done some API that i will use. There is an how-to about these API but every example is made using PHP. But my app is done using Python so i need to convert the code. here is the how-to: The request string is sealed with OpenSSL. The steps for sealing are as follows: • Random 128-bit key is created. • Random key is used to RSA-RC4 symettrically encrypt the request string. • Random key is encrypted with the public key using OpenSSL RSA asymmetrical encryption. • The encrypted request and encrypted key are each base64 encoded and placed in the appropriate fields. In PHP a full request to our API can be accomplished like so: <?php // initial request. $request = array('object' => 'Link', 'action' => 'get', 'args' => array( 'app_id' => 303612602 ) ); // encode the request in JSON $request = json_encode($request); // when you receive your profile, you will be given a public key to seal your request in. $key_pem = "-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALdu5C6d2sA1Lu71NNGBEbLD6DjwhFQO VLdFAJf2rOH63rG/L78lrQjwMLZOeHEHqjaiUwCr8NVTcVrebu6ylIECAwEAAQ== -----END PUBLIC KEY-----"; // load the public key $pkey = openssl_pkey_get_public($key_pem); // seal! $newrequest and $enc_keys are passed by reference. openssl_seal($request, $enc_request, $enc_keys, array($pkey)); // then wrap the request $wrapper = array( 'profile' => 'ProfileName', 'format' => 'RSA_RC4_Sealed', 'enc_key' => base64_encode($enc_keys[0]), 'request' => base64_encode($enc_request) ); // json encode the wrapper. urlencode it as well. $wrapper = urlencode(json_encode($wrapper)); // we can send the request wrapper via the cURL extension $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://api.site.com/'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); curl_close($ch); ?> Of all of that, i was able to convert "$request" and i'v also made the JSON encode. This is my code: import urllib import urllib2 import json url = 'http://api.site.com/' array = {'app_id' : "303612602"} values = { "object" : "Link", "action": "get", "args" : array } data = urllib.urlencode(values) json_data = json.dumps(data) What stop me is the sealing with OpenSSL and the publi key (that obviously i have) Using PHP OpenSSL it's so easy, but in Python i don't really know how to use it Please, help me!

    Read the article

  • gae error when i login.

    - by zjm1126
    i am using http://code.google.com/p/gaema/source/browse/#hg/demos/webapp, and this is my traceback: Traceback (most recent call last): File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 510, in __call__ handler.get(*groups) File "D:\gaema\demos\webapp\main.py", line 31, in get google_auth.get_authenticated_user(self._on_auth) File "D:\gaema\demos\webapp\gaema\auth.py", line 641, in get_authenticated_user OpenIdMixin.get_authenticated_user(self, callback) File "D:\gaema\demos\webapp\gaema\auth.py", line 83, in get_authenticated_user url = self._OPENID_ENDPOINT + "?" + urllib.urlencode(args) File "D:\Python25\lib\urllib.py", line 1250, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) how to do this thanks ??????????????? ???????? ??????????? ?????????????? ???????

    Read the article

  • urlopen error [errno 111] connection refused

    - by Ui-Gyun Jeong
    I am doing python exercise with a book 'headfirst python' and making android app by using python and sl4a my code is import android import json import time from urllib import urlencode from urllib2 import urlopen hello_msg = "Welcome to Coach Kelly's Timing App" list_title = 'Here is your list of athletes:' quit_msg = "Quitting Coach Kelly's App." web_server = 'http://127.0.0.1:8080' get_names_cgi = '/cgi-bin/generate_name.py' def send_to_server(url, post_data=None): if post_data: page = urlopen(url, urlencode(post_data)) else: page = urlopen(url) return(page.read().decode("utf8")) app = android.Android() def status_update(msg, how_long=2): app.makeToast(msg) time.sleep(how_long) status_update(hello_msg) athlete_names = sorted(json.loads(send_to_server(web_server + get_names_cgi))) app.dialogCreateAlert(list_title) app.dialogSetSingleChoiceItems(athlete_names) app.dialogSetPositiveButtonText('Select') app.dialogSetNegativeButtonText('Quit') app.dialogShow() resp = app.dialogGetResponse().result status_update(quit_msg) this is my code and the result is what is the problem??? I can not figure out what the problem is...

    Read the article

  • "digg" button and encoded url :S

    - by guest86
    Hi! I wrote a php site (it's still a prototype) and i placed a "Digg" button. Placing the button was easy but.... Official manual says "url has to be encoded". I did that with urlencode(). After urlencode, my url looks like this: http%3A%2F%2Fwww.mysite.com%2Fen%2Fredirect.php%3Fl%3Dhttp%3A%2F%2Fwww.othersite.rs%2FNews%2FWorld%2F227040%2FRusia-Airplane-crashed%26N%3DRusia%3A+Airplane+crashed So far, so good but when i want to submit that url to digg, it is recognized as invalid url: http://www.mysite.com/en/redirect.php?l=http://www.othersite.rs/News/World/227040/Rusia-Airplane-crashed&N=Rusia:+Airplane crashed If i place a "+" between "Airplane" and "crashed" (mere end of a link), then digg recognize it without any problems! Please help, this bizare problem is killing my braincells! P.S. for purpose of this answer urls are changed (nonexisting) because, in original, non-english sites are involved P.S.S. Happy New Year! :)

    Read the article

  • to avoid page refresh during button click event in asp.net

    - by ush
    public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) // If page loads for first time { Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); // Assign the Session["update"] with unique value //=============== Page load code ========================= //============== End of Page load code =================== } } protected void Button1_Click(object sender, EventArgs e) { if (Session["update"].ToString() == ViewState["update"].ToString()) // If page not Refreshed { //=============== On click event code ========================= Label1.Text = TextBox1.Text; //lblDisplayAddedName.Text = txtName.Text; //=============== End of On click event code ================== // After the event/ method, again update the session Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); } else // If Page Refreshed { // Do nothing } } protected override void OnPreRender(EventArgs e) { ViewState["update"] = Session["update"]; } } this is not working for high resolution gradient background

    Read the article

  • c# WebRequest to connect to wikipedia API

    - by NickJ
    Hey, This may be a pathetically simple problem but I cannot seem to format the post webrequest/response to get data from the wikipedia api. I have posted my code below if anyone can help me see my problem. string pgTitle = txtPageTitle.Text; Uri address = new Uri("http://en.wikipedia.org/w/api.php"); HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string action = "query"; string query = pgTitle; StringBuilder data = new StringBuilder(); data.Append("action=" + HttpUtility.UrlEncode(action)); data.Append("&query=" + HttpUtility.UrlEncode(query)); byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); request.ContentLength = byteData.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); divWikiData.InnerText = reader.ReadToEnd(); }

    Read the article

  • FileNet P8 workplace token issue in C#

    - by acadia
    Hello, I am trying to get user token and build the URL so that user need not login everytime they click the file. below is my code. My question is do I need to pass whole of the token value shown below or?? The token value I am getting is symmetric:algorithm:QUVT:keyid:NTZkYTNkNmI=:data:7P9aJHzkfGTOlwtotuWGaMqfU9COECscA9yxMdK64ZLa298A3tsGlHKHDFp0cH+gn/SiMrwKfbWNZybPXaltgo5e4H4Ak8KUiCRKWfS68qhmjfw69qPv9ib96vL3TzNORYFpp/hrwvp8aX4CQIZlBA== The problem is, once i copy the URL and past it in the browser, it is taking me to the login page. Though I am not getting any errors, it should take users directly to the imageviewer but instead it takes me to login page, if I login it is opening the file correctly. What am I doing wrong? string text = ""; string userName = "userName"; string pwd = "*****"; fileNetID = "{5FCE7E04-3D74-4A93-AA53-26C12A2FD4FC}"; Uri uri = null; string workplaceURL = "http://filenet:9081/WorkPlaceXT"; uri = new Uri(workplaceURL + "/setCredentials?op=getUserToken&userId=" + this.encodeLabel(userName) + "&password=" + this.encodeLabel(pwd) + "&verify=true"); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(uri); System.Net.WebResponse webResponse = webRequest.GetResponse(); StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()); String token = streamReader.ReadToEnd(); string contentURL = string.Empty; contentURL = workplaceURL + "/getContent?objectType=document&impersonate=true&objectStoreName=OBJECTSTORE&id=" + HttpUtility.UrlEncode(fileNetID); contentURL += "&ut=" + HttpUtility.UrlEncode(encodeLabel(token)); return contentURL;

    Read the article

  • Making HTTP POST request

    - by infrared
    I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' }) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("bkstr.com:80") conn.request("POST", "/webapp/wcs/stores/servlet/BuybackSearch", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read() conn.close() When I try from a browser, from this page: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackMaterialsView?langId=-1&catalogId=10001&storeId=10051&schoolStoreId=15828 , it works. What am I missing in my code? Thanks EDIT: Here's what I get when I call print response.msg 302 Moved Date: Tue, 07 Sep 2010 16:54:29 GMT Vary: Host,Accept-Encoding,User-Agent Location: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Content-Type: text/plain; charset=utf-8 Seems that the location points to the same url I'm trying to access in the first place? EDIT2: I've tried using urllib2 as suggested here. Here is the code: import urllib, urllib2 url = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch' values = {'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) print response.geturl() print response.info() the_page = response.read() print the_page And here is the output: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch Date: Tue, 07 Sep 2010 16:58:35 GMT Pragma: No-cache Cache-Control: no-cache Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: JSESSIONID=0001REjqgX2axkzlR6SvIJlgJkt:1311s25dm; Path=/ Vary: Accept-Encoding,User-Agent X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Connection: close Content-Type: text/html; charset=utf-8 Content-Language: en-US Set-Cookie: TSde3575=225ec58bcb0fdddfad7332c2816f1f152224db2f71e1b0474c866f3b; Path=/

    Read the article

  • how can i insert a new sitemap with google gdata api? it returns 400 bad request

    - by wingoo
    i try to insert a new sitemap to google using api, but i can't do it successful-_- this is the method var fullDomainUrl = "http://www.example.com/"; var entry = new SitemapsEntry(); entry.Id = new AtomId(fullDomainUrl + "sitemap.xml"); entry.Categories.Add(new AtomCategory("http://schemas.google.com/webmasters/tools/2007#site-info", new AtomUri("http://schemas.google.com/g/2005#kind"))); entry.SitemapType = "WEB"; myService.Insert(new Uri(string.Format("https://www.google.com/webmasters/tools/feeds/{0}/sitemaps/", HttpUtility.UrlEncode(fullDomainUrl))), entry); this will retuen a 400 bad requestand i try another method var settings = new RequestSettings("TesterApp1", domain.GoogleAuthToken, CommonService.GetRsaPrivateKey(Context)); var request = new WebmasterToolsRequest(settings); var sitemap = new Sitemap(); sitemap.Id = fullDomainUrl + "sitemap.xml"; sitemap.Categories.Add(new AtomCategory("http://schemas.google.com/webmasters/tools/2007#site-info", new AtomUri("http://schemas.google.com/g/2005#kind"))); sitemap.SitemapType = "WEB"; //request.AddSitemap(fullDomainUrl, sitemap); request.Insert(new Uri(string.Format("https://www.google.com/webmasters/tools/feeds/{0}/sitemaps/", HttpUtility.UrlEncode(fullDomainUrl))), sitemap); this also return a 400 bad request and then i try to use HttpWebRequest to post the atom to google,but it also return a 400 bad request(???") i can insert/update site successful,but can;t insert a new sitemap.. does any can give a right code with .net?

    Read the article

  • Wordpress creating plugin for most viewed posts problem?

    - by user303832
    Hello,I just want to create plugin that will when visitor(user,visitor,...) visit some post,remember what post,and to increment counter of that post,I wrote this code,but sometimes,counter is incremented,even post isn't viewed,or post with other Id is added to a table.Can someone help me with this,please.I know that there are plugins for this that I'm trying to do,but still want to write this plugin. function IncrementPostCount($the_content) { global $post; global $wpdb; if(($post->post_status == 'publish') && (int)$post->ID) { if(is_single()) { // just for single post - not for page $postID = (int)$post->ID; $postTitle = urlencode($post->post_title); $postLink = urlencode(get_permalink($post->ID)); $oneRow = $wpdb->get_row("SELECT * FROM wp_postovi WHERE postAjDi='$postID'"); if(empty ($oneRow)) { $postCounter = 1; $data_array = array( 'readnTimes' => $postCounter, 'linkPost'=>$postLink, 'TitlePost'=>$postTitle, 'postAjDi'=>$postID); $wpdb->insert('wp_najcitaniji_postovi', $data_array); } else { $postCounter = intval($oneRow->readnTimes) + 1; $data_array = array('readnTimes' => $postCounter); $where_array = array('postAjDi'=>intval($oneRow->postAjDi)); $wpdb->update('wp_postovi',$data_array,$where_array); } return $the_content; } return $the_content; } } add_filter('the_content','IncrementPostCount'); Sorry on my bad english,tnx in advance.

    Read the article

  • White space problem while using php proxy

    - by KCC
    Hi, I'm using a php web proxy with my URL already encoded and keep having getting a malformed request error once I have any text after a %20. Any idea why this would be happening? The web proxy code I'm using is just a sample that I took from yahoo services: <?php // PHP Proxy example for Yahoo! Web services. // Responds to both HTTP GET and POST requests // // Author: Jason Levitt // December 7th, 2005 // // Allowed hostname (api.local and api.travel are also possible here) define ('HOSTNAME', 'http://search.yahooapis.com/'); // Get the REST call path from the AJAX application // Is it a POST or a GET? $path = ($_POST['yws_path']) ? $_POST['yws_path'] : $_GET['yws_path']; $url = HOSTNAME.$path; // Open the Curl session $session = curl_init($url); // If it's a POST, put the POST data in the body if ($_POST['yws_path']) { $postvars = ''; while ($element = current($_POST)) { $postvars .= urlencode(key($_POST)).'='.urlencode($element).'&'; next($_POST); } curl_setopt ($session, CURLOPT_POST, true); curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars); } // Don't return HTTP headers. Do return the contents of the call curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // Make the call $xml = curl_exec($session); // The web service returns XML. Set the Content-Type appropriately //header("Content-Type: text/xml"); echo $xml; curl_close($session); ?>

    Read the article

  • POST variables to web server?

    - by OverTheRainbow
    Hello I've been trying several things from Google to POST data to a web server, but none of them work: I'm still stuck at how to convert the variables into the request, considering that the second variable is an SQL query so it has spaces. Does someone know the correct way to use a WebClient to POST data? I'd rather use WebClient because it requires less code than HttpWebRequest/HttpWebResponse. Here's what I tried so far: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc = New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim postData = String.Format("db={0}&query={1}", _ HttpUtility.UrlEncode("books.sqlite"), _ HttpUtility.UrlEncode("SELECT id,title FROM boooks")) 'Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", postData) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub Dim client = New WebClient() Dim nv As New Collection nv.Add("db", "books.sqlite") nv.Add("query", "SELECT id,title FROM books") Dim address As New Uri("http://localhost:9999/get") 'Dim bytRetData As Byte() = client.UploadValues(address, "POST", nv) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub 'Dim wc As New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query 'Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", bytArguments) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub End Sub Thank you.

    Read the article

  • P0ST variables to web server?

    - by OverTheRainbow
    Hello I've been trying several things from Google to POST data to a web server, but none of them work: I'm still stuck at how to convert the variables into the request, considering that the second variable is an SQL query so it has spaces. Does someone know the correct way to use a WebClient to POST data? I'd rather use WebClient because it requires less code than HttpWebRequest/HttpWebResponse. Here's what I tried so far: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc = New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim postData = String.Format("db={0}&query={1}", _ HttpUtility.UrlEncode("books.sqlite"), _ HttpUtility.UrlEncode("SELECT id,title FROM boooks")) 'Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", postData) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub Dim client = New WebClient() Dim nv As New Collection nv.Add("db", "books.sqlite") nv.Add("query", "SELECT id,title FROM books") Dim address As New Uri("http://localhost:9999/get") 'Dim bytRetData As Byte() = client.UploadValues(address, "POST", nv) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub 'Dim wc As New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query 'Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", bytArguments) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub End Sub Thank you.

    Read the article

  • Test if string is URL encoded in PHP

    - by Psytronic
    Hey guys, I've looked through the PHP Docs and can't see anything to do with this, so how can I test if a string is URL encoded? Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded, or use something like this which I've made function is_urlEncoded($string){ $test_string = $string; while(urldecode($test_string) != $test_string){ $test_string = urldecode($test_string); } return (urlencode($test_string) == $string)?True:False; } $t = "Hello World how are you?"; if(is_urlEncoded($sreq)){ print "Was Encoded.\n"; }else{ print "Not Encoded.\n"; print "Should be ".urlencode($sreq)."\n"; } Which works, however not in instances where this might occur $t = "Hello%2BWorld%2B%253E%2Bhow%2Bare%2Byou%253F"; I.e. where the string has been doubly encoded, or maybe this string $t = "Hello+World%2B%253E%2Bhow%2Bare%2Byou%253F"; I.e. where most has been doubly encoded, except for one space. (Yes I don't know when this string would ever occur, but you never know)

    Read the article

  • Fails proceeding after POSTing to web server

    - by OverTheRainbow
    Hello According to this question, it seems like the error "Too many automatic redirections were attempted" is caused when forgetting to use a cookiecontainer to connect to a web server that uses cookies to keep track of the user. However, even though I used "request.CookieContainer = MyCookieContainer", I'm still getting into an endless loop that is terminated by VB Express with this error message. Imports System.IO Imports System.Net 'Remember to add reference to System.Web DLL Imports System.Web Imports System.Text Public Class Form1 Const ConnectURL = "http://www.acme.com/logon.php" Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim request As HttpWebRequest = WebRequest.Create(ConnectURL) 'Build POST data request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" Dim Data As New StringBuilder Data.Append("Account=" + HttpUtility.UrlEncode("jdoe")) Data.Append("&Password=" + HttpUtility.UrlEncode("test")) Dim byteData() As Byte byteData = UTF8Encoding.UTF8.GetBytes(Data.ToString()) request.ContentLength = byteData.Length Dim postStream As Stream = Nothing Try postStream = request.GetRequestStream() postStream.Write(byteData, 0, byteData.Length) Finally If Not postStream Is Nothing Then postStream.Close() End Try 'Dim MyCookieContainer As New CookieContainer Dim MyCookieContainer As CookieContainer = New CookieContainer() request.CookieContainer = MyCookieContainer 'Makes no difference 'request.KeepAlive = True 'request.AllowAutoRedirect = True Dim response As HttpWebResponse 'HERE '"Too many automatic redirections were attempted" response = request.GetResponse() Dim reader As StreamReader = New StreamReader(response.GetResponseStream()) RichTextBox1.Text = reader.ReadToEnd End Sub End Class This is probably a newbie issue, but I don't know what else to try. Any idea? Thank you for any hint.

    Read the article

  • translate a PHP $string using google translator API

    - by Toni Michel Caubet
    hey there! been google'ing for a while how is the best way to translate with google translator in PHP, found very different ways converting URLS, or using Js but i want to do it only with php (or with a very simple solution JS/JQUery) example: //hopefully with $from_lan and $to_lan being like 'en','de', .. or similar function translate($from_lan, $to_lan, $text){ // do return $translated_text; } can you give me a clue? or maybe you already have this function.. my intention it's to use it only for the languages i have not already defined (or keys i haven't defined), that's why i wan it so simple, will be only temporal.. EDIT thanks for your replies we are now trying this soulutions: function auto_translate($from_lan, $to_lan, $text){ // do $json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan)); $translated_text = $json->responseData->translatedText; return $translated_text; } (there was a extra 'g' on variables for lang... anyway) it returns: works now :) i don't really understand much the function, so any idea why is not acepting the object? (now i do) OR: unction auto_translate($from_lan, $to_lan, $text){ // do // $json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan)); // $translated_text = $json['responseData']['translatedText']; error_reporting(1); require_once('GTranslate.php'); try{ $gt = new Gtranslate(); $translated_text = $gt-english_to_german($text); } catch (GTranslateException $ge) { $translated_text= $ge->getMessage(); } return $translated_text; } And this one looks great but it doesn't even gives me an error, the page won't load (error_report(1) :S) thanks in advance!

    Read the article

  • Move file or folder to a different folder in google document using api problem

    - by Minh Nguyen
    In Google Document i have a struct: Folder1 +------Folder1-1 +------+------File1-1-1 +------Folder1-2 +------File1-1 Folder2 I want to move "File1-1" to "Folder2" using .Net google api library(Google Data API SDK) public static void moveFolder(string szUserName, string szPassword, string szResouceID, string szToFolderResourceID) { string szSouceUrl = "https://docs.google.com/feeds/default/private/full" + "/" + HttpContext.Current.Server.UrlEncode(szResouceID); Uri sourceUri = new Uri(szSouceUrl); //create a atom entry AtomEntry atom = new AtomEntry(); atom.Id = new AtomId(szSouceUrl); string szTargetUrl = "http://docs.google.com/feeds/default/private/full/folder%3Aroot/contents/"; if (szToFolderResourceID != "") { szTargetUrl = "https://docs.google.com/feeds/default/private/full" + "/" + HttpContext.Current.Server.UrlEncode(szToFolderResourceID) + "/contents" ; } Uri targetUri = new Uri(szTargetUrl); DocumentsService service = new DocumentsService(SERVICENAME); ((GDataRequestFactory)service.RequestFactory).KeepAlive = false; service.setUserCredentials(szUserName, szPassword); service.EntrySend(targetUri, atom, GDataRequestType.Insert); } After run this function i have: Folder1 +------Folder1-1 +------+------File1-1-1 +------Folder1-2 +------File1-1 Folder2 +------File1-1 "File1-1" display in both "Folder1" and "Folder2", and when i delete it from a folder it will be deleted in another folder. (expect: "File1-1" display only in "Folder2") What happen? How can i solve this problem?

    Read the article

  • How to send XML and other post parameters via cURL in PHP

    - by tomaszs
    Hello. I've used code below to send XML to my REST API. $xml_string_data contains proper XML, and it is passed well to mypi.php: //set POST variables $url = 'http://www.server.cu/mypi.php'; $fields = array( 'data'=>urlencode($xml_string_data) ); //url-ify the data for the POST $fields_string = ""; foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string,'&'); echo $fields_string; //open connection $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,CURLOPT_POST,count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); curl_setopt($ch,CURLOPT_HTTPHEADER,array ( "Expect: " )); //execute post $result = @curl_exec($ch); But when I've added other field: $fields = array( 'method' => "methodGoPay", 'data'=>urlencode($xml_string_data) ); It stopped to work. On the mypi.php I don't recieve any more POST parameters at all! Could you you please tell me what to do to send XML and other post parameters in one cURL request? Please don't suggest using any libraries, I wan't to acomplish it in plain PHP.

    Read the article

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