WordPress.com



using ServiceApplication.Entities;namespace ServiceApplication{ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using ServiceApplication.Timer; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using Microsoft.SharePoint.Utilities; /// <summary> /// The Service Application is responsible for processing the request from the WFE server proxies. The Service Application can run.. /// on multiple application servers. /// The Service Application implements the Service Contract, and provides the implementation /// </summary> [Guid("7BF4F7B4-DEE9-449C-B498-23FD1BE77E1B")] [IisWebServiceApplicationBackupBehavior] internal class WebServiceApplication : SPIisWebServiceApplication, IService { #region Fields /// <summary> /// A persisted instance of the <see cref="T:SPDatabase"/> /// </summary> [Persisted] private WebServiceDatabase database; #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="WebServiceApplication"/> class. /// </summary> public WebServiceApplication() { } /// <summary> /// Initializes a new instance of the <see cref="WebServiceApplication"/> class. /// </summary> /// <param name="name">The name of the service application</param> /// <param name="service">The <see cref="T:SPIisWebService "/> instance</param> /// <param name="database">The <see cref="T:SPDatabase"/> instance</param> /// <param name="applicationPool">The initialized <see cref="T:SPIisWebServiceApplicationPool"/></param> internal WebServiceApplication(string name, WebService service, WebServiceDatabase database, SPIisWebServiceApplicationPool applicationPool) : base(name, service, applicationPool) { this.Database = database; } /// <summary> /// Initializes a new instance of the <see cref="WebServiceApplication"/> class. /// </summary> /// <param name="name">The name of the service application</param> /// <param name="service">The <see cref="T:SPIisWebService "/> instance</param> /// <param name="database">The <see cref="T:SPDatabase"/> instance</param> /// <param name="applicationPool">The initialized <see cref="T:SPIisWebServiceApplicationPool"/></param> internal WebServiceApplication(string name, SPIisWebService service, WebServiceDatabase database, SPIisWebServiceApplicationPool applicationPool) : base(name, service, applicationPool) { if (this.Database == null) { throw new ArgumentNullException("database"); } this.Database = database; } #endregion Constructors #region Properties /// <summary> /// Gets a persisted instance of the <see cref="T:WebServiceDatabase"/> /// </summary> public WebServiceDatabase Database { get { return this.database; } private set { this.database = value; } } /// <summary> /// Gets the CA relative URL of the page that the administrators should be taken to when they select the service, or /// when they click on the Manage Button /// </summary> /// <returns>Returns <see cref="T:Microsoft.SharePoint.Administration.SPAdministrationLink"/>.</returns> public override SPAdministrationLink ManageLink { get { if (!string.IsNullOrEmpty(Constants.WebApplicationServiceManageLink)) { return new SPAdministrationLink(Constants.WebApplicationServiceManageLink + this.Id.ToString()); } return base.ManageLink; } } /// <summary> /// Gets the CA relative URL of the page that the administrators should be taken to when clicking on the Properties button /// </summary> /// <returns>Returns <see cref="T:Microsoft.SharePoint.Administration.SPAdministrationLink"/>.</returns> public override SPAdministrationLink PropertiesLink { get { if (!string.IsNullOrEmpty(Constants.WebApplicationServicePropertiesLink)) { return new SPAdministrationLink(Constants.WebApplicationServicePropertiesLink + this.Id.ToString()); } return base.PropertiesLink; } } /// <summary> /// Gets the display name that describes the object type in the administrative user interface. /// </summary> /// <returns>A string that contains the name of the object type.</returns> public override string TypeName { get { return Constants.WebApplicationServiceName; } } /// <summary> /// Gets the name of the database. /// </summary> /// <value> /// The name of the database. /// </value> internal string DatabaseName { get { return this.Database.Name; } } /// <summary> /// Gets the database server. /// </summary> internal string DatabaseServer { get { return this.Database.ServiceInstance.NormalizedDataSource; } } /// <summary> /// Gets the failover server. /// </summary> internal string FailoverServer { get { string address = string.Empty; if (this.Database.FailoverServer != null) { address = this.Database.FailoverServer.Address; } return address; } } /// <summary> /// Gets the default name of the endpoint. /// </summary> /// <value> /// The default name of the endpoint. /// </value> protected override string DefaultEndpointName { get { return "http"; } } /// <summary> /// Gets the relative path where the service endpoint can be found on the application servers /// </summary> /// <returns>Returns <see cref="T:System.String"/>.</returns> protected override string InstallPath { get { return SPUtility.GetGenericSetupPath(Constants.WebApplicationInstallPath); } } /// <summary> /// Gets the name of WCF service endpoint file /// </summary> /// <returns>Returns <see cref="T:System.String"/>.</returns> protected override string VirtualPath { get { return Constants.WebApplicationVirtualPath; } } #endregion Properties #region Methods /// <summary> /// Adds a collection of audit entries in the database /// </summary> /// <param name="web"></param> /// <returns> /// Boolean indicating if the Items were persisted to the database /// </returns> public void AddListEntries() { List<Entities.ListEntry> entries = new List<Entities.ListEntry>(); foreach (SPService curService in SPFarm.Local.Services) { if (curService is SPWebService) { SPWebService webService = (SPWebService)curService; foreach (SPWebApplication webApp in webService.WebApplications) { foreach (SPWeb web in webApp.Sites[0].AllWebs) { entries.AddRange(from SPList list in web.Lists select new ListEntry() { ListName = list.Title, ItemCount = list.ItemCount, SiteId = list.ParentWeb.Title, Url = list.DefaultDisplayFormUrl }); } } } } if (entries.Count > 0) { using ( Entities.ListEntriesDataContext context = new Entities.ListEntriesDataContext(this.database.DatabaseConnectionString)) { context.ListEntries.InsertAllOnSubmit<Entities.ListEntry>(entries); context.SubmitChanges(); } } } public Collection<Entities.ListEntry> GetAllListEntries() { using (Entities.ListEntriesDataContext context = new Entities.ListEntriesDataContext(this.database.DatabaseConnectionString)) { return new Collection<Entities.ListEntry>(context.ListEntries.ToList<Entities.ListEntry>()); } } /// <summary> /// Adds a collection of audit entries in the database /// </summary> /// <param name="sitesId">The sites to query for audit entries</param> /// <param name="startDate">The starting data of the audit query</param> /// <returns> /// Boolean indicating if the Items were persisted to the database /// </returns> public bool AddAuditEntries(IEnumerable<Guid> sitesId, DateTime startDate) { if (sitesId == null) { throw new ArgumentNullException("sitesId"); } bool updated = false; foreach (Guid siteId in sitesId) { using (SPSite site = new SPSite(siteId)) { SPAuditQuery query = new SPAuditQuery(site); if (startDate != DateTime.MinValue) { query.SetRangeStart(startDate.AddHours(-1)); } SPAuditEntryCollection collection = site.Audit.GetEntries(query); List<Entities.AuditEntry> entries = new List<Entities.AuditEntry>(); foreach (SPAuditEntry entry in collection) { updated = true; entries.Add(new Entities.AuditEntry() { EventData = entry.EventData, EventName = entry.EventName, ItemId = entry.ItemId, EventType = (int)entry.LocationType, ItemType = (int)entry.ItemType, Location = GetSPListItem(site, entry.DocLocation), MachineName = entry.MachineName, Occurred = entry.Occurred, SiteId = entry.SiteId, SourceName = entry.SourceName, UserId = entry.UserId }); } if (entries.Count > 0) { using (Entities.AuditEntriesDataContext context = new Entities.AuditEntriesDataContext(this.database.DatabaseConnectionString)) { context.AuditEntries.InsertAllOnSubmit<Entities.AuditEntry>(entries); context.SubmitChanges(); } } } } return updated; } /// <summary> /// Adds some test dummy data to the database /// </summary> /// <param name="sitesId">The sites to quey for audit entries</param> /// <param name="startDate">The starting data of the audit query</param> public void AddDummyAuditEntries(System.Collections.Generic.IEnumerable<Guid> sitesId, DateTime startDate) { if (sitesId == null) { throw new ArgumentNullException("sitesId"); } foreach (Guid siteId in sitesId) { using (Entities.AuditEntriesDataContext context = new Entities.AuditEntriesDataContext(this.database.DatabaseConnectionString)) { context.AuditEntries.InsertOnSubmit(new Entities.AuditEntry() { EventData = "TESTING DATA", EventName = "TESTING NAME", EventType = 1, ItemId = Guid.NewGuid(), ItemType = 1, Location = "TESTING LOCATION", MachineName = "MACHINE NAME", Occurred = DateTime.Now, SiteId = siteId, SourceName = "SOURCE NAME", UserId = 102 }); } } } /// <summary> /// Clears all the sites audit logs from the specified sites /// </summary> /// <param name="sitesId">The Id of <see cref="T:SPSite"/> site</param> public void ClearAllSitesAuditLogs(List<Guid> sitesId) { if (sitesId == null) { throw new ArgumentNullException("sitesId"); } foreach (Guid siteId in sitesId) { using (SPSite site = new SPSite(siteId)) { site.Audit.DeleteEntries(DateTime.Now); } } } /// <summary> /// Deletes this instance. /// </summary> public override void Delete() { base.Delete(); if (this.Database != null) { this.Database.Delete(); } } /// <summary> /// Deletes entries from the database for the specified Site Id /// </summary> /// <param name="sitesId">The Id of <see cref="T:SPSite"/> site</param> public void DeleteDatabaseEntries(List<Guid> sitesId) { if (sitesId == null) { throw new ArgumentNullException("sitesId"); } foreach (Guid siteId in sitesId) { using (Entities.AuditEntriesDataContext context = new Entities.AuditEntriesDataContext(this.database.DatabaseConnectionString)) { var items = context.AuditEntries.Where(p => p.SiteId == siteId); context.AuditEntries.DeleteAllOnSubmit(items); context.SubmitChanges(); } } } public void DeleteListDatabaseEntries() { using (Entities.ListEntriesDataContext context = new Entities.ListEntriesDataContext(this.database.DatabaseConnectionString)) { var items = context.ListEntries; context.ListEntries.DeleteAllOnSubmit(items); context.SubmitChanges(); } } /// <summary> /// Gets all the audit entries in the database /// </summary> /// <returns> /// A collection of audit entries /// </returns> public Collection<Entities.AuditEntry> GetAllEntries() { using (Entities.AuditEntriesDataContext context = new Entities.AuditEntriesDataContext(this.database.DatabaseConnectionString)) { return new Collection<Entities.AuditEntry>(context.AuditEntries.ToList<Entities.AuditEntry>()); } } /// <summary> /// Gets the audit entries for the specified site ids /// </summary> /// <param name="siteId">The Id of <see cref="T:SPSite"/> site</param> /// <returns> /// A collection of audit entries corresponding to the site Id /// </returns> public Collection<Entities.AuditEntry> GetEntriesById(Guid siteId) { using (Entities.AuditEntriesDataContext context = new Entities.AuditEntriesDataContext(this.database.DatabaseConnectionString)) { return new Collection<Entities.AuditEntry>(context.AuditEntries.Where(p => p.SiteId == siteId).ToList<Entities.AuditEntry>()); } } /// <summary> /// Grants the access. /// </summary> /// <param name="user">The user.</param> public void GrantAccess(string user) { if (user == null) { throw new ArgumentNullException("user"); } using (SqlCommand command = new SqlCommand()) { command.Connection = new SqlConnection(this.database.DatabaseConnectionString); mandType = CommandType.Text; mandText = "declare @db_user_name sysname\r\nselect @db_user_name = name from dbo.sysusers where sid = SUSER_SID(@user_name) and hasdbaccess = 1\r\nif (@db_user_name is null)\r\nbegin\r\nif exists(select * from dbo.sysusers where name = @user_name)\r\nexec @revoke_result = sp_revokedbaccess @user_name\r\nexec @grant_result = sp_grantdbaccess @user_name, @db_user_name output\r\nend"; command.Parameters.Add("@user_name", SqlDbType.NVarChar, 0x80).Value = user; SqlParameter revokeResultParam = command.Parameters.Add("@revoke_result", SqlDbType.Int); revokeResultParam.Direction = ParameterDirection.Output; SqlParameter grantResultParam = command.Parameters.Add("@grant_result", SqlDbType.Int); grantResultParam.Direction = ParameterDirection.Output; command.ExecuteNonQuery(); if (DBNull.Value != grantResultParam.Value && (int)grantResultParam.Value != 0) { throw new SPDatabaseException(string.Format(CultureInfo.InvariantCulture, "GrantAccess(). Cannot add user '{0}' to the database", user)); } } } /// <summary> /// Determines whether the specified user has access. /// </summary> /// <param name="user">The user.</param> /// <returns> /// <c>true</c> if the specified user has access; otherwise, <c>false</c>. /// </returns> public bool HasAccess(string user) { if (user == null) { throw new ArgumentNullException("user"); } using (SqlCommand command = new SqlCommand()) { command.Connection = new SqlConnection(this.database.DatabaseConnectionString); mandType = CommandType.Text; mandText = "select @has_access = case when exists (select * from dbo.sysusers where (sid = SUSER_SID(@user_name)) and (hasdbaccess = 1)) then 1 else 0 end"; SqlParameter parameter = command.Parameters.Add("@has_access", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; command.Parameters.Add("@user_name", SqlDbType.NVarChar, 0x80).Value = user; command.ExecuteNonQuery(); return 1 == (int)parameter.Value; } } /// <summary> /// Provisions this instance. /// </summary> public override void Provision() { this.Database.Provision(); base.Provision(); } /// <summary> /// Unprovisions the specified delete data. /// </summary> /// <param name="deleteData">if set to <c>true</c> [delete data].</param> public override void Unprovision(bool deleteData) { base.Unprovision(deleteData); WebService service = SPFarm.Local.Services.GetValue<WebService>(); if (service.JobDefinitions.GetValue<GatherEventsTimerJob>("AuditLogGather") != null) { service.JobDefinitions.GetValue<GatherEventsTimerJob>("AuditLogGather").Delete(); } if (deleteData && this.Database != null) { this.Database.Unprovision(); } } /// <summary> /// Creates an new instance of the <see cref="T:SPIisWebServiceApplication"/> /// </summary> /// <param name="name">The name of the service application</param> /// <param name="databaseParameters">The database parameters</param> /// <param name="applicationPool">The application pool</param> /// <param name="isDefaultAssociation">Boolean indicating if the service application is part of the default group</param> /// <param name="failoverServer">The name of the Fail Over servers</param> /// <returns>Returns an instance of <see cref="T:SPIisWebServiceApplication"/></returns> internal static WebServiceApplication Create(string name, SPDatabaseParameters databaseParameters, SPIisWebServiceApplicationPool applicationPool, bool isDefaultAssociation, string failoverServer) { WebService service = SPFarm.Local.Services.GetValue<WebService>(); if (service == null) { throw new InvalidOperationException("Service not installed"); } WebServiceApplication application = Create(name, service, databaseParameters, applicationPool); application.Update(); application.Update(name, databaseParameters, applicationPool, true, true, failoverServer); WebServiceApplicationProxy.CreateProxy(application.Uri, application.Name, isDefaultAssociation); EnsureTimerJobDefition(service); return application; } /// <summary> /// Creates an new instance of the <see cref="T:SPIisWebServiceApplication"/> /// </summary> /// <param name="name">The name of the service application</param> /// <param name="service">An instance of the <see cref="T:SPIisWebService"/></param> /// <param name="databaseParameters">The database parameters</param> /// <param name="applicationPool">The application pool</param> /// <returns>Returns an instance of <see cref="T:SPIisWebServiceApplication"/></returns> internal static WebServiceApplication Create(string name, WebService service, SPDatabaseParameters databaseParameters, SPIisWebServiceApplicationPool applicationPool) { string error; if (!mon.IsServiceApplicationNameValid<WebServiceApplication, WebService>(name, out error)) { throw new SPException(error); } WebServiceDatabase database = WebServiceDatabase.Create(databaseParameters); WebServiceApplication application = new WebServiceApplication(name, service, database, applicationPool); application.Update(); application.AddServiceEndpoint("http", SPIisWebServiceBindingType.Http); application.AddServiceEndpoint("https", SPIisWebServiceBindingType.Https); return application; } /// <summary> /// Creates the database parameters. /// </summary> /// <param name="databaseName">Name of the database.</param> /// <param name="databaseServer">The database server.</param> /// <param name="sharedAppName">Name of the shared app.</param> /// <returns>Returns an instance of <see cref="T:SPDatabaseParameters"/></returns> internal static SPDatabaseParameters CreateDatabaseParameters(string databaseName, string databaseServer, string sharedAppName) { return CreateDatabaseParameters(databaseName, databaseServer, sharedAppName, null, null); } /// <summary> /// Creates the database parameters. /// </summary> /// <param name="databaseName">Name of the database.</param> /// <param name="databaseServer">The database server.</param> /// <param name="sharedAppName">Name of the shared app.</param> /// <param name="sqlAuthUserName">Name of the SQL auth user.</param> /// <param name="sqlAuthPassword">The SQL auth password.</param> /// <returns>Rerurns an instance of <see cref="T:SPDatabaseParameters"/></returns> internal static SPDatabaseParameters CreateDatabaseParameters(string databaseName, string databaseServer, string sharedAppName, string sqlAuthUserName, string sqlAuthPassword) { string initialCatalog = string.IsNullOrEmpty(databaseName) ? (sharedAppName + Constants.WebServiceDatabaseNameIfNotSupplied) : databaseName; string dataSource = string.IsNullOrEmpty(databaseServer) ? null : databaseServer; SPDatabaseParameterOptions options = string.IsNullOrEmpty(databaseName) ? SPDatabaseParameterOptions.GenerateUniqueName : SPDatabaseParameterOptions.None; return SPDatabaseParameters.CreateParameters(initialCatalog, dataSource, sqlAuthUserName, sqlAuthPassword, null, options); } /// <summary> /// Gets the application by id. /// </summary> /// <param name="applicationId">The application id.</param> /// <returns>The <see cref="T:SPIisWebServiceApplication"/> instance</returns> internal static WebServiceApplication GetApplicationById(Guid applicationId) { WebService service = SPFarm.Local.Services.GetValue<WebService>(); if (service != null) { return service.Applications.GetValue<WebServiceApplication>(applicationId); } return null; } /// <summary> /// Ensures the application access. /// </summary> /// <param name="userName">Name of the user.</param> internal void EnsureApplicationAccess(string userName) { if (this.HasAccess(userName)) { this.GrantAccess(userName); } Helpers.Database.AddRoleMember("db_owner", userName, this.database); } /// <summary> /// Adds the relevent permission to the database /// </summary> /// <param name="processSecurityIdentifier">The <see cref="T:SecurityIdentifier"/> token</param> protected override void OnProcessIdentityChanged(SecurityIdentifier processSecurityIdentifier) { base.OnProcessIdentityChanged(processSecurityIdentifier); this.Database.GrantApplicationPoolAccess(processSecurityIdentifier); } /// <summary> /// Ensures the timer job defition. /// </summary> /// <param name="service">The <see cref="T:SPIisWebService"/> service.</param> private static void EnsureTimerJobDefition(WebService service) { if (service.JobDefinitions.GetValue<GatherEventsTimerJob>("AuditLogGather") == null) { GatherEventsTimerJob definition = new GatherEventsTimerJob("AuditLogGather", service); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.Interval = 15; schedule.BeginSecond = 0; schedule.EndSecond = 59; definition.Schedule = schedule; definition.Update(); } } /// <summary> /// Gets the SP list item. /// </summary> /// <param name="site">The site.</param> /// <param name="itemUrl">The item URL.</param> /// <returns>A string containing the concatonated file URL</returns> private static string GetSPListItem(SPSite site, string itemUrl) { if (!string.IsNullOrEmpty(itemUrl)) { using (SPWeb web = site.OpenWeb()) { SPFile file = web.GetFile(string.Format("{0}/{1}", web.Url, itemUrl)); if (file.Exists) { itemUrl = file.Item.Title; } } } return itemUrl; } /// <summary> /// Sets the database. /// </summary> /// <param name="databaseName">Name of the database.</param> /// <param name="databaseServer">The database server.</param> private void SetDatabase(string databaseName, string databaseServer) { WebServiceDatabase serviceDatabase = WebServiceDatabase.Create(CreateDatabaseParameters(databaseName, databaseServer, this.Name)); this.database = serviceDatabase; this.database.Update(); this.database.Provision(); if (this.ApplicationPool != null) { string userName = this.ApplicationPool.GetSecurityIdentifier().Translate(typeof(NTAccount)).Value; this.EnsureApplicationAccess(userName); } else { throw new Exception("Application Pool cannot be null"); } } /// <summary> /// Updates the specified shared app name. /// </summary> /// <param name="sharedAppName">Name of the shared app.</param> /// <param name="parameters">The parameters.</param> /// <param name="applicationPool">The application pool.</param> /// <param name="authenticate">if set to <c>true</c> [authenticate].</param> /// <param name="createFailoverServer">if set to <c>true</c> [create failover server].</param> /// <param name="failoverServer">The failover server.</param> private void Update(string sharedAppName, SPDatabaseParameters parameters, SPIisWebServiceApplicationPool applicationPool, bool authenticate, bool createFailoverServer, string failoverServer) { if (!string.IsNullOrEmpty(sharedAppName) && !string.Equals(this.Name, sharedAppName, StringComparison.Ordinal)) { this.Name = sharedAppName; } string database = null; string server = null; if (!string.IsNullOrEmpty(parameters.Database) || !string.IsNullOrEmpty(parameters.Server)) { if (!string.IsNullOrEmpty(parameters.Database)) { database = parameters.Database; } else { database = this.DatabaseName; } if (!string.IsNullOrEmpty(parameters.Server)) { server = parameters.Server; } else { server = this.DatabaseServer; } if (!string.Equals(this.DatabaseName, database, StringComparison.OrdinalIgnoreCase) || !string.Equals(this.DatabaseServer, server, StringComparison.OrdinalIgnoreCase)) { this.SetDatabase(database, server); } } bool flag = false; if (authenticate) { this.Database.SetAuthenticationMode(parameters.Username, parameters.Password); flag = true; } if (createFailoverServer) { if (failoverServer == null) { failoverServer = string.Empty; } if (!string.Equals(this.FailoverServer, failoverServer, StringComparison.OrdinalIgnoreCase)) { this.Database.AddFailoverServiceInstance(failoverServer); flag = true; } } if (flag) { this.Database.Update(); } if (applicationPool != null && applicationPool != this.ApplicationPool) { this.ApplicationPool = applicationPool; } this.Update(); this.Provision(); } #endregion Methods }} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download