/// <summary>
        /// Load the content by inserting the lcid after the filename, before the extension
        /// E.g. someResource.html is replaced with someResource_1033.js
        /// Ideally this url should be relative so to benefit from caching without having
        /// to explicitly specify the cache key
        /// </summary>
        /// <param name="webresourceFileName"></param>
        /// <param name="lcid"></param>
        /// <param name="callback"></param>
        public static void LoadContent(string webresourceFileName, int lcid, Action callback)
        {
            bool lcidSupported = SupportedLCIDs.Contains(0) || SupportedLCIDs.Contains(lcid);

            // Check the locale is in the supported locales
            if (!lcidSupported || (lcid == FallBackLCID))
            {
                callback();
                return;
            }

            int pos = webresourceFileName.LastIndexOf('.');
            string resourceFileName = Page.Context.GetClientUrl() + "/" + PageEx.GetCacheKey() + "WebResources/" + webresourceFileName.Substr(0, pos) + "_" + lcid.ToString() + webresourceFileName.Substr(pos);

            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Type = "GET";
            options.Url = resourceFileName;
            options.DataType = "script";
            options.Cache = true;
            options.Success = delegate(object data, string textStatus, jQueryXmlHttpRequest request)
            {
                callback();
            };
            options.Error = delegate(jQueryXmlHttpRequest request, string textStatus, Exception error)
            {
                Script.Alert(String.Format("Could not load resource file '{0}'. Please contact your system adminsitrator.\n\n{1}:{2}", resourceFileName, textStatus, error.Message));
                callback();
            };
            jQuery.Ajax(options);
        }
        /// <summary>
        /// Load the content by inserting the lcid after the filename, before the extension
        /// E.g. someResource.html is replaced with someResource_1033.js
        /// Ideally this url should be relative so to benefit from caching without having
        /// to explicitly specify the cache key
        /// </summary>
        /// <param name="webresourceFileName"></param>
        /// <param name="lcid"></param>
        /// <param name="callback"></param>
        public void LoadContent(string webresourceFileName, int lcid, Action callback)
        {
            
            // If the filename starts in '/Webresources/' we must prefix with the cache key
            // TODO 
            // Xrm.Sparkle.Page.GetCacheKey()

            // Check the locale is in the supported locales
            if (!SupportedLCIDs.Contains(lcid))
                lcid = FallBackLCID;

            int pos = webresourceFileName.LastIndexOf('.');
            string resourceFileName = webresourceFileName.Substr(0,pos-1) + "_" + lcid.ToString() + webresourceFileName.Substr(pos);

            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Type = "GET";
            options.Url = resourceFileName;
            options.DataType = "script";
            options.Success = delegate(object data, string textStatus, jQueryXmlHttpRequest request)
            {
                callback();
            };
            options.Error = delegate(jQueryXmlHttpRequest request, string textStatus, Exception error)
            {
                Script.Alert(String.Format("Could not load resource file '{0}'. Please contact your system adminsitrator.",resourceFileName));
            };
            jQuery.Ajax(options);
        }
		protected override void MakeRequest(string text, Dictionary<object, object> requestParameters, int maxNumberOfItemsToGet)
		{
			Dictionary<object, object> parameters = new Dictionary<object, object>();
			parameters["text"] = text;
			parameters["maxNumberOfItemsToGet"] = maxNumberOfItemsToGet;
			parameters["parameters"] = requestParameters;
			//if (webRequest != null && webRequest.Executor.Started) webRequest.Executor.Abort();
			//webRequest = WebServiceProxy.Invoke(
			//    url,
			//    this.MethodName,
			//    true,
			//    parameters, 
			//    this.SuccessCallback,
			//    Trace.WebServiceFailure, text, -1
			//);
			if (ajaxRequest != null)
			{
				try
				{
					ajaxRequest.Abort();
				}
				catch { }
			}

			jQueryAjaxOptions o = new jQueryAjaxOptions();
			o.Url = url + "/" + this.MethodName;
			o.Timeout = 10000;
			o.Type = "POST";
			o.Async = true;
			o.Cache = false;
			o.ContentType = "application/json; charset=utf-8";
			o.Data = JSON.stringify(parameters);
			o.DataType = "json";
			o.Error =
				delegate(jQueryXmlHttpRequest request, string error, System.Exception exception)
				{
					//this.FailureCallback(
					//    new WebServiceError(
					//        exception.GetType().ToString(),
					//        error,
					//        exception.ToString(),
					//        request.Status,
					//        request.Status == 408),
					//    textSoFar,
					//    webServiceCommand);
				};
			o.Success =
				delegate(object data, string textStatus, jQueryXmlHttpRequest request)
				{
					this.SuccessCallback(((Dictionary<string, object>)data)["d"], text, this.MethodName);
				};
			ajaxRequest = jQuery.Ajax(o);

		}
 private void SaveCustomer(jQueryEvent evt)
 {
     var opts = new jQueryAjaxOptions { Url = "/Home/SaveCustomer" };
     ((dynamic)opts).data = jQuery.Select("#customerForm").Serialize();
     var req = jQuery.Ajax(opts);
     req.Success(_ => {
         ((DialogObject)jQuery.Select("#customerForm")).Close();
         LoadCustomers();
     });
     req.Fail(_ => Window.Alert("Save failed"));
 }
        public void Refresh()
        {
            if (refreshTimer > -1)
            Window.ClearTimeout(refreshTimer);

             String Url = String.Format("http://search.twitter.com/search.json?callback=?&result_type=recent&lang={0}&q=&geocode={1},{2},{3}mi&rpp=5{4}", Utils.GetLanguage(), LocationHelper.Latitude, LocationHelper.Longitude, GetMaxDistance(), (LastID > -1 ? ("&since_id=" + LastID) : ""));
             jQueryAjaxOptions ajaxOptions = new jQueryAjaxOptions();
             ajaxOptions.DataType = "jsonp";
             ajaxOptions.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest request) {
            jQuery.Select("#loading-indicator").Hide();
            Array results = (Array)Type.GetField(data, "results");
            results.Reverse();
            for (int i = 0; i < results.Length; i++)
            {
               Tweet tweet = new Tweet();
               tweet.Created = ((String)Type.GetField(results[i], "created_at")).Replace(" +0000", "");
               tweet.Id = (long)Type.GetField(results[i], "id");
               if (tweet.Id > LastID)
                  LastID = tweet.Id;
               tweet.ProfileImageUrl = (String)Type.GetField(results[i], "profile_image_url");
               tweet.Text = (String)Type.GetField(results[i], "text");
               tweet.FromUser = (String)Type.GetField(results[i], "from_user");

               String tweetUrl = "https://twitter.com/" + tweet.FromUser + "/status/" + tweet.Id;
               String tweetTitle = tweet.FromUser + "'s Tweet";

               tweet.ShareUrl = "http://www.facebook.com/sharer.php?u=" + tweetUrl.EncodeUriComponent() + "&t=" + tweetTitle.EncodeUriComponent();

               if (CurrentTweets.GetItems().Count > 0)
               {
                  if (CurrentTweets.GetItems()[0].Id == tweet.Id)
                     continue;
               }
               CurrentTweets.Unshift(tweet);
            }
            refreshTimer = Window.SetTimeout(Refresh, 2500);
             });
             ajaxOptions.Error = new AjaxErrorCallback(delegate(jQueryXmlHttpRequest request, string error, Exception ex) {
            refreshTimer = Window.SetTimeout(Refresh, 5000);
             });
             jQuery.Ajax(Url, ajaxOptions);
        }
		public void RequestSuggestions(string textSoFar)
		{
			Dictionary<object, object> parameters = new Dictionary<object, object>();
			parameters["text"] = textSoFar;
			parameters["maxNumberOfItemsToGet"] = maxNumberOfItemsToGet;
			CancelRequests();
		//	webRequest = WebServiceProxy.Invoke(webServiceUrl, webServiceCommand, true, parameters, this.SuccessCallback, this.FailureCallback, textSoFar, -1);

			jQueryAjaxOptions o = new jQueryAjaxOptions();
			o.Url = webServiceUrl + "/" + webServiceCommand;
			o.Timeout = 10000;
			o.Type = "POST";
			o.Async = true;
			o.Cache = false;
			o.ContentType = "application/json; charset=utf-8";
			o.Data = JSON.stringify(parameters);
			o.DataType = "json";
			o.Error = 
				delegate(jQueryXmlHttpRequest request, string error, System.Exception exception)
				{
					this.FailureCallback(
						new WebServiceError(
							exception.GetType().ToString(),
							error,
							exception.ToString(),
							request.Status,
							request.Status == 408),
						textSoFar,
						webServiceCommand);
				};
			o.Success =
			    delegate(object data, string textStatus, jQueryXmlHttpRequest request)
			    {
					this.SuccessCallback(((Dictionary<string, object>)data)["d"], textSoFar, webServiceCommand);
			    };
			ajaxRequest = jQuery.Ajax(o);
			
		}
Example #7
0
        public IDeferred<IEnumerable<Photo>> SearchPhotos(string tags, int count)
        {
            jQueryAjaxOptions ajaxOptions =
                new jQueryAjaxOptions("url", String.Format(SearchUriFormat, _apiKey, tags.EncodeUriComponent(), count),
                                      "jsonp", "jsoncallback",
                                      "dataType", "jsonp");
            return jQuery.AjaxRequest<SearchResponse>(ajaxOptions).Pipe<IEnumerable<Photo>>(
                delegate(SearchResponse response) {
                    List<Photo> photos =
                        response.PhotoResponse.PhotoList.Map<Photo>(delegate(PhotoResult photoResult) {
                            return new Photo(photoResult.ID,
                                             photoResult.Title,
                                             "http://flic.kr/p/" + Base58Encode(photoResult.ID),
                                             photoResult.Url_m,
                                             photoResult.Url_t,
                                             Int32.Parse(photoResult.Width_m),
                                             Int32.Parse(photoResult.Height_m),
                                             Int32.Parse(photoResult.Width_t),
                                             Int32.Parse(photoResult.Height_t));
                    });

                    return photos;
                });
        }
Example #8
0
        private static void LoadResources()
        {
            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Async = false;
            int lcid = Page.Context.GetUserLcid();

            if (_siteMap == null)
            {
                options.Url = Page.Context.GetClientUrl() + "/" + PageEx.GetCacheKey() + "/WebResources/dev1_/js/SiteMap" + lcid.ToString() + ".js";
                _siteMap = jQuery.ParseJsonData<SiteMap>(jQuery.Ajax(options).ResponseText);
            }

            if (_resources == null)
            {
                Dictionary<string, string> loadedResources = null;
                options.Url =  GetResourceStringWebResourceUrl(lcid);
                try
                {
                    loadedResources = jQuery.ParseJsonData<Dictionary<string, string>>(jQuery.Ajax(options).ResponseText);
                }
                catch { }

                if (loadedResources == null)
                {
                    // We fall back to the 1033 because this is included in the solution
                    options.Url = GetResourceStringWebResourceUrl(1033);
                    loadedResources = jQuery.ParseJsonData<Dictionary<string, string>>(jQuery.Ajax(options).ResponseText);
                }
                _resources = loadedResources;
            }
        }
Example #9
0
 /// <summary>
 /// Sets up defaults for future Ajax requests.
 /// </summary>
 /// <param name="options">The options and settings for Ajax requests.</param>
 public static void AjaxSetup(jQueryAjaxOptions options)
 {
 }
Example #10
0
        /// <summary>
        /// Load a language file
        /// </summary>
        /// <param name="language">The language to be loaded</param>
        /// <param name="successCallback">Success Callback</param>
        /// <param name="failureCallback">Failure Callback</param>
        public static void LoadLanguageFile(string language, Action successCallback, Action<Exception> failureCallback)
        {
            if (loadedLanguageData.ContainsKey(language))
            {
                successCallback();
                return;
            }

            AjaxErrorCallback onError = delegate(jQueryXmlHttpRequest request, string textStatus, Exception error)
            {
                failureCallback(error);
            };

            AjaxRequestCallback onFinish = delegate(object data, string textStatus, jQueryXmlHttpRequest request)
            {
                loadedLanguageData[language] = new Dictionary<string, string>();

                jQuery.FromHtml((string)data).Each(delegate(int index, Element element)
                {
                    jQueryObject currentObject = jQuery.FromElement(element);
                    if (String.Compare(element.TagName, "p", true) == 0)
                    {
                        string stringId = currentObject.GetAttribute("id");
                        if (!String.IsNullOrEmpty(stringId))
                        {
                            loadedLanguageData[language][stringId] = currentObject.GetHtml();
                        }
                    }
                });

                successCallback();
            };

            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Type = "GET";
            options.DataType = "html";
            options.Error = onError;
            options.Success = onFinish;

            jQuery.Ajax(String.Format(LanguageFilePathFormat, language), options);
        }
Example #11
0
 /// <summary>
 /// Issues an Ajax request.
 /// </summary>
 /// <param name="options">The options and settings for the request to invoke.</param>
 /// <returns>The jQueryXmlHttpRequest object.</returns>
 public static jQueryXmlHttpRequest Ajax(jQueryAjaxOptions options)
 {
     return(null);
 }
Example #12
0
 public static jQueryDataHttpRequest <TData> AjaxRequest <TData>(jQueryAjaxOptions options)
 {
     return(null);
 }
Example #13
0
        private void SendRequest()
        {
            jQueryAjaxOptions options = new jQueryAjaxOptions();
            options.Data = new Dictionary<string, string>("j", Json.Stringify(data));
            options.DataType = "json";
            options.Type = "POST";
            options.Cache = false;
            options.Error = AjaxError;
            options.Success = AjaxSuccess;

            jQuery.Ajax(Endpoint + (Environment.ServerType == ServerType.AspNet ? ".aspx" : ".php"), options);
        }
Example #14
0
		public static jQueryAjaxOptions Options(
			string methodName,
			string url,
			Dictionary<string, object> parameters,
			WebServiceFailureCallback failure,
			object userContext,
			int timeout)
		{
			jQueryAjaxOptions o = new jQueryAjaxOptions();
			o.Url = url + "/" + methodName;
			o.Timeout = timeout;
			o.Type = "POST";
			o.Async = true;
			o.Cache = false;
			o.ContentType = "application/json; charset=utf-8";
			o.Data = JSON.stringify(parameters);
			o.DataType = "json";
			o.Error =
				delegate(jQueryXmlHttpRequest request, string error, Exception exception)
				{
					failure(
						new WebServiceError(
							exception.GetType().ToString(),
							error,
							exception.ToString(),
							request.Status,
							request.Status == 408),
						userContext,
						methodName);
				};
			return o;
		}
 public static void SetDataString(jQueryAjaxOptions options, string data)
 {
 }
Example #16
0
 private void InvokeUsingWsdl(XmlDocument wsdl)
 {
     XmlNode targetNamespaceNode = wsdl.DocumentElement.Attributes.GetNamedItem("targetNamespace");
     string targetNamespace = targetNamespaceNode == null ? string.Empty : targetNamespaceNode.Value;
     NamespacePrefixes namespacePrefixes = new NamespacePrefixes(targetNamespace);
     string parametersXml = GetParametersXml(wsdl, namespacePrefixes);
     string soapRequest = @"<?xml version=""1.0"" encoding=""utf-8""?>
     <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
     <soap:Body>
     <" + _method + @" xmlns=""" + targetNamespace + @"""" + namespacePrefixes.GetPrefixDefinitions() + ">" + parametersXml + @"</" + _method + @">
     </soap:Body>
     </soap:Envelope>";
     jQueryAjaxOptions options = new jQueryAjaxOptions { DataType = "xml" };
     bool useCredentials = !string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password);
     if (useCredentials)
     {
         options.Username = _username;
         options.Password = _password;
     }
     options.BeforeSend = request =>
         {
             if (useCredentials)
             {
                 request.SetRequestHeader("Authorization", "Basic " + StringUtility.ToBase64(_username + ":" + _password));
             }
             string soapAction = FindSoapAction(wsdl, targetNamespace);
             request.SetRequestHeader("SOAPAction", soapAction);
             request.SetRequestHeader("Content-Type", "text/xml; charset=utf-8");
         };
     options.Timeout = (int)_timeout.TotalMilliseconds;
     options.Type = "POST";
     jQueryAjaxOptionsUtility.SetDataString(options, soapRequest);
     jQuery.Ajax(_url, options).Then((data, textStatus, request) => _successCallback(GetReturnValue(wsdl, Script.Reinterpret<XmlDocument>(data)), textStatus, request), new AjaxFailCallback(_errorCallback));
 }
Example #17
0
 /// <summary>
 /// Issues an Ajax request.
 /// </summary>
 /// <param name="url">The endpoint to which the request is issued.</param>
 /// <param name="options">The options and settings for the request to invoke.</param>
 /// <returns>The jQueryXmlHttpRequest object.</returns>
 public static jQueryXmlHttpRequest <object> Ajax(string url, jQueryAjaxOptions options)
 {
     return(null);
 }
Example #18
0
 public static jQueryXmlHttpRequest <TData> AjaxRequest <TData>(string url, jQueryAjaxOptions options)
 {
     return(null);
 }
Example #19
0
        public static void LoadTemplateFile(Action successCallback, Action<Exception> failureCallback)
        {
            int templateIndex = 0;
            string currentTemplateFile = string.Empty;
            Action loadNextTemplate = delegate { };

            AjaxErrorCallback onError = delegate(jQueryXmlHttpRequest request, string textStatus, Exception error)
            {
                failureCallback(new Exception(String.Format(Strings.Get("TemplateLoadError"), currentTemplateFile, error)));
            };

            AjaxRequestCallback onFinish = delegate(object data, string textStatus, jQueryXmlHttpRequest request)
            {
                jQueryObject templateDiv = jQuery.FromElement(Document.CreateElement("div")).AppendTo(TempDivObject).Append(jQuery.FromHtml((string)data));

                loadedTemplateData[currentTemplateFile] = new Dictionary<string, jQueryObject>();
                foreach (string templateId in TemplateIds[currentTemplateFile])
                {
                    jQueryObject selectedTemplate = jQuery.Select("#" + templateId, templateDiv);
                    if (selectedTemplate.Length != 1)
                    {
                        failureCallback(new Exception(String.Format(Strings.Get("TemplateParseError"), currentTemplateFile, templateId)));
                        return;
                    }

                    loadedTemplateData[currentTemplateFile][templateId] = selectedTemplate.Clone();
                    selectedTemplate.Remove();
                }

                templateDiv.Remove();

                templateIndex++;
                loadNextTemplate();
            };

            loadNextTemplate = delegate
            {
                if (templateIndex >= Templates.Length)
                {
                    successCallback();
                    return;
                }

                currentTemplateFile = Templates[templateIndex];

                jQueryAjaxOptions options = new jQueryAjaxOptions();
                options.Type = "GET";
                options.DataType = "html";
                options.Error = onError;
                options.Success = onFinish;

                jQuery.Ajax(String.Format(TemplateFilePathFormat, currentTemplateFile), options);
            };

            loadNextTemplate();
        }