public int Count(object countParams) { var parameters = new CountParams(this.Engine.Object.InstancePrototype); if (countParams != null && countParams != Null.Value && countParams != Undefined.Value) { parameters = JurassicHelper.Coerce <CountParams>(this.Engine, countParams); } if (String.IsNullOrEmpty(parameters.TableName)) { parameters.TableName = GetFullTableName(); } if (String.IsNullOrEmpty(parameters.TableName)) { throw new JavaScriptException(this.Engine, "Error", "A table name must be specified either as a parameter or via the tableName property on the DynamicModel instance."); } if (String.IsNullOrEmpty(parameters.Where)) { return((int)Scalar(String.Format("SELECT COUNT(*) FROM {0}", parameters.TableName))); } return((int)Scalar(String.Format("SELECT COUNT(*) FROM {0} WHERE {1}", parameters.TableName, parameters.Where))); }
public object Single(object filterCriteria) { var criteria = new EntityFilterCriteriaInstance(Engine.Object.InstancePrototype); if (filterCriteria is FolderInstance) { criteria.EntityFilterCriteria.Path = (filterCriteria as FolderInstance).FullPath; } else if (filterCriteria is string || filterCriteria is StringInstance || filterCriteria is ConcatenatedString) { criteria.EntityFilterCriteria.Path = filterCriteria.ToString(); } else if (filterCriteria != null && filterCriteria != Null.Value && filterCriteria != Undefined.Value) { criteria = JurassicHelper.Coerce <EntityFilterCriteriaInstance>(Engine, filterCriteria); } var result = m_repository.Single(criteria.EntityFilterCriteria); if (result == null) { return(Null.Value); } return(new EntityInstance(Engine, result)); }
public ArrayInstance ListEntities(object filterCriteria) { var criteria = new EntityFilterCriteriaInstance(Engine.Object.InstancePrototype); if (filterCriteria is FolderInstance) { criteria.EntityFilterCriteria.Path = (filterCriteria as FolderInstance).FullPath; } else if (filterCriteria is string || filterCriteria is StringInstance || filterCriteria is ConcatenatedString) { criteria.EntityFilterCriteria.Path = filterCriteria.ToString(); } else if (filterCriteria != null && filterCriteria != Null.Value && filterCriteria != Undefined.Value) { criteria = JurassicHelper.Coerce <EntityFilterCriteriaInstance>(Engine, filterCriteria); } var result = Engine.Array.Construct(); foreach (var entity in m_repository.ListEntities(criteria.EntityFilterCriteria)) { ArrayInstance.Push(result, new EntityInstance(Engine, entity)); } return(result); }
public DocumentStoreInstance Construct(object creationInfo) { if (creationInfo != null && creationInfo != Null.Value && creationInfo != Undefined.Value && creationInfo is ObjectInstance) { var result = JurassicHelper.Coerce <DocumentStoreInstance>(this.Engine, creationInfo); return(result); } return(new DocumentStoreInstance(this.InstancePrototype)); }
public override object CallLateBound(object thisObject, params object[] argumentValues) { var contentObject = argumentValues.ElementAtOrDefault(0); if (contentObject == Undefined.Value || contentObject == Null.Value || contentObject == null) { return(thisObject); } var mergeSettings = argumentValues.ElementAtOrDefault(1); JsonMergeSettingsInstance jms = null; if (mergeSettings != Undefined.Value && mergeSettings != Null.Value && mergeSettings != null) { if (mergeSettings is JsonMergeSettingsInstance) { jms = (mergeSettings as JsonMergeSettingsInstance); } else { jms = JurassicHelper.Coerce <JsonMergeSettingsInstance>(this.Engine, mergeSettings); } } var s1 = JSONObject.Stringify(this.Engine, thisObject, null, null); var s2 = JSONObject.Stringify(this.Engine, contentObject, null, null); if (TypeUtilities.IsObject(thisObject) == false && TypeUtilities.IsArray(thisObject) == false) { throw new JavaScriptException(this.Engine, "Error", "This object must either be an object or an array."); } if (TypeUtilities.IsObject(contentObject) == false && TypeUtilities.IsArray(contentObject) == false) { throw new JavaScriptException(this.Engine, "Error", "Content object must either be an object or an array."); } var o1 = (JContainer)JToken.Parse(s1); var o2 = (JContainer)JToken.Parse(s2); if (jms != null) { o1.Merge(o2, jms.JsonMergeSettings); } else { o1.Merge(o2); } var result = JSONObject.Parse(this.Engine, o1.ToString(), null); return(result); }
public ObjectInstance Paged(object pagedParams) { PagedParams parameters = new PagedParams(this.Engine.Object.InstancePrototype); if (pagedParams != null && pagedParams != Undefined.Value && pagedParams != Null.Value) { parameters = JurassicHelper.Coerce <PagedParams>(this.Engine, pagedParams); } return(BuildPagedResult(parameters)); }
public int Delete(object deleteParams) { if (deleteParams == null || deleteParams == Null.Value || deleteParams == Undefined.Value) { throw new JavaScriptException(this.Engine, "Error", "Must specify an object with where or key"); } var parameters = JurassicHelper.Coerce <DeleteParams>(this.Engine, deleteParams); int result = Execute(CreateDeleteCommand(parameters)); return(result); }
public ArrayInstance All(object allParams) { var parameters = new AllParams(this.Engine.Object.InstancePrototype); if (allParams != null && allParams != Undefined.Value && allParams != Null.Value) { parameters = JurassicHelper.Coerce <AllParams>(this.Engine, allParams); } string sql = BuildSelect(parameters.Where, parameters.OrderBy, parameters.Limit); return(Query(string.Format(sql, parameters.Columns, GetFullTableName()), parameters.Args)); }
protected override ObjectSettings Unwrap(ObjectInstance objectSettings) { if (objectSettings == null) { return(null); } var os = objectSettings as ObjectSettingsInstance; if (os != null) { return(os.ObjectSettings); } var os2 = JurassicHelper.Coerce <ObjectSettingsInstance>(Engine, objectSettings); return(os2.ObjectSettings); }
protected override IBaristaCookie Unwrap(ObjectInstance cookie) { if (cookie == null) { return(null); } //If c is cookie, that's good for me. var c = cookie as BaristaCookieInstance; if (c != null) { return(c.BaristaCookie); } var os2 = JurassicHelper.Coerce <BaristaCookieInstance>(Engine, cookie); return(os2.BaristaCookie); }
public string PutIndex(object name, object indexDefinition, object overwrite) { if (name == null || name == Undefined.Value || name == Null.Value) { throw new JavaScriptException(this.Engine, "Error", "The first argument must contain the index name."); } if (indexDefinition == null || indexDefinition == Undefined.Value || indexDefinition == Null.Value) { throw new JavaScriptException(this.Engine, "Error", "The second argument must contain the index definition."); } var strName = TypeConverter.ToString(name); RavenDB.Abstractions.Indexing.IndexDefinition objIndexDefinition; if (indexDefinition is IndexDefinitionInstance) { objIndexDefinition = (indexDefinition as IndexDefinitionInstance).IndexDefinition; } else if (indexDefinition is ObjectInstance) { objIndexDefinition = JurassicHelper.Coerce <IndexDefinitionInstance>(this.Engine, indexDefinition).IndexDefinition; } else { throw new JavaScriptException(this.Engine, "Error", "The second argument must contain either an instance of IndexDefinition or a object that can be converted"); } string result; if (overwrite != null && overwrite != Null.Value && overwrite != Undefined.Value) { result = m_databaseCommands.PutIndex(strName, objIndexDefinition, TypeConverter.ToBoolean(overwrite)); } else { result = m_databaseCommands.PutIndex(strName, objIndexDefinition); } return(result); }
public DocumentSessionInstance OpenSession(object arg) { RavenDB.IDocumentSession session; if (arg == null || arg == Null.Value || arg == Undefined.Value) { session = m_documentStore.OpenSession(); } else if (arg is ObjectInstance) { var openSessionOptions = JurassicHelper.Coerce <OpenSessionsOptionsInstance>(this.Engine, arg); session = m_documentStore.OpenSession(openSessionOptions.OpenSessionOptions); } else { session = m_documentStore.OpenSession(TypeConverter.ToString(arg)); } return(new DocumentSessionInstance(this.Engine.Object.InstancePrototype, session)); }
public SPWebInstance CreateWeb(object webCreationInfo) { SPWeb createdWeb; if (webCreationInfo is string) { createdWeb = m_site.AllWebs.Add(webCreationInfo as string); } else { var creationInfo = JurassicHelper.Coerce <SPWebCreationInformation>(Engine, webCreationInfo); if (creationInfo.WebTemplate is string) { createdWeb = m_site.AllWebs.Add(creationInfo.Url, creationInfo.Title, creationInfo.Description, (uint)creationInfo.Language, creationInfo.WebTemplate as string, !creationInfo.UseSamePermissionsAsParentSite, creationInfo.ConvertIfThere); } else { //attempt to get an instance of a web template from the original object. var webCreationInstance = webCreationInfo as ObjectInstance; if (webCreationInstance == null) { throw new JavaScriptException(Engine, "Error", "Unable to create a web from the specified template. Could not determine the value of the web template."); } if (webCreationInstance.HasProperty("webTemplate") == false) { throw new JavaScriptException(Engine, "Error", "Unable to create a web from the specified template. Web Template property was null."); } var webTemplate = JurassicHelper.Coerce <SPWebTemplateInstance>(Engine, webCreationInstance.GetPropertyValue("webTemplate")); createdWeb = m_site.AllWebs.Add(creationInfo.Url, creationInfo.Title, creationInfo.Description, (uint)creationInfo.Language, webTemplate.WebTemplate, !creationInfo.UseSamePermissionsAsParentSite, creationInfo.ConvertIfThere); } } return(new SPWebInstance(Engine, createdWeb)); }
public void Import( [JSDoc("An object that contains import settings properties or an instance of SPImportSettings")] object importSettings, [JSDoc("The target drop location from where the files should be copied from or null to use files on the files system.")] object dropLocation) { var import = new SPImport(); if (importSettings is SPImportSettingsInstance) { import.Settings = (importSettings as SPImportSettingsInstance).SPImportSettings; } else if (importSettings is ObjectInstance) { var settings = JurassicHelper.Coerce <SPImportSettingsInstance>(Engine, importSettings as ObjectInstance); import.Settings = settings.SPImportSettings; } else { throw new JavaScriptException(Engine, "Error", "Expected the first argument to be an import settings object."); } import.Run(); }
public ArrayInstance Export( [JSDoc("An object that contains export settings properties or an instance of SPExportSettings")] object exportSettings, [JSDoc("The target drop location or null to keep in target folder.")] object dropLocation) { var export = new SPExport(); if (exportSettings is SPExportSettingsInstance) { export.Settings = (exportSettings as SPExportSettingsInstance).SPExportSettings; } else if (exportSettings is ObjectInstance) { var settings = JurassicHelper.Coerce <SPExportSettingsInstance>(Engine, exportSettings as ObjectInstance); export.Settings = settings.SPExportSettings; } else { throw new JavaScriptException(Engine, "Error", "Expected the first argument to be a export settings object."); } export.Run(); if (dropLocation != Null.Value && dropLocation != Undefined.Value) { SPExportInstance.CopyFilesToDropLocation(export, TypeConverter.ToString(dropLocation)); } var result = Engine.Array.Construct(); foreach (var dataFile in export.Settings.DataFiles.OfType <string>()) { ArrayInstance.Push(result, dataFile); } return(result); }
public object Json2Csv(object array, object csvOptions) { if (array == null || array == Null.Value || array == Undefined.Value || (array is ArrayInstance) == false || (array as ArrayInstance).Length == 0) { return(Null.Value); } var options = new CsvOptions(this.Engine.Object.InstancePrototype); if (csvOptions != null && csvOptions != Undefined.Value && csvOptions != Null.Value) { options = JurassicHelper.Coerce <CsvOptions>(this.Engine, csvOptions); } var jsonArray = array as ArrayInstance; HeaderRecord headerRecord = null; if (options.HasHeader) { var firstRecord = jsonArray[0] as ObjectInstance; if (firstRecord == null) { return(Null.Value); } var keys = firstRecord.Properties .Select(property => property.Name) .ToList(); headerRecord = new HeaderRecord(keys); } using (var ms = new MemoryStream()) { using (var csvWriter = new CsvWriter(ms)) { csvWriter.ValueDelimiter = options.ValueDelimiter[0]; csvWriter.ValueSeparator = options.ValueSeparator[0]; if (headerRecord != null) { csvWriter.WriteHeaderRecord(headerRecord); } foreach (var value in jsonArray.ElementValues.OfType <ObjectInstance>()) { var currentRecord = new DataRecord(headerRecord); if (headerRecord == null) { foreach (var property in value.Properties) { var propertyValue = String.Empty; if (property.Value != null) { propertyValue = property.Value.ToString(); } currentRecord.Values.Add(propertyValue); } } else { foreach (var key in headerRecord.Values) { var propertyValue = String.Empty; if (value.HasProperty(key) && value[key] != null) { propertyValue = value[key].ToString(); } currentRecord.Values.Add(propertyValue); } } csvWriter.WriteDataRecord(currentRecord); } csvWriter.Flush(); ms.Seek(0, SeekOrigin.Begin); return(Encoding.UTF8.GetString(ms.ToArray())); } } }
public object Csv2Json(object csv, object csvOptions) { if (csv == null || csv == Null.Value || csv == Undefined.Value) { return(null); } string csvString; if (csv is Base64EncodedByteArrayInstance) { csvString = (csv as Base64EncodedByteArrayInstance).ToUtf8String(); } else { csvString = TypeConverter.ToString(csv); } var options = new CsvOptions(this.Engine.Object.InstancePrototype); if (csvOptions != null && csvOptions != Undefined.Value && csvOptions != Null.Value) { options = JurassicHelper.Coerce <CsvOptions>(this.Engine, csvOptions); } using (var csvReader = CsvReader.FromCsvString(csvString)) { csvReader.PreserveLeadingWhiteSpace = options.PreserveLeadingWhiteSpace; csvReader.PreserveTrailingWhiteSpace = options.PreserveTrailingWhiteSpace; csvReader.ValueDelimiter = options.ValueDelimiter[0]; csvReader.ValueSeparator = options.ValueSeparator[0]; HeaderRecord headerRecord = null; if (options.HasHeader) { headerRecord = csvReader.ReadHeaderRecord(); } var result = new List <ObjectInstance>(); DataRecord currentRecord; while ((currentRecord = csvReader.ReadDataRecord()) != null) { ObjectInstance currentObject; if (headerRecord == null) { // ReSharper disable CoVariantArrayConversion currentObject = this.Engine.Array.Construct(currentRecord.Values.ToArray()); // ReSharper restore CoVariantArrayConversion } else { currentObject = this.Engine.Object.Construct(); foreach (var key in headerRecord.Values) { currentObject.SetPropertyValue(key, currentRecord[key], false); } } result.Add(currentObject); } // ReSharper disable CoVariantArrayConversion return(this.Engine.Array.Construct(result.ToArray())); // ReSharper restore CoVariantArrayConversion } }
public static SPListInstance CreateList(ScriptEngine engine, SPListCollection collection, SPListTemplateCollection templates, object listCreationInfo) { Guid createdListId; if (listCreationInfo == null || listCreationInfo == Null.Value || listCreationInfo == Undefined.Value) { throw new JavaScriptException(engine, "Error", "A List Creation Info object must be specified."); } var listCreationInstance = listCreationInfo as ObjectInstance; var creationInfo = JurassicHelper.Coerce <SPListCreationInformation>(engine, listCreationInfo); SPListTemplate.QuickLaunchOptions quickLaunchOptions = (SPListTemplate.QuickLaunchOptions)Enum.Parse(typeof(SPListTemplate.QuickLaunchOptions), creationInfo.QuickLaunchOption); //If dataSourceProperties property has a value, create the list instance as a BCS list. if (listCreationInstance != null && listCreationInstance.HasProperty("dataSourceProperties")) { var dataSourceInstance = listCreationInstance.GetPropertyValue("dataSourceProperties") as ObjectInstance; if (dataSourceInstance == null) { return(null); } var dataSource = new SPListDataSource(); foreach (var property in dataSourceInstance.Properties) { dataSource.SetProperty(property.Name, property.Value.ToString()); } createdListId = collection.Add(creationInfo.Title, creationInfo.Description, creationInfo.Url, dataSource); } //If listTemplate property has a value, create the list instance using the strongly-typed SPListTemplate, optionally using the docTemplate value. else if (listCreationInstance != null && listCreationInstance.HasProperty("listTemplate") && templates != null) { var listTemplateValue = listCreationInstance.GetPropertyValue("listTemplate"); SPListTemplate listTemplate = null; if (listTemplateValue is int) { listTemplate = templates.OfType <SPListTemplate>().FirstOrDefault(dt => (int)dt.Type == (int)listTemplateValue); } else { var s = listTemplateValue as string; if (s != null) { listTemplate = templates.OfType <SPListTemplate>().FirstOrDefault(dt => dt.Type.ToString() == s); } else if (listTemplateValue is ObjectInstance) { listTemplate = JurassicHelper.Coerce <SPListTemplateInstance>(engine, listTemplateValue).ListTemplate; } } if (listTemplate == null) { return(null); } if (listCreationInstance.HasProperty("docTemplate")) { var docTemplate = JurassicHelper.Coerce <SPDocTemplateInstance>(engine, listCreationInstance.GetPropertyValue("docTemplate")); createdListId = collection.Add(creationInfo.Title, creationInfo.Description, creationInfo.Url, listTemplate.FeatureId.ToString(), listTemplate.Type_Client, docTemplate.DocTemplate.Type.ToString(CultureInfo.InvariantCulture), quickLaunchOptions); } else { createdListId = collection.Add(creationInfo.Title, creationInfo.Description, creationInfo.Url, listTemplate.FeatureId.ToString(), listTemplate.Type_Client, String.Empty, quickLaunchOptions); } } //Otherwise attempt to create the list using all properties set on the creation info object. else { SPFeatureDefinition listInstanceFeatureDefinition = null; if (listCreationInstance != null && listCreationInstance.HasProperty("listInstanceFeatureDefinition")) { var featureDefinitionInstance = JurassicHelper.Coerce <SPFeatureDefinitionInstance>(engine, listCreationInstance.GetPropertyValue("listInstanceFeatureDefinition")); listInstanceFeatureDefinition = featureDefinitionInstance.FeatureDefinition; } createdListId = collection.Add(creationInfo.Title, creationInfo.Description, creationInfo.Url, creationInfo.TemplateFeatureId, creationInfo.TemplateType, creationInfo.DocumentTemplateType, creationInfo.CustomSchemaXml, listInstanceFeatureDefinition, quickLaunchOptions); } var createdList = collection[createdListId]; return(new SPListInstance(engine, null, null, createdList)); }
public object Ajax(string url, object settings) { //If we're running under Claims authentication, impersonate the thread user //by calling the Claims to Windows Token Service and call the remote site using //the impersonated credentials. NOTE: The Claims to Windows Token Service must be running. WindowsImpersonationContext ctxt = null; if (Thread.CurrentPrincipal.Identity is ClaimsIdentity) { IClaimsIdentity identity = (ClaimsIdentity)System.Threading.Thread.CurrentPrincipal.Identity; var firstClaim = identity.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.Upn); if (firstClaim == null) { throw new InvalidOperationException("No UPN claim found"); } var upn = firstClaim.Value; if (String.IsNullOrEmpty(upn)) { throw new InvalidOperationException("A UPN claim was found, however, the value was empty."); } var currentIdentity = S4UClient.UpnLogon(upn); ctxt = currentIdentity.Impersonate(); } try { var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); var targetUri = ObtainTargetUri(url); var request = (HttpWebRequest)WebRequest.Create(targetUri); request.CachePolicy = noCachePolicy; //TODO: Make this configurable. //Get the proxy from the concrete instance. var proxyAddress = ObtainDefaultProxyAddress(); //If the proxy address is defined, create a new proxy with the address, otherwise, use the system proxy. request.Proxy = proxyAddress.IsNullOrWhiteSpace() == false ? new WebProxy(proxyAddress, true, null, CredentialCache.DefaultNetworkCredentials) : WebRequest.GetSystemWebProxy(); if (request.Proxy != null) { request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; } var dataType = AjaxDataType.Unknown; //If a settings parameter is defined, coerce it and set properties on the request object. var ajaxSettings = JurassicHelper.Coerce <AjaxSettingsInstance>(Engine, settings); if (ajaxSettings != null) { if (ajaxSettings.UseDefaultCredentials == false) { //if the "credentials" setting is set on the ajaxsettingsinstance, use those credentials instead. if (ajaxSettings.Credentials != null && ajaxSettings.Credentials != Null.Value && ajaxSettings.Credentials != Undefined.Value && ajaxSettings.Credentials is NetworkCredentialInstance) { request.Credentials = (ajaxSettings.Credentials as NetworkCredentialInstance).NetworkCredential; } //Otherwise, use the username/password/domain if specified. else if (String.IsNullOrEmpty(ajaxSettings.Username) == false || String.IsNullOrEmpty(ajaxSettings.Password) == false || String.IsNullOrEmpty(ajaxSettings.Domain) == false) { request.Credentials = new NetworkCredential(ajaxSettings.Username, ajaxSettings.Password, ajaxSettings.Domain); } } else { request.UseDefaultCredentials = true; request.Credentials = CredentialCache.DefaultNetworkCredentials; } if (String.IsNullOrEmpty(ajaxSettings.Accept) == false) { request.Accept = ajaxSettings.Accept; } if (ajaxSettings.Proxy != null && ajaxSettings.Proxy != Undefined.Value && ajaxSettings.Proxy != Null.Value) { var proxySettings = JurassicHelper.Coerce <ProxySettingsInstance>(Engine, ajaxSettings.Proxy); if (proxySettings != null) { if (String.IsNullOrEmpty(proxySettings.Address) == false) { try { var proxy = new WebProxy(proxySettings.Address, true); request.Proxy = proxy; } catch { /* do nothing */ } } if (proxySettings.UseDefaultCredentials) { request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; } } } if (String.IsNullOrEmpty(ajaxSettings.DataType) == false) { switch (ajaxSettings.DataType.ToLowerInvariant()) { case "json": dataType = AjaxDataType.Json; break; case "xml": dataType = AjaxDataType.Xml; break; case "raw": dataType = AjaxDataType.Raw; break; default: dataType = AjaxDataType.Unknown; break; } } if (String.IsNullOrEmpty(ajaxSettings.Method) == false) { request.Method = ajaxSettings.Method; } if (String.IsNullOrEmpty(ajaxSettings.UserAgent) == false) { request.UserAgent = ajaxSettings.UserAgent; } if (String.IsNullOrEmpty(ajaxSettings.ContentType) == false) { request.ContentType = ajaxSettings.ContentType; } if (String.IsNullOrEmpty(ajaxSettings.Referer) == false) { request.Referer = ajaxSettings.Referer; } } else { request.Accept = "application/json"; } //Get some not-serialized properties from the original webinstance if (settings != Null.Value && settings != Undefined.Value && settings is ObjectInstance) { var settingsObj = settings as ObjectInstance; if (settingsObj.HasProperty("headers")) { var headersObj = settingsObj.GetPropertyValue("headers"); if (headersObj != Null.Value && headersObj != Undefined.Value && headersObj is ObjectInstance) { var headersObjInstance = headersObj as ObjectInstance; foreach (var prop in headersObjInstance.Properties) { try { request.Headers.Set(prop.Name, TypeConverter.ToString(prop.Value)); } catch (Exception) { //Ignore it. } } } } if (settingsObj.HasProperty("timeout")) { var timeoutObj = settingsObj.GetPropertyValue("timeout"); request.Timeout = TypeConverter.ToInteger(timeoutObj); } if (settingsObj.HasProperty("body")) { var bodyObj = settingsObj.GetPropertyValue("body"); if (bodyObj != Null.Value && bodyObj != Undefined.Value) { var bodyByteArray = bodyObj as Base64EncodedByteArrayInstance; if (bodyByteArray != null) { var requestStream = request.GetRequestStream(); requestStream.Write(bodyByteArray.Data, 0, bodyByteArray.Data.Length); requestStream.Close(); } else { var data = Encoding.UTF8.GetBytes(TypeConverter.ToString(bodyObj)); var requestStream = request.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); } } } } if (ajaxSettings != null && ajaxSettings.Async) { var tcs = new TaskCompletionSource <object>(); try { request.BeginGetResponse(iar => { HttpWebResponse response = null; try { response = (HttpWebResponse)request.EndGetResponse(iar); var resultObject = GetResultFromResponse(response, dataType); tcs.SetResult(resultObject); } catch (Exception exc) { tcs.SetException(exc); } finally { if (response != null) { response.Close(); } } }, null); } catch (Exception exc) { tcs.SetException(exc); } return(new DeferredInstance(Engine.Object.InstancePrototype, tcs.Task)); } object result; try { var syncResponse = (HttpWebResponse)request.GetResponse(); result = GetResultFromResponse(syncResponse, dataType); } catch (WebException e) { //The request failed -- usually a 400 var httpResponse = e.Response as HttpWebResponse; result = httpResponse == null ? null : new HttpWebResponseInstance(Engine.Object.InstancePrototype, httpResponse); } catch (Exception ex) { LogAjaxException(ex); throw; } return(result); } finally { if (ctxt != null) { ctxt.Dispose(); } } }