////// <summary> ////// The list received a context event. ////// </summary> //public override void ContextEvent(SPItemEventProperties properties) //{ // base.ContextEvent(properties); //} /// <summary> /// Executes the Barista Script in response to an item event. /// </summary> /// <param name="properties">The properties.</param> private static void ExecuteBaristaScript(SPItemEventProperties properties) { BrewRequest request; using (var web = properties.OpenWeb()) { var list = web.Lists[properties.ListId]; var item = list.GetItemById(properties.ListItemId); var headers = new Dictionary <string, IEnumerable <string> > { { "Content-Type", new[] { "application/json" } } }; request = new BrewRequest { Headers = new BrewRequestHeaders(headers), Code = properties.ReceiverData, ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52" }; request.SetExtendedPropertiesFromSPItemEventProperties(web, list, item, properties); } var serviceContext = SPServiceContext.Current ?? SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, new SPSiteSubscriptionIdentifier(Guid.Empty)); var client = new BaristaServiceClient(serviceContext); client.Exec(request); //TODO: Allow for Syncronous events that expect to return an object with which to update the properties object with. }
private static void SetBaristaV2Flags(IScriptSource source, BrewRequest request, BrewResponse response) { if (String.IsNullOrWhiteSpace(request.Bootstrapper)) { source.Flags["bootstrapperPath"] = ConfigurationManager.AppSettings.GetValue("Barista_v2_Bootstrapper", "./../lib/BaristaBootstrapper_v1.js"); } else { source.Flags["bootstrapperPath"] = request.Bootstrapper; } var dcs = new DataContractSerializer(typeof(BrewRequest)); source.Flags["request_xml"] = BaristaHelper.SerializeXml(request); source.Flags["response_xml"] = BaristaHelper.SerializeXml(response); source.Flags["request"] = JsonConvert.SerializeObject(request); source.Flags["response"] = JsonConvert.SerializeObject(response); source.Flags["environment"] = JsonConvert.SerializeObject(new { baristaWebServiceBinFolder = SPUtility.GetVersionedGenericSetupPath(@"WebServices\Barista\bin", SPUtility.CompatibilityLevel15), baristaAssembly = BaristaHelper.GetAssemblyPath(typeof(Barista.Library.BaristaGlobal)) + "\\Barista.Core.dll", baristaSharePointAssembly = BaristaHelper.GetAssemblyPath(typeof(Barista.SharePoint.Library.BaristaSharePointGlobal)) + "\\Barista.SharePoint.Core.dll", sharePointAssembly = BaristaHelper.GetAssemblyPath(typeof(Microsoft.SharePoint.SPContext)) + "\\Microsoft.SharePoint.dll" }); }
public HttpRequestInstance(ScriptEngine engine, BrewRequest request) : base(engine) { Request = request; PopulateFields(); PopulateFunctions(); }
public void Exec(BrewRequest request) { BaristaServiceApplicationProxy.Invoke( m_serviceContext, proxy => proxy.Exec(request) ); }
public Stream TestMe() { if (WebOperationContext.Current == null) { throw new InvalidOperationException("This service operation is intended to be invoked only by REST clients."); } //If this call fails, ensure that the Service Application is started, and then do an IISReset (Yoda Says: !!Important, the last part, it is.) BaristaServiceClient client = new BaristaServiceClient(SPServiceContext.Current); var request = BrewRequest.CreateServiceApplicationRequestFromHttpRequest(HttpContext.Current.Request); request.ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52"; request.Code = "6*7"; var result = client.Eval(request); var setHeaders = true; if (WebOperationContext.Current != null) { result.ModifyOutgoingWebResponse(WebOperationContext.Current.OutgoingResponse); setHeaders = false; } result.ModifyHttpResponse(HttpContext.Current.Response, setHeaders); var resultStream = new MemoryStream(result.Content); return(resultStream); }
protected override void InternalProcessRecord() { // get the specified service context var serviceContext = ServiceContext.Read(); if (serviceContext == null) { WriteError(new InvalidOperationException("Invalid service context."), ErrorCategory.ResourceExists, null); return; } if (m_isEval && m_isExec) { WriteError(new InvalidOperationException("Can be exec or eval, but not both."), ErrorCategory.InvalidArgument, null); return; } if (m_isEval == false && m_isExec == false) { WriteError(new InvalidOperationException("Must specify either eval or exec"), ErrorCategory.InvalidArgument, null); return; } var client = new BaristaServiceClient(serviceContext); var headers = new Dictionary <string, IEnumerable <string> > { { "Content-Type", new[] { "application/json" } } }; var request = new BrewRequest { Code = m_code, Headers = new BrewRequestHeaders(headers), ScriptEngineFactory = m_scriptEngineFactory }; if (m_isEval) { var response = client.Eval(request); if (response.ContentType.StartsWith("application/json", StringComparison.InvariantCultureIgnoreCase) || response.ContentType.StartsWith("application/xml", StringComparison.InvariantCultureIgnoreCase) || response.ContentType.StartsWith("application/javascript", StringComparison.InvariantCultureIgnoreCase) || response.ContentType.StartsWith("text", StringComparison.InvariantCultureIgnoreCase)) { WriteResult(Encoding.UTF8.GetString(response.Content)); } else { WriteObject(response.Content); } } else { client.Exec(request); } }
public BrewResponse Eval(BrewRequest request) { BrewResponse result = null; // execute the call against the service app ExecuteOnChannel(channel => result = channel.Eval(request)); return(result); }
public BrewResponse Eval(BrewRequest request) { BrewResponse result = null; BaristaServiceApplicationProxy.Invoke( m_serviceContext, proxy => result = proxy.Eval(request) ); return(result); }
protected override void CreateChildControls() { if (String.IsNullOrEmpty(Code)) { return; } if (String.IsNullOrEmpty(Code.Trim())) { return; } BaristaHelper.EnsureExecutionInTrustedLocation(); string codePath; var codeToExecute = Tamp(Code, out codePath); var client = new BaristaServiceClient(SPServiceContext.Current); var request = BrewRequest.CreateServiceApplicationRequestFromHttpRequest(HttpContext.Current.Request); request.ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52"; request.Code = codeToExecute; request.CodePath = codePath; var headers = new Dictionary <string, IEnumerable <string> > { { "barista_instancemode", new[] { InstanceMode.ToString() } }, { "barista_instancename", new[] { InstanceName } }, { "barista_instanceabsoluteexpiration", new[] { InstanceAbsoluteExpiration.ToString() } }, { "barista_instanceslidingexpiration", new[] { InstanceSlidingExpiration.ToString() } } }; if (String.IsNullOrEmpty(InstanceInitializationCode) == false) { string filePath; request.InstanceInitializationCode = Tamp(InstanceInitializationCode, out filePath); request.InstanceInitializationCodePath = filePath; } request.Headers = new BrewRequestHeaders(headers); request.SetExtendedPropertiesFromCurrentSPContext(); var result = client.Eval(request); var resultText = System.Text.Encoding.UTF8.GetString(result.Content); //TODO: Based on the content type of the result, emit the contents differently. var cntrl = new LiteralControl(resultText); Controls.Add(cntrl); }
/// <summary> /// Brews a cup of coffee. E.g. Executes the specified script. /// </summary> /// <param name="code"></param> /// <param name="codePath"></param> /// <param name="requestBody"></param> public static void Brew(string code, string codePath, Stream requestBody, string scriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52") { var webContext = WebOperationContext.Current; if (webContext == null) { throw new InvalidOperationException("Current WebOperationContext is null."); } var request = BrewRequest.CreateBrewRequestFromIncomingWebRequest(webContext.IncomingRequest, requestBody, OperationContext.Current); request.ScriptEngineFactory = scriptEngineFactory; request.Code = code; request.CodePath = codePath; //If the request has a header named "X-Barista-Bootstrapper" define it on the request. var requestHeaders = webContext.IncomingRequest.Headers; var bootstrapperKey = requestHeaders.AllKeys.FirstOrDefault(k => k.ToLowerInvariant() == "X-Barista-Bootstrapper".ToLowerInvariant()); if (!String.IsNullOrWhiteSpace(bootstrapperKey)) { var bootstrapperValue = requestHeaders[bootstrapperKey]; if (!String.IsNullOrWhiteSpace(bootstrapperValue)) { request.Bootstrapper = bootstrapperValue; } } var instanceSettings = request.ParseInstanceSettings(); if (string.IsNullOrEmpty(instanceSettings.InstanceInitializationCode) == false) { string instanceInitializationCodePath; request.InstanceInitializationCode = Tamp(instanceSettings.InstanceInitializationCode, out instanceInitializationCodePath); request.InstanceInitializationCodePath = instanceInitializationCodePath; } request.SetExtendedPropertiesFromCurrentSPContext(); var client = new BaristaServiceClient(SPServiceContext.Current); client.Exec(request); //abandon the session and set the ASP.net session cookie to nothing. if (HttpContext.Current != null && HttpContext.Current.Session != null) { HttpContext.Current.Session.Abandon(); HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); } }
public static void SetExtendedPropertiesFromCurrentSPContext(this BrewRequest request) { if (request == null) { return; } if (SPContext.Current == null) { return; } if (SPContext.Current.Site != null) { request.ExtendedProperties.Add("SPSiteId", SPContext.Current.Site.ID.ToString()); request.ExtendedProperties.Add("SPUrlZone", SPContext.Current.Site.Zone.ToString()); if (SPContext.Current.Site.UserToken != null && SPContext.Current.Site.UserToken.BinaryToken != null && SPContext.Current.Site.UserToken.BinaryToken.Length > 0) { request.ExtendedProperties.Add("SPUserToken", Convert.ToBase64String(SPContext.Current.Site.UserToken.BinaryToken)); } } if (SPContext.Current.Web != null) { request.ExtendedProperties.Add("SPWebId", SPContext.Current.Web.ID.ToString()); } if (SPContext.Current.ListId != default(Guid) && SPContext.Current.ListId != Guid.Empty) { request.ExtendedProperties.Add("SPListId", SPContext.Current.ListId.ToString()); } if (String.IsNullOrEmpty(SPContext.Current.ListItemServerRelativeUrl) == false) { request.ExtendedProperties.Add("SPListItemUrl", SPContext.Current.ListItemServerRelativeUrl); } if (SPContext.Current.ViewContext != null && SPContext.Current.ViewContext.ViewId != Guid.Empty) { request.ExtendedProperties.Add("SPViewId", SPContext.Current.ViewContext.ViewId.ToString()); } if (SPContext.Current.File != null && SPContext.Current.File.UniqueId != Guid.Empty) { request.ExtendedProperties.Add("SPFileId", SPContext.Current.File.UniqueId.ToString()); } }
/// <summary> /// Brews a cup of coffee. E.g. Executes the specified script. /// </summary> /// <param name="code"></param> /// <param name="codePath"></param> private static void Brew(string code, string codePath) { var request = BrewRequest.CreateServiceApplicationRequestFromHttpRequest(HttpContext.Current.Request); request.ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52"; request.Code = code; request.CodePath = codePath; if (String.IsNullOrEmpty(request.InstanceInitializationCode) == false) { string instanceInitializationCodePath; request.InstanceInitializationCode = Tamp(request.InstanceInitializationCode, out instanceInitializationCodePath); request.InstanceInitializationCodePath = instanceInitializationCodePath; } Exec(request); }
public static void SetExtendedPropertiesFromSPItemEventProperties(this BrewRequest request, SPWeb web, SPList list, SPListItem item, SPItemEventProperties properties) { if (request == null) { return; } if (properties == null) { return; } var baristaProperties = BaristaItemEventProperties.CreateItemEventProperties(properties); var value = JsonConvert.SerializeObject(baristaProperties); if (properties.SiteId != default(Guid)) { request.ExtendedProperties.Add("SPSiteId", properties.SiteId.ToString()); } if (web != null) { request.ExtendedProperties.Add("SPWebId", web.ID.ToString()); } if (list != null) { request.ExtendedProperties.Add("SPListId", list.ID.ToString()); } if (item != null) { request.ExtendedProperties.Add("SPListItemUrl", item.Url); } request.ExtendedProperties.Add("SPItemEventProperties", value); }
/// <summary> /// Pulls a shot of espresso. E.g. Executes the specified script and sets the appropriate values on the response object. /// </summary> /// <param name="code"></param> /// <param name="codePath"></param> /// <returns></returns> private static Stream Pull(string code, string codePath) { var request = BrewRequest.CreateServiceApplicationRequestFromHttpRequest(HttpContext.Current.Request); request.ScriptEngineFactory = "Barista.SharePoint.SPBaristaScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52"; request.Code = code; request.CodePath = codePath; if (String.IsNullOrEmpty(request.InstanceInitializationCode) == false) { string instanceInitializationCodePath; request.InstanceInitializationCode = Tamp(request.InstanceInitializationCode, out instanceInitializationCodePath); request.InstanceInitializationCodePath = instanceInitializationCodePath; } var result = Eval(request); var setHeader = true; if (WebOperationContext.Current != null) { result.ModifyOutgoingWebResponse(WebOperationContext.Current.OutgoingResponse); setHeader = false; } result.ModifyHttpResponse(HttpContext.Current.Response, setHeader); if (result.Content == null) { return(null); } var resultStream = new MemoryStream(result.Content); return(resultStream); }
public static void Exec(BrewRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var response = new BrewResponse { ContentType = request.Headers.ContentType }; //Set the current context with information from the current request and response. BaristaContext.Current = new BaristaContext(request, response); var instanceSettings = BaristaContext.Current.Request.ParseInstanceSettings(); //If we're not executing with Per-Call instancing, create a mutex to synchronize against. Mutex syncRoot = null; if (instanceSettings.InstanceMode != BaristaInstanceMode.PerCall) { syncRoot = new Mutex(false, "Barista_ScriptEngineInstance_" + instanceSettings.InstanceName); } var webBundle = new BaristaWebBundle(); var source = new BaristaScriptSource(request.Code, request.CodePath); if (syncRoot != null) { syncRoot.WaitOne(); } try { bool isNewScriptEngineInstance; bool errorInInitialization; var scriptEngineFactory = new BaristaScriptEngineFactory(); var engine = scriptEngineFactory.GetScriptEngine(webBundle, out isNewScriptEngineInstance, out errorInInitialization); if (engine == null) { throw new InvalidOperationException("Unable to obtain a script engine instance."); } if (errorInInitialization) { return; } try { engine.Evaluate(source); } catch (JavaScriptException ex) { //BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.JavaScriptException, // "A JavaScript exception was thrown while evaluating script: "); scriptEngineFactory.UpdateResponseWithJavaScriptExceptionDetails(engine, ex, response); } catch (Exception ex) { //BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.Runtime, // "An internal error occured while executing script: "); scriptEngineFactory.UpdateResponseWithExceptionDetails(ex, response); } finally { //Cleanup // ReSharper disable RedundantAssignment engine = null; // ReSharper restore RedundantAssignment if (BaristaContext.Current != null) { BaristaContext.Current.Dispose(); } BaristaContext.Current = null; } } finally { if (syncRoot != null) { syncRoot.ReleaseMutex(); } } }
public static BrewResponse Eval(BrewRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var response = new BrewResponse { ContentType = request.Headers.ContentType }; BaristaContext.Current = new BaristaContext(request, response); var instanceSettings = BaristaContext.Current.Request.ParseInstanceSettings(); Mutex syncRoot = null; if (instanceSettings.InstanceMode != BaristaInstanceMode.PerCall) { syncRoot = new Mutex(false, "Barista_ScriptEngineInstance_" + instanceSettings.InstanceName); } var webBundle = new BaristaWebBundle(); var source = new BaristaScriptSource(request.Code, request.CodePath); if (syncRoot != null) { syncRoot.WaitOne(); } try { bool isNewScriptEngineInstance; bool errorInInitialization; var scriptEngineFactory = new BaristaScriptEngineFactory(); var engine = scriptEngineFactory.GetScriptEngine(webBundle, out isNewScriptEngineInstance, out errorInInitialization); if (engine == null) { throw new InvalidOperationException("Unable to obtain a script engine instance."); } if (errorInInitialization) { return(response); } try { var result = engine.Evaluate(source); var isRaw = false; //If the web instance has been initialized on the web bundle, use the value set via script, otherwise use defaults. if (webBundle.WebInstance == null || webBundle.WebInstance.Response.AutoDetectContentType) { response.ContentType = BrewResponse.AutoDetectContentTypeFromResult(result, response.ContentType); var arrayResult = result as Barista.Library.Base64EncodedByteArrayInstance; if (arrayResult != null && arrayResult.FileName.IsNullOrWhiteSpace() == false && response.Headers != null && response.Headers.ContainsKey("Content-Disposition") == false) { var br = BrowserUserAgentParser.GetDefault(); var clientInfo = br.Parse(request.Headers.UserAgent); if (clientInfo.UserAgent.Family == "IE" && (clientInfo.UserAgent.Major == "7" || clientInfo.UserAgent.Major == "8")) { response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(arrayResult.FileName)); } else if (clientInfo.UserAgent.Family == "Safari") { response.Headers.Add("Content-Disposition", "attachment; filename=" + arrayResult.FileName); } else { response.Headers.Add("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(arrayResult.FileName) + "\""); } } } if (webBundle.WebInstance != null) { isRaw = webBundle.WebInstance.Response.IsRaw; } response.SetContentsFromResultObject(engine, result, isRaw); } catch (JavaScriptException ex) { //BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.JavaScriptException, "A JavaScript exception was thrown while evaluating script: "); scriptEngineFactory.UpdateResponseWithJavaScriptExceptionDetails(engine, ex, response); } catch (Exception ex) { //BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.Runtime, "An internal error occurred while evaluating script: "); scriptEngineFactory.UpdateResponseWithExceptionDetails(ex, response); } finally { //Cleanup // ReSharper disable RedundantAssignment engine = null; // ReSharper restore RedundantAssignment if (BaristaContext.Current != null) { BaristaContext.Current.Dispose(); } BaristaContext.Current = null; } } finally { if (syncRoot != null) { syncRoot.ReleaseMutex(); } } return(response); }
public void Exec(BrewRequest request) { // execute the call against the service app ExecuteOnChannel(channel => channel.Exec(request)); }
public BrewResponse Eval(BrewRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var response = new BrewResponse { ContentType = request.Headers.ContentType }; SPBaristaContext.Current = new SPBaristaContext(request, response); var instanceSettings = SPBaristaContext.Current.Request.ParseInstanceSettings(); Mutex syncRoot = null; if (instanceSettings.InstanceMode != BaristaInstanceMode.PerCall) { syncRoot = new Mutex(false, "Barista_ScriptEngineInstance_" + instanceSettings.InstanceName); } var webBundle = new SPWebBundle(); var source = new BaristaScriptSource(request.Code, request.CodePath); if (syncRoot != null) { syncRoot.WaitOne(); } try { bool isNewScriptEngineInstance; bool errorInInitialization; if (request.ScriptEngineFactory.IsNullOrWhiteSpace()) { throw new InvalidOperationException("A ScriptEngineFactory must be specified as part of a BrewRequest."); } var baristaScriptEngineFactoryType = Type.GetType(request.ScriptEngineFactory, true); if (baristaScriptEngineFactoryType == null) { throw new InvalidOperationException("Unable to locate the specified ScriptEngineFactory: " + request.ScriptEngineFactory); } var scriptEngineFactory = (ScriptEngineFactory)Activator.CreateInstance(baristaScriptEngineFactoryType); var engine = scriptEngineFactory.GetScriptEngine(webBundle, out isNewScriptEngineInstance, out errorInInitialization); if (engine == null) { throw new InvalidOperationException("Unable to obtain a script engine instance."); } if (errorInInitialization) { return(response); } if (engine is EdgeJSScriptEngine) { SetBaristaV2Flags(source, request, response); } try { //Default execution timeout to be 60 seconds. if (request.ExecutionTimeout <= 0) { request.ExecutionTimeout = 60 * 1000; } object result; using (new SPMonitoredScope("Barista Script Eval", request.ExecutionTimeout, new SPCriticalTraceCounter(), new SPExecutionTimeCounter(request.ExecutionTimeout), new SPRequestUsageCounter(), new SPSqlQueryCounter())) { //var mre = new ManualResetEvent(false); //var scopeEngine = engine; //var actionThread = new Thread(() => //{ // result = scopeEngine.Evaluate(source); //always call endinvoke // mre.Set(); //}); //actionThread.Start(); //mre.WaitOne(TimeSpan.FromMilliseconds(request.ExecutionTimeout)); //if (actionThread.IsAlive) // actionThread.Abort(); result = engine.Evaluate(source); } if (engine is EdgeJSScriptEngine) { //EdgeJSScriptEngine takes care of itself, just need to set the response as the response object. if (result != null) { var resultData = (dynamic)result; response = JsonConvert.DeserializeObject <BrewResponse>((string)resultData.response); } } else { var isRaw = false; //If the web instance has been initialized on the web bundle, use the value set via script, otherwise use defaults. if (webBundle.WebInstance == null || webBundle.WebInstance.Response.AutoDetectContentType) { response.ContentType = BrewResponse.AutoDetectContentTypeFromResult(result, response.ContentType); var arrayResult = result as Barista.Library.Base64EncodedByteArrayInstance; if (arrayResult != null) { if (arrayResult.FileName.IsNullOrWhiteSpace() == false && response.Headers != null && response.Headers.ContainsKey("Content-Disposition") == false) { var br = BrowserUserAgentParser.GetDefault(); var clientInfo = br.Parse(request.Headers.UserAgent); if (clientInfo.UserAgent.Family == "IE" && (clientInfo.UserAgent.Major == "7" || clientInfo.UserAgent.Major == "8")) { response.Headers.Add("Content-Disposition", "attachment; filename=" + Barista.Helpers.HttpUtility.UrlEncode(arrayResult.FileName)); } else if (clientInfo.UserAgent.Family == "Safari") { response.Headers.Add("Content-Disposition", "attachment; filename=" + arrayResult.FileName); } else { response.Headers.Add("Content-Disposition", "attachment; filename=\"" + Barista.Helpers.HttpUtility.UrlEncode(arrayResult.FileName) + "\""); } } //Set the ETag on the response if the Base64EncodedByteArrayInstance defines an ETag and one has not already been set. if (arrayResult.ETag.IsNullOrWhiteSpace() == false && response.Headers != null && response.Headers.ContainsKey("ETag") == false) { response.Headers.Add("ETag", arrayResult.ETag); } } } if (webBundle.WebInstance != null) { isRaw = webBundle.WebInstance.Response.IsRaw; } response.SetContentsFromResultObject(engine, result, isRaw); } } catch (JavaScriptException ex) { try { BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.JavaScriptException, "A JavaScript exception was thrown while evaluating script: "); } catch { //Do Nothing... } scriptEngineFactory.UpdateResponseWithJavaScriptExceptionDetails(engine, ex, response); } catch (Exception ex) { try { BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.Runtime, "An internal error occurred while evaluating script: "); } catch { //Do Nothing... } scriptEngineFactory.UpdateResponseWithExceptionDetails(ex, response); } finally { var engineDisposable = engine as IDisposable; if (engineDisposable != null) { engineDisposable.Dispose(); } //Cleanup // ReSharper disable RedundantAssignment engine = null; // ReSharper restore RedundantAssignment if (SPBaristaContext.Current != null) { SPBaristaContext.Current.Dispose(); } SPBaristaContext.Current = null; } } finally { if (syncRoot != null) { syncRoot.ReleaseMutex(); } } return(response); }
public void Exec(BrewRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var response = new BrewResponse { ContentType = request.Headers.ContentType }; //Set the current context with information from the current request and response. SPBaristaContext.Current = new SPBaristaContext(request, response); var instanceSettings = SPBaristaContext.Current.Request.ParseInstanceSettings(); //If we're not executing with Per-Call instancing, create a mutex to synchronize against. Mutex syncRoot = null; if (instanceSettings.InstanceMode != BaristaInstanceMode.PerCall) { syncRoot = new Mutex(false, "Barista_ScriptEngineInstance_" + instanceSettings.InstanceName); } SPBaristaContext.Current.WebBundle = new SPWebBundle(); var source = new BaristaScriptSource(request.Code, request.CodePath); if (syncRoot != null) { syncRoot.WaitOne(); } try { bool isNewScriptEngineInstance; bool errorInInitialization; var baristaScriptEngineFactoryType = Type.GetType("Barista.SharePoint.SPBaristaScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52", true); if (baristaScriptEngineFactoryType == null) { throw new InvalidOperationException("Unable to locate the SPBaristaScriptEngineFactory"); } var scriptEngineFactory = (ScriptEngineFactory)Activator.CreateInstance(baristaScriptEngineFactoryType); var engine = scriptEngineFactory.GetScriptEngine(SPBaristaContext.Current.WebBundle, out isNewScriptEngineInstance, out errorInInitialization); if (engine == null) { throw new InvalidOperationException("Unable to obtain an instance of a Script Engine."); } if (errorInInitialization) { return; } try { using (new SPMonitoredScope("Barista Script Exec", 110000, new SPCriticalTraceCounter(), new SPExecutionTimeCounter(), new SPRequestUsageCounter(), new SPSqlQueryCounter())) { engine.Evaluate(source); } } catch (JavaScriptException ex) { try { BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.JavaScriptException, "A JavaScript exception was thrown while evaluating script: "); } catch { //Do Nothing... } scriptEngineFactory.UpdateResponseWithJavaScriptExceptionDetails(engine, ex, response); } catch (Exception ex) { try { BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.Runtime, "An internal error occured while executing script: "); } catch { //Do Nothing... } scriptEngineFactory.UpdateResponseWithExceptionDetails(ex, response); } finally { //Cleanup // ReSharper disable RedundantAssignment engine = null; // ReSharper restore RedundantAssignment if (SPBaristaContext.Current != null) { SPBaristaContext.Current.Dispose(); } SPBaristaContext.Current = null; } } finally { if (syncRoot != null) { syncRoot.ReleaseMutex(); } } }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { Result = String.Empty; // get all of the information we currently have about the item // that this workflow is running on var listGuid = new Guid(__ListId); var web = __Context.Web; var myList = __Context.Web.Lists[listGuid]; var myItem = __Context.GetListItem(myList, __ListItem); var serviceContext = SPServiceContext.GetContext(__Context.Site); var client = new BaristaServiceClient(serviceContext); var headers = new Dictionary <string, IEnumerable <string> > { { "Content-Type", new[] { "application/json" } } }; var request = new BrewRequest { Code = Code, Headers = new BrewRequestHeaders(headers), Body = Encoding.UTF8.GetBytes(Body), ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52", ExtendedProperties = new Dictionary <string, string> { { "SPSiteId", __Context.Site.ID.ToString() }, { "SPUrlZone", __Context.Site.Zone.ToString() }, { "SPUserToken", Convert.ToBase64String(__Context.Site.UserToken.BinaryToken) }, { "SPWebId", web.ID.ToString() }, { "SPListId", __ListId }, { "SPListItemUrl", myItem.Url }, { "SPWorkflowAssociationTitle", __Context.AssociationTitle }, { "SPWorkflowInstanceId", __Context.WorkflowInstanceId.ToString() }, { "SPWorkflowCurrentItemUrl", __Context.CurrentItemUrl }, { "SPWorkflowCurrentWebUrl", __Context.CurrentWebUrl }, { "SPWorkflowItemName", __Context.ItemName }, { "SPWorkflowTaskListGuid", __Context.TaskListGuid }, { "SPWorkflowStatusUrl", __Context.WorkflowStatusUrl }, { "SPWorkflowAssociatorUserLoginName", __Context.AssociatorUser.LoginName }, { "SPWorkflowInitiatorUserLoginName", __Context.InitiatorUser.LoginName }, { "SPWorkflowItemId", __Context.ItemId.ToString(CultureInfo.InvariantCulture) }, { "SPWorkflowStartedDateTime", __Context.StartedDateTime.ToUniversalTime().ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz") }, { "SPWorkflowLastRunDateTime", __Context.LastRunDateTime.ToUniversalTime().ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz") } } }; var response = client.Eval(request); if (response.StatusCode == HttpStatusCode.BadRequest && response.ExtendedProperties.ContainsKey("Exception_Message")) { var wfService = executionContext.GetService <ISharePointService>(); wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Message", response.ExtendedProperties["Exception_Message"], ""); wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Name", response.ExtendedProperties["Exception_Name"], ""); wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Function Name", response.ExtendedProperties["Exception_FunctionName"], ""); wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Line Number", response.ExtendedProperties["Exception_LineNumber"], ""); wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Source Path", response.ExtendedProperties["Exception_SourcePath"], ""); wfService.LogToHistoryList(executionContext.ContextGuid, SPWorkflowHistoryEventType.WorkflowError, 0, TimeSpan.Zero, "Stack Trace", response.ExtendedProperties["Exception_StackTrace"], ""); return(ActivityExecutionStatus.Faulting); } Result = Encoding.UTF8.GetString(response.Content); return(ActivityExecutionStatus.Closed); }
/// <summary> /// Pulls a shot of espresso. E.g. Executes the specified script and sets the appropriate values on the response object. /// </summary> /// <param name="code"></param> /// <param name="codePath"></param> /// <param name="requestBody"></param> /// <returns></returns> public static Message Pull(string code, string codePath, Stream requestBody, string scriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52") { var webContext = WebOperationContext.Current; if (webContext == null) { throw new InvalidOperationException("Current WebOperationContext is null."); } var request = BrewRequest.CreateBrewRequestFromIncomingWebRequest(webContext.IncomingRequest, requestBody, OperationContext.Current); request.ScriptEngineFactory = scriptEngineFactory; request.Code = code; request.CodePath = codePath; var instanceSettings = request.ParseInstanceSettings(); if (string.IsNullOrEmpty(instanceSettings.InstanceInitializationCode) == false) { string instanceInitializationCodePath; request.InstanceInitializationCode = Tamp(instanceSettings.InstanceInitializationCode, out instanceInitializationCodePath); request.InstanceInitializationCodePath = instanceInitializationCodePath; } request.SetExtendedPropertiesFromCurrentSPContext(); //Make a call to the Barista Service application to handle the request. var client = new BaristaServiceClient(SPServiceContext.Current); var result = client.Eval(request); //abandon the session and set the ASP.net session cookie to nothing. var cookies = new List <IBaristaCookie>(); cookies.AddRange(result.Cookies); var existingCookie = cookies.FirstOrDefault(c => c != null && c.Name == "ASP.NET_SessionId"); if (existingCookie != null) { cookies.Remove(existingCookie); } cookies.Add(new Biscotti("ASP.NET_SessionId", "")); result.Cookies = cookies; result.ModifyOutgoingWebResponse(webContext.OutgoingResponse); //if (HttpContext.Current != null && HttpContext.Current.Session != null) //{ // HttpContext.Current.Session.Abandon(); // HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); //} return(webContext.CreateStreamResponse( stream => { if (result.Content == null) { return; } using (var writer = new BinaryWriter(stream)) { writer.Write(result.Content); } }, result.ContentType ?? string.Empty)); }
public SPBaristaContext(BrewRequest request, BrewResponse response) : base(request, response) { if (request.ExtendedProperties == null || !request.ExtendedProperties.ContainsKey("SPSiteId")) { return; } var siteId = new Guid(request.ExtendedProperties["SPSiteId"]); if (siteId != Guid.Empty) { SPUrlZone siteUrlZone; if (request.ExtendedProperties.ContainsKey("SPUrlZone") && request.ExtendedProperties["SPUrlZone"].TryParseEnum(true, SPUrlZone.Default, out siteUrlZone)) { if (request.ExtendedProperties.ContainsKey("SPUserToken")) { var tokenBytes = Convert.FromBase64String(request.ExtendedProperties["SPUserToken"]); var userToken = new SPUserToken(tokenBytes); Site = new SPSite(siteId, siteUrlZone, userToken); } else { Site = new SPSite(siteId, siteUrlZone); } } } if (!request.ExtendedProperties.ContainsKey("SPWebId")) { return; } var webId = new Guid(request.ExtendedProperties["SPWebId"]); if (webId != Guid.Empty) { Web = Site.OpenWeb(webId); } if (request.ExtendedProperties.ContainsKey("SPListId")) { var listId = new Guid(request.ExtendedProperties["SPListId"]); if (listId != Guid.Empty) { List = Web.Lists[listId]; } if (request.ExtendedProperties.ContainsKey("SPViewId")) { var viewId = new Guid(request.ExtendedProperties["SPViewId"]); if (viewId != Guid.Empty) { View = List.Views[viewId]; } } } if (request.ExtendedProperties.ContainsKey("SPListItemUrl")) { var url = request.ExtendedProperties["SPListItemUrl"]; if (String.IsNullOrEmpty(url) == false) { Uri listItemUri; //In the two places this gets used, this is a site-relative URL. if (Uri.TryCreate(new Uri(Web.Url.EnsureEndsWith("/")), url.EnsureStartsWith("/"), out listItemUri)) { try { ListItem = Web.GetListItem(listItemUri.ToString()); } catch (FileNotFoundException) { //Do Nothing.. } } } } if (!request.ExtendedProperties.ContainsKey("SPFileId")) { return; } var fileId = new Guid(request.ExtendedProperties["SPFileId"]); if (fileId != Guid.Empty) { File = Web.GetFile(fileId); } }