public string BuildEndpoint(RestClient client) { var sb = new StringBuilder(); var path = Path.IsNullOrBlank() ? client.Path.IsNullOrBlank() ? "" : client.Path : Path; var versionPath = VersionPath.IsNullOrBlank() ? client.VersionPath.IsNullOrBlank() ? "" : client.VersionPath : VersionPath; var skipAuthority = client.Authority.IsNullOrBlank(); sb.Append(skipAuthority ? "" : client.Authority); sb.Append(skipAuthority ? "" : client.Authority.EndsWith("/") ? "" : "/"); sb.Append(skipAuthority ? "" : versionPath.IsNullOrBlank() ? "" : versionPath); if (!skipAuthority && !versionPath.IsNullOrBlank()) { sb.Append(versionPath.EndsWith("/") ? "" : "/"); } sb.Append(path.IsNullOrBlank() ? "" : path.StartsWith("/") ? path.Substring(1) : path); var queryStringHandling = QueryHandling ?? client.QueryHandling ?? Hammock.QueryHandling.None; switch (queryStringHandling) { case Hammock.QueryHandling.AppendToParameters: return(WebExtensions.UriMinusQuery(sb.ToString(), Parameters)); default: return(sb.ToString()); } }
public override void WithResolvingModelHost(object modelHost, DefinitionBase model, Type childModelType, Action <object> action) { if (modelHost is SecurableObject) { var securityGroupLinkModel = model as SecurityGroupLinkDefinition; if (securityGroupLinkModel == null) { throw new ArgumentException("model has to be SecurityGroupDefinition"); } var web = GetWebFromSPSecurableObject(modelHost as SecurableObject); var context = web.Context; context.Load(web, w => w.SiteGroups); context.ExecuteQuery(); var securityGroup = WebExtensions.FindGroupByName(web.SiteGroups, securityGroupLinkModel.SecurityGroupName); var newModelHost = new SecurityGroupModelHost { SecurableObject = modelHost as SecurableObject, SecurityGroup = securityGroup }; action(newModelHost); } else { action(modelHost); } }
static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("USAGE: ValidateAssemblyBindings <appConfigFileName>"); Console.WriteLine(); Console.WriteLine(" Example: ValidateAssemblyBindings openPDC.exe.config"); Console.WriteLine(); return(1); } try { string appConfigFileName = FilePath.GetAbsolutePath(args[0]); if (!File.Exists(appConfigFileName)) { throw new FileNotFoundException($"Application configuration file name \"{appConfigFileName}\" not found."); } Console.WriteLine($"Updating assembly bindings for \"{appConfigFileName}\""); bool result = WebExtensions.ValidateAssemblyBindings(appConfigFileName); Console.WriteLine($"Assembly bindings update {(result ? "succeeded" : "failed")}."); return(result ? 0 : 3); } catch (Exception ex) { Console.WriteLine($"ERROR: Failed to validate assembly bindings: {ex.Message}"); Console.WriteLine(); return(2); } }
protected override void Render(HtmlTextWriter writer) { using (WebExtensions.GetEditableWrapper(CurrentItem, Editable && ControlPanel.GetState(this) == ControlPanelState.DragDrop, PropertyName, Displayable, writer)) { string format = Format; if (!string.IsNullOrEmpty(format)) { int index = format.IndexOf("{0}"); if (index > 0) { writer.Write(format.Substring(0, index)); base.Render(writer); writer.Write(format.Substring(index + 3)); } else { writer.Write(format); } } else { base.Render(writer); } } }
public GitlabRepo() : base(RepoType.Gitlab) { try { treeUrl = "https://gitlab.com/api/v3/projects/{0}/repository/tree?ref={1}&recursive=1"; tagUrl = "https://gitlab.com/api/v3/projects/{0}/repository/tags"; fileUrl = "https://gitlab.com/api/v3/projects/{0}/repository/files?ref={1}&file_path={2}"; string html = WebExtensions.DownloadString(Program.appArgs.RepoUrl); if (string.IsNullOrEmpty(html)) { throw new Exception("There was a problem downloading html from the Gitlab repo!"); } CQ doc = CQ.Create(html), element = doc["input[name=project_id]"]; if (element == null) { throw new Exception( string.Format( "[{0}] You hadn't passed a valid Gitlab project url! Please, specify only the root: http://gitlab.com/Author/Repository_name/, if the problem persists, please tell it to the owner!", Program.appArgs.RepoUrl)); } RepoID = int.Parse(element[0].Attributes["value"]); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// 基于Combres的ResourceName引入js/css /// </summary> /// <param name="resourceType"><see cref="PageResourceType"/></param> /// <param name="resouceSetName">Combres中设置的ResourceSet</param> /// <param name="debugResouceSetName">debug时使用的ResouceSetName</param> /// <param name="renderPriority">呈现优先级</param> /// <param name="renderLocation">在页面中的呈现位置</param> /// <param name="htmlAttributes">设置的html属性</param> public void IncludeCombresResouceSet(PageResourceType resourceType, string resouceSetName, string debugResouceSetName = null, ResourceRenderPriority renderPriority = ResourceRenderPriority.Unspecified, ResourceRenderLocation renderLocation = ResourceRenderLocation.Head, IDictionary <string, string> htmlAttributes = null) { if (string.IsNullOrEmpty(resouceSetName)) { throw new ArgumentNullException("resouceSetName"); } string url = WebExtensions.CombresUrl(resouceSetName); string debugUrl = null; if (debugResouceSetName != null) { debugUrl = WebExtensions.CombresUrl(debugResouceSetName); } ResourceEntry resource = new ResourceEntry(resourceType, null, url, debugUrl, renderPriority, renderLocation, htmlAttributes); switch (resourceType) { case PageResourceType.JS: _includedScripts.Add(resource); break; case PageResourceType.CSS: _includedCsss.Add(resource); break; } }
//выборка данных и занесение их во временную таблицу, с которой далее будет работать приложение (для ускорения выполнения запросов) public async Task CreateTempDataTable(string aptekaId, string RegionId) { using (SqlConnection connection = new SqlConnection(connectionString)) { try { await connection.OpenAsync(); SqlCommand query = new SqlCommand(); query.CommandText = SqlCommandText.ForCreateTempDataTable1; query.Connection = connection; query.Parameters.AddWithValue("aptekaId", int.Parse(aptekaId)); query.Parameters.AddWithValue("regionId", int.Parse(RegionId)); query.Parameters.AddWithValue("tableName", "tmp_gnvls_" + aptekaId); await query.ExecuteNonQueryAsync(); } catch (SqlException) { string message = DateTime.Now + " Произошла ошибка при создании временной таблицы " + Environment.NewLine; WebExtensions.WriteToLog(logPath, message); throw; } catch (Exception) { throw; } } }
/// <summary> /// Check application for update. Installs the latest installer to user downloads folder and opens the file before closing this instance /// </summary> public static void CheckForUpdate() { try { Program.Log.Info("Checking for update"); var newVersion = new Version(); var request = WebExtensions.GetRequest(UrlLatestVersion); using (WebResponse webResponse = request.GetResponse()) using (var reader = new StreamReader(webResponse.GetResponseStream())) { newVersion = new Version(reader.ReadToEnd()); Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (curVersion.CompareTo(newVersion) < 0) { RunLatestInstaller(newVersion); } else { Program.Log.InfoFormat("Running the latest version: {0}", newVersion.ToString()); } } } catch (Exception ex) { Program.Log.Error("Failed ", ex); MessageBox.Show("There was an issue checking for update. You will be redirected to the latest available version download page."); Process.Start($"{OpenLink.UrlGitHub}releases/latest"); Application.Exit(); } }
public void Render(RenderingContext context, TextWriter writer) { var tw = WebExtensions.GetEditableWrapper(context.Content, context.IsEditable, context.PropertyName, context.Displayable, writer); using (tw) { var renderer = ResolveRenderer(context.Displayable.GetType()); renderer.Render(context, writer); } }
/// <summary>Begins an editable wrapper that can be used to edit a single property in a view.</summary> /// <param name="html"></param> /// <param name="item"></param> /// <param name="displayableName"></param> /// <returns>A disposable object that must be called to close the editable wrapper element.</returns> public static IDisposable BeginEditableWrapper(this HtmlHelper html, ContentItem item, string displayableName) { if (ControlPanel.GetState(html.ContentEngine()) == ControlPanelState.DragDrop) { return(WebExtensions.GetEditableWrapper(item, true, displayableName, html.ContentEngine().Definitions.GetDefinition(item).Displayables[displayableName], html.ViewContext.Writer)); } else { return(new EmptyDisposable()); } }
public static bool IsFileRequest(Uri uri) { string absolutePath = uri.AbsolutePath; if (string.IsNullOrWhiteSpace(absolutePath)) { return(false); } string extension = Path.GetExtension(absolutePath); return(!string.IsNullOrWhiteSpace(extension) && !WebExtensions.Contains(extension)); }
protected virtual Group ResolveSecurityGroup(SecurityGroupLinkDefinition securityGroupLinkModel, Web web, ClientRuntimeContext context) { Group securityGroup = null; if (securityGroupLinkModel.IsAssociatedMemberGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup = true. Resolving AssociatedMemberGroup"); context.Load(web, w => w.AssociatedMemberGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedMemberGroup; } else if (securityGroupLinkModel.IsAssociatedOwnerGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedOwnerGroup = true. Resolving IsAssociatedOwnerGroup"); context.Load(web, w => w.AssociatedOwnerGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedOwnerGroup; } else if (securityGroupLinkModel.IsAssociatedVisitorGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedVisitorGroup = true. Resolving IsAssociatedVisitorGroup"); context.Load(web, w => w.AssociatedVisitorGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedVisitorGroup; } else if (!string.IsNullOrEmpty(securityGroupLinkModel.SecurityGroupName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving group by name: [{0}]", securityGroupLinkModel.SecurityGroupName); securityGroup = WebExtensions.FindGroupByName(web.SiteGroups, securityGroupLinkModel.SecurityGroupName); } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup/IsAssociatedOwnerGroup/IsAssociatedVisitorGroup/SecurityGroupName should be defined. Throwing SPMeta2Exception"); throw new SPMeta2Exception("securityGroupLinkModel"); } return(securityGroup); }
private async Task <Stream> OpenResourceAsync(string fileName, bool embeddedResource, CancellationToken cancellationToken) { Stream stream = embeddedResource ? WebExtensions.OpenEmbeddedResourceStream(fileName) : File.OpenRead(fileName); if (!(m_releaseMode || m_options.UseMinifyInDebug) || !(m_options.MinifyJavascript || m_options.MinifyStyleSheets)) { return(stream); } string extension = FilePath.GetExtension(fileName).Trim().ToLowerInvariant(); if (string.IsNullOrWhiteSpace(extension)) { return(stream); } Minifier minifier = new Minifier(); Stream minimizedStream = null; switch (extension) { case ".js": if (m_options.MinifyJavascript) { await Task.Run(async() => { using (StreamReader reader = new StreamReader(stream)) minimizedStream = await minifier.MinifyJavaScript(await reader.ReadToEndAsync()).ToStreamAsync(); }, cancellationToken); } break; case ".css": if (m_options.MinifyStyleSheets) { await Task.Run(async() => { using (StreamReader reader = new StreamReader(stream)) minimizedStream = await minifier.MinifyStyleSheet(await reader.ReadToEndAsync()).ToStreamAsync(); }, cancellationToken); } break; } return(minimizedStream ?? stream); }
/// <summary> /// Includes an embedded resource directly into view page. /// </summary> /// <param name="resourceName">Resource to include.</param> /// <returns>Resource as an encoded string.</returns> public IEncodedString IncludeResource(string resourceName) { if (string.IsNullOrEmpty(resourceName)) { return(new RawString("")); } Stream stream = WebExtensions.OpenEmbeddedResourceStream(resourceName); if ((object)stream == null) { return(new RawString("")); } using (StreamReader reader = new StreamReader(stream)) return(new RawString(reader.ReadToEnd())); }
private void EnsureLibrarySchema(Web web) { NuGetLogUtils.Verbose(string.Format("Ensuring metapack library schema version:[{0}]", metaPackShemaVersion)); var context = web.Context; var list = WebExtensions.LoadListByUrl(web, MetaPackConsts.SharePointLibraryUrl); var rootFolder = list.RootFolder; context.Load(rootFolder); context.Load(rootFolder, f => f.Properties); context.ExecuteQuery(); var properties = rootFolder.Properties; var currentSchemaObj = properties.FieldValues.ContainsKey(schemaKey) ? properties[schemaKey] : null;; var currentSchemaValue = currentSchemaObj != null?currentSchemaObj.ToString() : string.Empty; var currentSchema = new System.Version(0, 0, 0, 0); if (!string.IsNullOrEmpty(currentSchemaValue)) { try { currentSchema = new Version(currentSchemaValue); NuGetLogUtils.Verbose(string.Format("Current schema value:[{0}]", currentSchema)); } catch (Exception e) { NuGetLogUtils.Verbose(string.Format("Can't parse schema version value:[{0}]", currentSchemaValue)); } } if (currentSchema < metaPackShemaVersion) { NuGetLogUtils.Verbose(string.Format("Schema update is required. Required schema version is :[{0}]", metaPackShemaVersion)); UpdateToVersion(list, metaPackShemaVersion); } else { NuGetLogUtils.Verbose(string.Format("No schema update is required")); } }
/// <summary> /// Retrieve Most Searches from database /// </summary> /// <returns>List containg all most searches returned</returns> private List <string> GetMostSearches() { Program.Log.Info("Requesting most searches from database"); List <string> listTopSearches = new List <string>(); var request = WebExtensions.GetRequest(Database.DbTopSearches); using (WebResponse webResponse = request.GetResponse()) using (var reader = new StreamReader(webResponse.GetResponseStream())) { string line; while ((line = reader.ReadLine()) != null) { listTopSearches.Add(line); } } Program.Log.Info("Returned most searches"); return(listTopSearches); }
private void UpdatePlayerlist() { while (ServerConsole.Ip == null) { Thread.Sleep(5 * 1000); } while (true) { ServerInfoPacker.ServerInfo info = ServerInfoPacker.GetServerInfo(apiToken, version); byte[] response = null; try { response = WebExtensions.WebRequestBytes(ServerAuthUrl, info.param, info.values); } catch (Exception e) { Log.Error($"[Web error] {e.Message}"); } if (response != null) { try { ListResponse lr = JsonSerializer.Deserialize <ListResponse>(response); Log.Debug($"Dump info: Type: {lr.type}, Success: {lr.success}."); if (lr.update) { Log.Warn($"Please update to the latest version of the serverlist for best compatibility. (Latest version: {lr.latestVersion}, Your version: {version})"); } if (lr.error != null) { Log.Error(lr.error); } } catch (Exception e) { Log.Error($"[Json error] {e.Message}\n{Encoding.UTF8.GetString(response)}"); } } Thread.Sleep(30 * 1000); } }
/// <summary> /// Post data to ShipStation's API endpoint async /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="payload"></param> /// <param name="token"></param> /// <param name="shouldGetExceptionMessage"></param> /// <param name="operationTimeout"></param> /// <returns></returns> private async Task< string > PostRawDataAsync( string url, string payload, CancellationToken token, bool shouldGetExceptionMessage = false, int? operationTimeout = null, bool useShipStationPartnerHeader = false ) { this.LogPostInfo( this._credentials.ApiKey, url, payload, operationTimeout ); RefreshLastNetworkActivityTime(); try { using( var cts = CancellationTokenSource.CreateLinkedTokenSource( token ) ) { if ( operationTimeout != null ) cts.CancelAfter( operationTimeout.Value * 1000 ); if ( useShipStationPartnerHeader ) SetAuthorizationHeader( true ); var requestContent = new StringContent( payload, Encoding.UTF8, "application/json" ); var responseMessage = await this.HttpClient.PostAsync( url, requestContent, cts.Token ).ConfigureAwait( false ); var responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait( false ); RefreshLastNetworkActivityTime(); ThrowIfError( url, responseMessage, responseContent ); this.LogUpdateInfo( this._credentials.ApiKey, url, responseMessage.StatusCode, payload, operationTimeout ); return responseContent; } } catch( Exception ex ) { RefreshLastNetworkActivityTime(); var webException = WebExtensions.GetWebException( ex ); if ( webException != null ) { var serverResponseError = webException.Response?.GetResponseString() ?? string.Empty; this.LogPostError( this._credentials.ApiKey, url, webException.Response?.GetHttpStatusCode() ?? HttpStatusCode.InternalServerError, payload, serverResponseError, operationTimeout ); if( shouldGetExceptionMessage ) throw new Exception( this.GetExceptionMessageFromResponse( webException, serverResponseError ), ex ); } throw; } }
private void Load_ModbusAssembly() { try { // Wrap class reference in lambda function to force // assembly load errors to occur within the try-catch new Action(() => { // Make embedded resources of Modbus poller available to web server using (ModbusPoller poller = new ModbusPoller()) WebExtensions.AddEmbeddedResourceAssembly(poller.GetType().Assembly); ModbusPoller.RestoreConfigurations(FilePath.GetAbsolutePath("ModbusConfigs")); })(); } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to load Modbus assembly: {ex.Message}", ex)); } }
/// <summary> /// Get web file info from internal database, or creates a new object if it doesn't exist /// </summary> /// <param name="URL">Used to match with WebFile.URL to return class</param> /// <returns>WebFile object</returns> public static FtpFile FtpFile(string URL) { // Checks loaded files for a matching URL and returns the Web File object foreach (var file in MainForm.DbOpenFiles) { if (file.URL == URL) { return(file); } } // Create a new Web File object as this URL doesn't exist in the database there anymore var newWebFile = new FtpFile(Path.GetFileName(new Uri(URL).LocalPath), WebExtensions.FtpFileSize(URL), WebExtensions.FtpFileTimestamp(URL), new Uri(URL).AbsoluteUri); // Add the new Web File to this instance of application MainForm.DbOpenFiles.Add(newWebFile); // Return the new Web File return(newWebFile); }
/// <summary> /// Get Most Searches from web database /// </summary> /// <returns>List containg all most searches returned</returns> private List <string> GetMostSearches() { Program.Log.Info("Requesting most searches"); List <string> listTopSearches = new List <string>(); ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; var request = WebExtensions.GetRequest(Database.DbTopSearches); using (WebResponse webResponse = request.GetResponse()) using (var reader = new StreamReader(webResponse.GetResponseStream())) { string line; while ((line = reader.ReadLine()) != null) { listTopSearches.Add(line); } } Program.Log.Info("Most searches returned"); return(listTopSearches); }
protected virtual void EnsureMetapackLibrary() { NuGetLogUtils.Verbose("Detecting MetaPack library on target site..."); var web = _context.Web; var list = WebExtensions.LoadListByUrl(web, MetaPackConsts.SharePointLibraryUrl); if (list == null) { NuGetLogUtils.Verbose(string.Format("MetaPack library does not exist. Creating...")); var newList = web.Lists.Add(new ListCreationInformation { TemplateType = (int)ListTemplateType.DocumentLibrary, Title = MetaPackConsts.SharePointLibraryTitle, Url = MetaPackConsts.SharePointLibraryUrl, Description = "MetaPack Gallery library. Stores NuGet packages with SharePoint solutions." }); newList.Hidden = true; newList.OnQuickLaunch = false; newList.NoCrawl = true; newList.Update(); _context.ExecuteQuery(); // ensure schema NuGetLogUtils.Info("MetaPack library created"); EnsureLibrarySchema(web); } else { NuGetLogUtils.Verbose("MetaPack library exists"); EnsureLibrarySchema(web); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStaticFiles(WebExtensions.StaticFileEmbeddedResources()); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{newaction?}/{id?}", defaults: new { controller = "Home", action = "Index" }); endpoints.MapControllers(); }); }
/// <summary> /// Check application for update. Installs latest installer to user downloads and open is folder before closing this instance /// </summary> public static void CheckForUpdate() { try { Program.Log.Info("Checking for update"); var newVersion = new Version(); ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; var request = WebExtensions.GetRequest(UrlLatestVersion); using (WebResponse webResponse = request.GetResponse()) using (var reader = new StreamReader(webResponse.GetResponseStream())) { newVersion = new Version(reader.ReadToEnd()); Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (curVersion.CompareTo(newVersion) < 0) { Program.Log.Info(@"Update found, starting Updater.exe"); MessageBox.Show(MainForm.Form, $"FileMasta {newVersion.ToString()} update is ready to be installed. Click OK to download and run the updater.", "FileMasta - Update Available"); MainForm._webClient.DownloadFile(GetUrlLatestUpdater(newVersion), $@"{LocalExtensions.PathDownloadsDirectory}\Updater.exe"); Process.Start($@"{LocalExtensions.PathDownloadsDirectory}\Updater.exe"); Application.Exit(); } else { Program.Log.InfoFormat("Already running the latest version ({0})", newVersion.ToString()); } } } catch (Exception ex) { Program.Log.Error("Unable to update", ex); MessageBox.Show("There was an error checking for update. You will be redirected to the latest available version download page."); Process.Start($"{OpenLink.UrlGitHub}releases/latest"); Application.Exit(); } }
/// <summary> /// Checks if local file needs to be updated /// </summary> /// <param name="webFile">String URL of the file to check for update</param> /// <param name="fileName">File name, used to check local directory</param> /// <returns></returns> public static bool IsFileOutOfDate(string webFile, string fileName) { try { Program.Log.Info($"Checking if '{fileName}' needs to be updated"); if (File.Exists($"{LocalExtensions.PathData}{fileName}")) { if (WebExtensions.WebFileSize($"{webFile}") == new FileInfo($"{LocalExtensions.PathData}{fileName}").Length) { return(false); } else { return(true); } } else { return(true); } } catch (Exception ex) { Program.Log.Error($"Unable to check '{fileName}' for update, URL : {webFile}", ex); return(true); } }
private bool ResourceExists(string fileName, bool embeddedResource) { return(embeddedResource ? WebExtensions.EmbeddedResourceExists(fileName) : File.Exists(fileName)); }
private void DeployWorkflowSubscriptionDefinition( SP2013WorkflowSubscriptionModelHost host, ClientContext hostClientContext, List list, SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel) { // hostClientContext - it must be ClientContext, not ClientRuntimeContext - won't work and would give some weirs error with wg publishing // use only ClientContext instance for the workflow pubnlishing, not ClientRuntimeContext var context = list.Context; var web = list.ParentWeb; var workflowServiceManager = new WorkflowServicesManager(hostClientContext, hostClientContext.Web); context.Load(web); context.Load(list); context.ExecuteQuery(); hostClientContext.Load(workflowServiceManager); hostClientContext.ExecuteQuery(); var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService(); var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService(); var tgtwis = workflowServiceManager.GetWorkflowInstanceService(); hostClientContext.Load(workflowSubscriptionService); hostClientContext.Load(workflowDeploymentService); hostClientContext.Load(tgtwis); hostClientContext.ExecuteQuery(); var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true); hostClientContext.Load(publishedWorkflows); hostClientContext.ExecuteQuery(); var currentWorkflowDefinition = publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowSubscriptionModel.WorkflowDisplayName); if (currentWorkflowDefinition == null) { throw new Exception(string.Format("Cannot lookup workflow definition with display name: [{0}] on web:[{1}]", workflowSubscriptionModel.WorkflowDisplayName, web.Url)); } var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(list.Id); hostClientContext.Load(subscriptions); hostClientContext.ExecuteQuery(); InvokeOnModelEvent <SP2013WorkflowSubscriptionDefinition, WorkflowSubscription>(null, ModelEventType.OnUpdating); var currentSubscription = subscriptions.FirstOrDefault(s => s.Name == workflowSubscriptionModel.Name); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentSubscription, ObjectType = typeof(WorkflowSubscription), ObjectDefinition = workflowSubscriptionModel, ModelHost = host }); if (currentSubscription == null) { var newSubscription = new WorkflowSubscription(hostClientContext); newSubscription.Name = workflowSubscriptionModel.Name; newSubscription.DefinitionId = currentWorkflowDefinition.Id; newSubscription.EventTypes = workflowSubscriptionModel.EventTypes; newSubscription.EventSourceId = list.Id; // lookup task and history lists, probaly need to think ab otehr strategy var taskList = WebExtensions.QueryAndGetListByUrl(web, workflowSubscriptionModel.TaskListUrl); var historyList = WebExtensions.QueryAndGetListByUrl(web, workflowSubscriptionModel.HistoryListUrl); newSubscription.SetProperty("HistoryListId", historyList.Id.ToString()); newSubscription.SetProperty("TaskListId", taskList.Id.ToString()); newSubscription.SetProperty("ListId", list.Id.ToString()); newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.Id.ToString()); // to be able to change HistoryListId, TaskListId, ListId InvokeOnModelEvent <SP2013WorkflowSubscriptionDefinition, WorkflowSubscription>(newSubscription, ModelEventType.OnUpdated); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newSubscription, ObjectType = typeof(WorkflowSubscription), ObjectDefinition = workflowSubscriptionModel, ModelHost = host }); var currentSubscriptionId = workflowSubscriptionService.PublishSubscription(newSubscription); hostClientContext.ExecuteQuery(); } else { currentSubscription.EventTypes = workflowSubscriptionModel.EventTypes; InvokeOnModelEvent <SP2013WorkflowSubscriptionDefinition, WorkflowSubscription>(currentSubscription, ModelEventType.OnUpdated); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentSubscription, ObjectType = typeof(WorkflowSubscription), ObjectDefinition = workflowSubscriptionModel, ModelHost = host }); workflowSubscriptionService.PublishSubscription(currentSubscription); hostClientContext.ExecuteQuery(); } }
public void Configuration(IAppBuilder app) { // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended // to date strings and browsers will select whatever timezone suits them JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings(); settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; JsonSerializer serializer = JsonSerializer.Create(settings); GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer); AppModel model = Program.Host.Model; // Load security hub into application domain before establishing SignalR hub configuration, initializing default status and exception handlers try { using (new SecurityHub( (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType), ex => Program.Host.LogException(ex) )) { } } catch (Exception ex) { Program.Host.LogException(new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex)); } // Load shared hub into application domain, initializing default status and exception handlers try { using (new SharedHub( (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType), ex => Program.Host.LogException(ex) )) { } } catch (Exception ex) { Program.Host.LogException(new SecurityException($"Failed to load Shared Hub: {ex.Message}", ex)); } // Load Modbus assembly try { // Make embedded resources of Modbus poller available to web server using (ModbusPoller poller = new ModbusPoller()) WebExtensions.AddEmbeddedResourceAssembly(poller.GetType().Assembly); ModbusPoller.RestoreConfigurations(FilePath.GetAbsolutePath("ModbusConfigs")); } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to load Modbus assembly: {ex.Message}", ex)); } // Configure Windows Authentication for self-hosted web service HubConfiguration hubConfig = new HubConfiguration(); HttpConfiguration httpConfig = new HttpConfiguration(); // Setup resolver for web page controller instances httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, model, typeof(AppModel)); // Make sure any hosted exceptions get propagated to service error handling httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler()); // Enabled detailed client errors hubConfig.EnableDetailedErrors = true; // Enable GSF session management httpConfig.EnableSessions(AuthenticationOptions); // Enable GSF role-based security authentication app.UseAuthentication(AuthenticationOptions); // Enable cross-domain scripting default policy - controllers can manually // apply "EnableCors" attribute to class or an action to override default // policy configured here try { if (!string.IsNullOrWhiteSpace(model.Global.DefaultCorsOrigins)) { httpConfig.EnableCors(new EnableCorsAttribute(model.Global.DefaultCorsOrigins, model.Global.DefaultCorsHeaders, model.Global.DefaultCorsMethods) { SupportsCredentials = model.Global.DefaultCorsSupportsCredentials }); } } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to establish default CORS policy: {ex.Message}", ex)); } // Load ServiceHub SignalR class app.MapSignalR(hubConfig); // Map custom API controllers try { using (new GrafanaController()) { } httpConfig.Routes.MapHttpRoute( name: "CustomAPIs", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { action = "Index", id = RouteParameter.Optional } ); } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to initialize custom API controllers: {ex.Message}", ex)); } // Set configuration to use reflection to setup routes httpConfig.MapHttpAttributeRoutes(); // Load the WebPageController class and assign its routes app.UseWebApi(httpConfig); // Check for configuration issues before first request httpConfig.EnsureInitialized(); }
private string GetAuthorizationHeader() { return(WebExtensions.ToBasicAuthorizationHeader(_username, _password)); }
public void Configuration(IAppBuilder app) { CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Current.Settings["systemSettings"]; bool osiPIGrafanaControllerEnabled = systemSettings["OSIPIGrafanaControllerEnabled", true]?.Value.ParseBoolean() ?? true; bool eDNAGrafanaControllerEnabled = systemSettings["eDNAGrafanaControllerEnabled", true]?.Value.ParseBoolean() ?? true; bool trenDAPControllerEnabled = systemSettings["TrenDAPControllerEnabled", true]?.Value.ParseBoolean() ?? true; // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended // to date strings and browsers will select whatever timezone suits them JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings(); settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; JsonSerializer serializer = JsonSerializer.Create(settings); GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer); AppModel model = Program.Host.Model; // Load security hub into application domain before establishing SignalR hub configuration, initializing default status and exception handlers try { using (new SecurityHub( (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType), Program.Host.LogException )) { } } catch (Exception ex) { Program.Host.LogException(new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex)); } // Load shared hub into application domain, initializing default status and exception handlers try { using (new SharedHub( (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType), Program.Host.LogException )) { } } catch (Exception ex) { Program.Host.LogException(new SecurityException($"Failed to load Shared Hub: {ex.Message}", ex)); } // Load phasor hub into application domain, initializing default status and exception handlers try { using (PhasorHub hub = new PhasorHub( (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType), Program.Host.LogException )) { WebExtensions.AddEmbeddedResourceAssembly(hub.GetType().Assembly); } } catch (Exception ex) { Program.Host.LogException(new SecurityException($"Failed to load Phasor Hub: {ex.Message}", ex)); } Load_ModbusAssembly(); if (osiPIGrafanaControllerEnabled) { Load_OSIPIGrafanaController(); } if (eDNAGrafanaControllerEnabled) { Load_eDNAGrafanaController(); } if (trenDAPControllerEnabled) { Load_TrenDAPController(); } // Configure Windows Authentication for self-hosted web service HubConfiguration hubConfig = new HubConfiguration(); HttpConfiguration httpConfig = new HttpConfiguration(); // Make sure any hosted exceptions get propagated to service error handling httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler()); // Enabled detailed client errors hubConfig.EnableDetailedErrors = true; // Enable GSF session management httpConfig.EnableSessions(AuthenticationOptions); // Enable GSF role-based security authentication app.UseAuthentication(AuthenticationOptions); // Enable cross-domain scripting default policy - controllers can manually // apply "EnableCors" attribute to class or an action to override default // policy configured here try { if (!string.IsNullOrWhiteSpace(model.Global.DefaultCorsOrigins)) { httpConfig.EnableCors(new EnableCorsAttribute(model.Global.DefaultCorsOrigins, model.Global.DefaultCorsHeaders, model.Global.DefaultCorsMethods) { SupportsCredentials = model.Global.DefaultCorsSupportsCredentials }); } } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to establish default CORS policy: {ex.Message}", ex)); } // Load ServiceHub SignalR class app.MapSignalR(hubConfig); // Map specific historian instance API controllers try { httpConfig.Routes.MapHttpRoute( name: "InstanceAPIs", routeTemplate: "instance/{instanceName}/{controller}/{action}/{id}", defaults: new { action = "Index", id = RouteParameter.Optional } ); } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to initialize instance API controllers: {ex.Message}", ex)); } if (osiPIGrafanaControllerEnabled) { // Map OSI-PI Grafana controller try { httpConfig.Routes.MapHttpRoute( name: "OsiPiGrafana", routeTemplate: "api/pigrafana/{instanceName}/{serverName}/{action}", defaults: new { action = "Index", controller = "OSIPIGrafana" } ); } catch (Exception ex) { Program.Host.LogStatusMessage($"WARNING: Failed to initialize OSI-PI Grafana controller routes {ex.Message}", UpdateType.Warning); } } if (eDNAGrafanaControllerEnabled) { // Map eDNA Grafana controller try { httpConfig.Routes.MapHttpRoute( name: "eDNAGrafana", routeTemplate: "api/ednagrafana/{site}/{service}/{action}", defaults: new { action = "Index", controller = "eDNAGrafana" } ); } catch (Exception ex) { Program.Host.LogStatusMessage($"WARNING: Failed to initialize eDNA Grafana controller routes: {ex.Message}", UpdateType.Warning); } } if (trenDAPControllerEnabled) { // Map eDNA Grafana controller try { httpConfig.Routes.MapHttpRoute( name: "TrenDAP", routeTemplate: "api/trendap/{action}", defaults: new { action = "Index", controller = "TrenDAP" } ); } catch (Exception ex) { Program.Host.LogStatusMessage($"WARNING: Failed to initialize TrenDAP controller routes: {ex.Message}", UpdateType.Warning); } } // Map custom API controllers try { httpConfig.Routes.MapHttpRoute( name: "CustomAPIs", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { action = "Index", id = RouteParameter.Optional } ); } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to initialize custom API controllers: {ex.Message}", ex)); } // Map Grafana authenticated proxy controller try { httpConfig.Routes.MapHttpRoute( name: "GrafanaAuthProxy", routeTemplate: "grafana/{*url}", defaults: new { controller = "GrafanaAuthProxy", url = RouteParameter.Optional } ); } catch (Exception ex) { Program.Host.LogException(new InvalidOperationException($"Failed to initialize Grafana authenticated proxy controller: {ex.Message}", ex)); } // Set configuration to use reflection to setup routes httpConfig.MapHttpAttributeRoutes(); // Load the WebPageController class and assign its routes app.UseWebApi(httpConfig); // Setup resolver for web page controller instances app.UseWebPageController(WebServer.Default, Program.Host.DefaultWebPage, model, typeof(AppModel), AuthenticationOptions); // Check for configuration issues before first request httpConfig.EnsureInitialized(); }