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 override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // install the service
            var service = BaristaHelper.GetBaristaService(SPFarm.Local);

            if (service == null)
            {
                service = new BaristaService(SPFarm.Local);
                service.Update(true);
            }


            // install the service proxy
            var serviceProxy = BaristaHelper.GetBaristaServiceProxy(SPFarm.Local);

            if (serviceProxy == null)
            {
                serviceProxy = new BaristaServiceProxy(SPFarm.Local);
                serviceProxy.Update(true);
            }


            // with service added to the farm, install instance
            var serviceInstance = new BaristaServiceInstance(SPServer.Local, service);

            serviceInstance.Update(true);
        }
        public object ListPackages()
        {
            var objBundles = BaristaHelper.ListPackages();

            var bundlesString = objBundles.ToString();

            return(JSONObject.Parse(Engine, bundlesString, null));
        }
        public object InstallBundle(Jurassic.ScriptEngine engine)
        {
            engine.SetGlobalValue("SearchArguments", new SearchArgumentsConstructor(engine));
            engine.SetGlobalValue("JsonDocument", new JsonDocumentConstructor(engine));

            var searchServiceInstance = new SearchServiceInstance(engine.Object.InstancePrototype,
                                                                  new SPBaristaSearchServiceProxy())
            {
                GetIndexDefinitionFromName = indexName => BaristaHelper.GetBaristaIndexDefinitionFromIndexName(indexName)
            };

            return(searchServiceInstance);
        }
        public object GetPackageInfo(string packageId)
        {
            var objBundles = BaristaHelper.GetPackageInfo(packageId);

            if (objBundles == null)
            {
                return(Undefined.Value);
            }

            var bundlesString = objBundles.ToString();

            return(JSONObject.Parse(Engine, bundlesString, null));
        }
        /// <summary>
        /// Takes an order. E.g. Asserts that the current web is valid, the user has read permissions on the current web, and the current web is a trusted location.
        /// </summary>
        public static void TakeOrder()
        {
            if (SPContext.Current == null || SPContext.Current.Web == null)
            {
                throw new InvalidOperationException("Cannot execute Barista: Barista must execute within the context of a SharePoint Web.");
            }

            if (SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.Open) == false)
            {
                throw new InvalidOperationException("Cannot execute Barista: Access Denied - The current user does not have access to the current web.");
            }

            BaristaHelper.EnsureExecutionInTrustedLocation();
        }
        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);
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // uninstall the instance
            var serviceInstance = BaristaHelper.GetBaristaServiceInstance(SPFarm.Local);

            if (serviceInstance != null)
            {
                serviceInstance.Delete();
                SPServer.Local.ServiceInstances.Remove(serviceInstance.Id);
            }

            // uninstall the service proxy
            var serviceProxy = BaristaHelper.GetBaristaServiceProxy(SPFarm.Local);

            if (serviceProxy != null)
            {
                serviceProxy.Delete();
                SPFarm.Local.ServiceProxies.Remove(serviceProxy.Id);
            }

            // uninstall the service
            var service = BaristaHelper.GetBaristaService(SPFarm.Local);

            if (service == null)
            {
                return;
            }

            if (service.Instances.Count != 0)
            {
                foreach (var remainingInstance in service.Instances)
                {
                    SPServer.Local.ServiceInstances.Remove(remainingInstance.Id);
                }
            }
            service.Delete();
            SPFarm.Local.Services.Remove(service.Id);
        }
        public Message Status()
        {
            var webContext = WebOperationContext.Current;

            if (webContext == null)
            {
                throw new InvalidOperationException("Current WebOperationContext is null.");
            }

            var result = new JObject();

            var environment = new JObject
            {
                { "commandLine", Environment.CommandLine },
                { "currentDirectory", Environment.CurrentDirectory },
                { "machineName", Environment.MachineName },
                { "newLine", Environment.NewLine },
                {
                    "osVersion", new JObject
                    {
                        { "platform", Environment.OSVersion.Platform.ToString() },
                        { "servicePack", Environment.OSVersion.ServicePack },
                        { "version", Environment.OSVersion.Version.ToString() },
                        { "versionString", Environment.OSVersion.VersionString }
                    }
                },
                { "processorCount", Environment.ProcessorCount },
                { "systemDirectory", Environment.SystemDirectory },
                { "tickCount", Environment.TickCount },
                { "userDomainName", Environment.UserDomainName },
                { "userInteractive", Environment.UserInteractive },
                { "userName", Environment.UserName },
                { "version", Environment.Version.ToString() },
                { "workingSet", Environment.WorkingSet },
                { "currentThreadId", System.Threading.Thread.CurrentThread.ManagedThreadId }
            };

            //try
            //{
            //    var cpuCounter = new PerformanceCounter
            //    {
            //        CategoryName = "Processor",
            //        CounterName = "% Processor Time",
            //        InstanceName = "_Total"
            //    };

            //    var firstValue = cpuCounter.NextValue();
            //    System.Threading.Thread.Sleep(1000);
            //    environment.Add("processorPct", cpuCounter.NextValue());

            //    PerformanceCounter memoryCounter = new PerformanceCounter
            //    {
            //        CategoryName = "Memory",
            //        CounterName = "Available MBytes"
            //    };

            //    environment.Add("availableMBytes", memoryCounter.NextValue());
            //}
            //catch {/* Do Nothing */}

            result.Add("environment", environment);

            var webContextObject = new JObject();

            var queryParameters        = new JObject();
            var requestQueryParameters = webContext.IncomingRequest.UriTemplateMatch.QueryParameters;

            foreach (var key in requestQueryParameters.AllKeys)
            {
                queryParameters.Add(key, requestQueryParameters[key]);
            }
            webContextObject.Add("queryParameters", queryParameters);

            var headers        = new JObject();
            var requestHeaders = webContext.IncomingRequest.Headers;

            foreach (var key in requestHeaders.AllKeys)
            {
                headers.Add(key, requestHeaders[key]);
            }
            webContextObject.Add("headers", headers);

            result.Add("webContext", webContextObject);

            var sharepoint = new JObject();

            var servers = new JArray();

            foreach (var spServer in SPFarm.Local.Servers)
            {
                JObject server;
                try
                {
                    server = new JObject
                    {
                        { "id", spServer.Id },
                        { "address", spServer.Address },
                        { "name", spServer.Name },
                        { "needsUpgrade", spServer.NeedsUpgrade },
                        //{"needsUpgradeIncludeChildren", spServer.NeedsUpgradeIncludeChildren},
                        { "version", spServer.Version },
                        { "role", spServer.Role.ToString() }
                    };
                }
                catch (Exception ex)
                {
                    server = new JObject
                    {
                        { "id", spServer.Id },
                        { "address", spServer.Address },
                        { "name", spServer.Name },
                        { "exception", ex.Message },
                        { "stackTrace", ex.StackTrace }
                    };
                }

                servers.Add(server);
            }

            sharepoint.Add("serversInFarm", servers);

            try
            {
                sharepoint.Add("SPBuildVersion", SPFarm.Local.BuildVersion.ToString());
                var baristaService = BaristaHelper.GetBaristaService(SPFarm.Local);
                sharepoint.Add("baristaService", GetSharePointServiceRepresentation(baristaService));
            }
            catch
            {
                //Do Nothing
            }

            try
            {
                var baristaSearchService = BaristaHelper.GetBaristaSearchService(SPFarm.Local);
                sharepoint.Add("baristaSearchService", GetSharePointServiceRepresentation(baristaSearchService));
            }
            catch
            {
                //Do Nothing
            }

            result.Add("sharepoint", sharepoint);


            //trusted locations config

            var    codeValue = BaristaServiceRequestPipeline.Grind(null, false);
            string scriptPath;
            var    whatIf = new JObject();

            whatIf.Add("codeValue", codeValue);
            whatIf.Add("codeContents", BaristaServiceRequestPipeline.Tamp(codeValue, out scriptPath));
            whatIf.Add("finalScriptPath", scriptPath);
            result.Add("whatIf", whatIf);

            return(webContext.CreateStreamResponse(
                       stream =>
            {
                var js = new JsonSerializer
                {
                    Formatting = Formatting.Indented
                };

                using (var sw = new StreamWriter(stream))
                {
                    js.Serialize(sw, result);
                }
            },
                       "application/json"));
        }
        public string ListPackages()
        {
            var objResult = BaristaHelper.ListPackages();

            return(objResult.ToString(Formatting.Indented));
        }