コード例 #1
0
 public HttpResponseInstance(ScriptEngine engine, BrewResponse response)
     : base(engine)
 {
     this.AutoDetectContentType = true;
     this.Response = response;
     this.PopulateFunctions();
     this.StatusCode = 200;
 }
コード例 #2
0
        public BrewResponse Eval(BrewRequest request)
        {
            BrewResponse result = null;

            // execute the call against the service app
            ExecuteOnChannel(channel => result = channel.Eval(request));

            return(result);
        }
コード例 #3
0
        public BrewResponse Eval(BrewRequest request)
        {
            BrewResponse result = null;

            BaristaServiceApplicationProxy.Invoke(
                m_serviceContext,
                proxy => result = proxy.Eval(request)
                );
            return(result);
        }
コード例 #4
0
        public async Task Invoke(HttpContext context)
        {
            var brewContext = context.Items[BrewKeys.BrewContext] as BaristaContext;

            if (brewContext == null)
            {
                throw new InvalidOperationException("BrewContext was not defined within the http context.");
            }

            var brewResult = context.Items[BrewKeys.BrewResult] as JsValue;

            if (brewResult is JsObject jsObject &&
                jsObject.TryGetBean(out JsExternalObject exObj) &&
                exObj.Target is BrewResponse brewResponseObj
                )
            {
                BrewResponse.PopulateHttpResponse(context.Response, brewContext, brewResponseObj);
                return;
            }
コード例 #5
0
        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();
                }
            }
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        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);
            }
        }
コード例 #8
0
        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();
                }
            }
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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"
            });
        }