using Dapper; using Serilog; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using webapi.Infractructure.Model; using webapi.Domain.Model; //[assembly: NeutralResourcesLanguageAttribute("en")] namespace webapi.Infractructure.Services { public class RepositoryContextFactory //: IDisposable { //readonly readonly IDbConnection _connection; readonly string _connectionString; public RepositoryContextFactory(string connectionString) { //_connection = new SqlConnection(connectionString); _connectionString = connectionString; } //public T CreateDbContext(string connectionString) where T : IDbConnection //{ // var optionsBuilder = new DbContextOptionsBuilder(); // optionsBuilder.UseNpgsql(connectionString); // return (T)Activator.CreateInstance(typeof(T), optionsBuilder.Options); //} public IDbConnection GetDbContext() => new SqlConnection(_connectionString); //#region IDisposable Support //private bool disposedValue = false; // To detect redundant calls //protected virtual void Dispose(bool disposing) //{ // if (!disposedValue) // { // if (disposing) // { // // TODO: dispose managed state (managed objects). // } // if (_connection != null) // { // _connection.Close(); // } // // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // // TODO: set large fields to null. // disposedValue = true; // } //} //// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. //// ~RepositoryContextFactory() //// { //// // Do not change this code. Put cleanup code in Dispose(bool disposing) above. //// Dispose(false); //// } //// This code added to correctly implement the disposable pattern. //public void Dispose() //{ // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(true); // // TODO: uncomment the following line if the finalizer is overridden above. // // GC.SuppressFinalize(this); //} //#endregion } public class SPService: ISPService { #region Members readonly RepositoryContextFactory _contextFactory; readonly ILogger _log; #endregion //public SPService(string connectionString): // this(Serilog.Log.ForContext(), new RepositoryContextFactory(connectionString)) //{ // //_contextFactory = ; // //_log = ; // //_emailService = emailService; //} public SPService(ILogger log, RepositoryContextFactory contextFactory) { _contextFactory = contextFactory; _log = log; //_emailService = emailService; } //async Task GetUser(string email, string displayName) { // var sql = @"SELECT * FROM [dbo].[aspnet_Users] u // LEFT JOIN [dbo].[mdb_RightsRedirect_aspnet_UserCondos] c ON c.UserId = u.UserId"; // using (var connection = _contextFactory.CreateDbContext()) // { // return (await connection.QueryAsync(sql, new { email = email, displayName = displayName }))?.FirstOrDefault(); // } //} //async Task CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved) //{ // var salt = CreateSalt(new byte[128]); // //var salt = Encoding.Unicode.GetString(storeSalt); // _log.Information($"salt: {salt}, password: {password}"); // var passwordEncoded = EncodePassword(password, salt); // var newUserId = Guid.NewGuid(); // var sql = @" // INSERT INTO [dbo].[aspnet_Users] ( // [ApplicationId], // [UserId], // [UserName], // [LoweredUserName], // --[MobileAlias] --NULL, // --[IsAnonymous] --0, // [LastActivityDate]) // SELECT TOP 1 // a.ApplicationId, // @UserId, // @UserName, // LOWER(@UserName), // @LastActivityDate // FROM [dbo].[aspnet_Applications]; // INSERT INTO [dbo].[aspnet_Membership] ( // [ApplicationId], // [UserId], // [Password], // [PasswordFormat], // [PasswordSalt], // [PasswordQuestion], // [PasswordAnswer], // [Email], // [LoweredEmail], // [IsApproved], // [IsLockedOut], // [CreateDate], // [LastLoginDate], // [LastPasswordChangedDate], // [LastLockoutDate], // [FailedPasswordAttemptCount], // [FailedPasswordAttemptWindowStart], // [FailedPasswordAnswerAttemptCount], // [FailedPasswordAnswerAttemptWindowStart], // [Comment]) // SELECT TOP 1 // a.ApplicationId, // @UserId, // @Password, // 1, --PasswordFormat // @PasswordSalt, // @PasswordQuestion, // @PasswordAnswer, // @Email, // LOWER(@Email), // @IsApproved // 0, -- IsLockedOut // @CreateDate, // @CreateDate, // @CreateDate, // @MinDate, --1754-01-01 00:00:00.000, // 0, // @MinDate, // 0, // @MinDate, // NULL // FROM [dbo].[aspnet_Applications]; // "; // try // { // using (var connection = _contextFactory.CreateDbContext()) // { // using (var transactionScope = new TransactionScope()) // { // await connection.ExecuteAsync(sql, new // { // UserId = newUserId, // UserName = username, // Password = passwordEncoded, // PasswordSalt = salt, // PasswordQuestion = passwordQuestion, // PasswordAnswer = passwordAnswer, // Email = email, // IsApproved = isApproved, // CreateDate = DateTime.UtcNow, // MinDate = new DateTime(1754, 1, 1), // LastActivityDate = DateTime.UtcNow // }); // transactionScope.Complete(); // return true; // } // } // } // catch (Exception ex) // { // _log.Error($"CreateUser error. {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // return false; // //string sql = "select c.Title, uc.DisplayName " + // // "from mdb_RightsRedirect_aspnet_UserCondos uc " + // // "join aspnet_Users u on uc.UserId = u.UserId " + // // "join mdb_RightsRedirect_aspnet_Condos c on uc.SiteId = c.SiteId " + // // "where u.LoweredUserName = @username and lower(c.Url) = @condopath"; // //using (var cmd = Connection.CreateCommand()) // //{ // // cmd.CommandText = sql; // // cmd.Parameters.AddWithValue("@username", displayName); // // cmd.Parameters.AddWithValue("@condopath", email); // // using (var reader = cmd.ExecuteReader()) // // { // // if (!reader.Read()) // // { // // //fullname = condoname = string.Empty; // // //return false; // // } // // //fullname = reader["DisplayName"].ToString(); // // //condoname = reader["Title"].ToString(); // // //return true; // // } // //} //} //private string EncodePassword(string pass, byte[] salt) //{ // byte[] bytes = Encoding.Unicode.GetBytes(pass); // //byte[] src = Encoding.Unicode.GetBytes(salt); Corrected 5/15/2013 // //byte[] src = Convert.FromBase64String(salt); // byte[] dst = new byte[salt.Length + bytes.Length]; // Buffer.BlockCopy(salt, 0, dst, 0, salt.Length); // Buffer.BlockCopy(bytes, 0, dst, salt.Length, bytes.Length); // HashAlgorithm algorithm = HashAlgorithm.Create("SHA1"); // byte[] inArray = algorithm.ComputeHash(dst); // return Convert.ToBase64String(inArray); //} //private byte[] CreateSalt(byte[] saltSize) //{ // byte[] saltBytes = saltSize; // RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // rng.GetNonZeroBytes(saltBytes); // return saltBytes; //} //async Task UpdateUser(Guid userId, string email) //{ // var sql = @"UPDATE [dbo].[aspnet_Users] SET Email = @Email // WHERE u.UserId = @UserId // "; // using (var connection = _contextFactory.CreateDbContext()) // { // await connection.ExecuteAsync(sql, new { Email = email, UserId = userId }); // } //} public async Task GetUserEmail(Guid taloyhtioUserId) { var sql = $@"SELECT m.Email FROM [dbo].[aspnet_Membership] m WHERE m.UserId = '{taloyhtioUserId}' "; //if (_contextFactory._connection.State == ConnectionState.Closed) //{ // _contextFactory._connection.Open(); //} //var rezult = await _contextFactory._connection.QueryAsync(sql); //_contextFactory._connection.Close(); //return rezult.FirstOrDefault(); using (var db = _contextFactory.GetDbContext()) { return (await db.QueryAsync(sql)).FirstOrDefault(); } } public async Task GetUserName(Guid taloyhtioUserId) { var sql = $@"SELECT m.UserName FROM [dbo].[aspnet_Users] m WHERE m.UserId = '{taloyhtioUserId}' "; using (var db = _contextFactory.GetDbContext()) { return (await db.QueryAsync(sql)).FirstOrDefault(); } } public async Task> GetUserCondos(Guid userId) { var sql = $@"SELECT UserCondo.PmcId, UserCondo.SiteId, UserCondo.Url as PmcName, UserCondo.Title as CondoName FROM [dbo].[mdb_RightsRedirect_aspnet_UserCondos] uc LEFT JOIN [dbo].mdb_RightsRedirect_aspnet_Condos UserCondo ON UserCondo.SiteId = uc.SiteId WHERE uc.UserId = '{userId}' "; using (var db = _contextFactory.GetDbContext()) { //var lookup = new Dictionary(); var result = (await db.QueryAsync( sql, (pmc, condo) => { //if (!lookup.TryGetValue(pmc.PmcId, out var userPmc)) // lookup.Add(pmc.PmcId, userPmc = pmc); //if (userPmc.Condos == null) // userPmc.Condos = new List(); //userPmc.Condos.Add(condo); //return userPmc; pmc.Condos = pmc.Condos ?? new List(); pmc.Condos.Add(condo); return pmc; }, splitOn: "PmcId,SiteId")) .GroupBy(x => new { x.PmcId, x.PmcName}); ; //.AsQueryable(); //return lookup.Values; //_log.Information($"{SPSecurity.AuthenticationMode}"); //RunSecured(() => //{ // try // { // foreach (var pmc in result) // { // //_log.Information($"WWWWWWWWWW: {pmc?.PmcId}"); // pmc.PmcName = GetPMCTitle(pmc.PmcId); // } // } // catch (Exception ex) // { // _log.Error($"GetPMCTitle error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } //}); return result.Select(x => new UserPmc() { PmcId = x.Key.PmcId, PmcName = x.Key.PmcName, Condos = x.SelectMany(c => c.Condos) .GroupBy(c => c.SiteId) .Select(c=> c.FirstOrDefault()) .ToList() }); } } public async Task AddUserToCondo(Guid pmcId, string condoUrl, Guid? userId, int groupId, string groupName, string displayName) { var sql = $@"INSERT INTO [dbo].[mdb_RightsRedirect_aspnet_UserCondos](UserId, SiteId, PmcId, IsPMCLevelGroup, GroupId,GroupName, DisplayName) SELECT '{userId}', SiteId, '{pmcId}', 0, {groupId}, '{groupName}', '{displayName}' FROM [dbo].[mdb_RightsRedirect_aspnet_Condos] WHERE Url='{condoUrl}' AND pmcId = '{pmcId}' AND NOT EXISTS(SELECT 1 FROM [dbo].[mdb_RightsRedirect_aspnet_UserCondos] uc INNER JOIN [dbo].[mdb_RightsRedirect_aspnet_Condos] c ON c.SiteId = uc.SiteId AND c.PmcId = uc.PmcId WHERE uc.UserId='{userId}' AND c.Url='{condoUrl}' AND uc.PmcId='{pmcId}')"; using (var db = _contextFactory.GetDbContext()) { var result = await db.ExecuteAsync(sql); } } public async Task> GetPMCUserList(Guid pmcId, Guid condoId) { var sql = $@"SELECT uc.UserId FROM [dbo].[mdb_RightsRedirect_aspnet_UserCondos] uc WHERE uc.PmcId = '{pmcId}' AND uc.SiteId = '{condoId}' "; using (var db = _contextFactory.GetDbContext()) { return await db.QueryAsync(sql); } } public async Task CheckUserPMCAccess(Guid userId, Guid pmcId) { var sql = $@"SELECT 1 FROM [dbo].[mdb_RightsRedirect_aspnet_UserCondos] uc WHERE uc.PmcId = '{pmcId}' AND uc.UserId = '{userId}' "; //AND uc.SiteId = '{condoId} //comment using (var db = _contextFactory.GetDbContext()) { return (await db.QueryAsync(sql)).FirstOrDefault(); } } public Guid GetUserByEmail(string username) { var sql = $@"select UserID from [dbo].[aspnet_Users] where [LoweredUserName] = '{username}'"; using (var db = _contextFactory.GetDbContext()) { return db.Query(sql).FirstOrDefault(); } } //public Guid RegisterUser(string fbaCurrentUserName, Guid pmcId, Guid webId, string webUrl, // string email, string displayName, out string password) //{ // if (string.IsNullOrEmpty(email)) throw new ArgumentNullException(nameof(email)); // if (string.IsNullOrEmpty(displayName)) throw new ArgumentNullException(nameof(displayName)); // var registeredUserId = Guid.Empty; // string newPassword = string.Empty; // RunSecured(() => // { // try // { // // it is important to get current user before creating new SPSite under elevated privileges // // (after creating new SPSite SPWeb.CurrentUser will return system account) // //var web = SPContext.Current.Web; // //user = web.CurrentUser; // _log.Information($"Open PMC site: {pmcId}"); // using (var site = new SPSite(pmcId)) // { // _log.Information($"PMC site: {site.HostName}"); // _log.Information($"Open web: {webId}"); // using (var spWeb = site.OpenWeb(webUrl, false)) // { // #region Validation // _log.Information($"Web: {spWeb.Url}"); // spWeb.AllowUnsafeUpdates = true; // var membershipProviderName = SecurityHelper.GetMembershipProvider(spWeb.Site); // _log.Information($"{nameof(membershipProviderName)}: {membershipProviderName}"); // var userLogin = SecurityHelper.GetFBALoginName(membershipProviderName.ToLower(), fbaCurrentUserName); // _log.Information($"Get current user: {userLogin}"); // var spUser = spWeb.EnsureUser(userLogin); // //_log.Information($"User: {spUser.Name}"); // //var user = _spRepository.GetUserById(currUserId).GetAwaiter().GetResult(); // //if (user == null) // //{ // // //this.Visible = false; // // return; // //} // //bool isFrontPage = this.Request.Url.AbsoluteUri.ToLower().EndsWith("default.aspx") || // //this.Request.Url.AbsoluteUri.ToLower().EndsWith("etusivu.aspx"); // //if (!WebHelper.IsCondo(spWeb) || !isFrontPage) // //{ // // //this.Visible = false; // // return; // //} // var isGeneralTenant = string.Compare(spUser.Name, GetGeneralTentantUserName(spWeb), true) == 0 || // (string.Compare(spUser.Email, webapi.Infrastructure.Common.Constants.Security.GENERAL_USER_EMAIL, true) == 0 && spUser.Groups.Cast().Any(g => g.Name.Equals(SecurityHelper.GetTenantsGroupName(spWeb)))); // var isGeneralLandlord = string.Compare(spUser.Name, GetGeneralLandlordUserName(spWeb), true) == 0 || // (string.Compare(spUser.Email, webapi.Infrastructure.Common.Constants.Security.GENERAL_USER_EMAIL, true) == 0 && spUser.Groups.Cast().Any(g => g.Name.Equals(SecurityHelper.GetLandlordsGroupName(spWeb)))); // var bmGroupName = SecurityHelper.GetBoardMembersGroupName(spWeb); // var isBoardMemberWithoutEmail = string.IsNullOrEmpty(spUser.Email); // && SecurityHelper.IsUserInGroup(spWeb, user.LoginName, bmGroupName); // //if (isBoardMemberWithoutEmail) // //{ // // //this.BtnSubmit.Text = Resources.TaloyhtioCondoAutomation.RegisterBox_BoardMembers_ButtonText; // //} // //else if (!isGeneralTenant && !isGeneralLandlord) // //{ // // //this.Visible = false; // //} // _log.Information($"isGeneralTenant {isGeneralTenant}, \nisGeneralLandlord {isGeneralLandlord}, \nisBoardMemberWithoutEmail {isBoardMemberWithoutEmail}"); // #endregion // var membershipProvider = Membership.Providers[membershipProviderName]; // if (membershipProvider == null) // { // _log.Warning(string.Format("Membership provider is null web site {0}", spWeb.Url)); // return; // } // //int num = 0; // var users = membershipProvider.FindUsersByName(fbaCurrentUserName, 0, 100, out var num) // .Cast().ToArray(); // if (num == 0) // { // // think it's impossible but let's handle it // _log.Error("FBA User is not found."); // return; // } // var fbaUser = users.FirstOrDefault(); // if (fbaUser == null) // { // _log.Error("FBA User is not found."); // return; // } // registeredUserId = (Guid)fbaUser.ProviderUserKey; // if (isBoardMemberWithoutEmail) // { // //var username = user.LoginName.Split('|').Last(); // //var fbaUser = _spRepository.GetUserByUserName(fbaUserName).GetAwaiter().GetResult(); // //if (fbaUser == null) // //{ // // _log.Error($"FBA User is not found UserName: {fbaUserName}"); // // return; // //} // //var users = membershipProvider.FindUsersByName(fbaUserName, 0, 100, out num).Cast().ToList(); // //if (num == 0) // //{ // // // think it's impossible but let's handle it // // _log.Error("FBA User is not found."); // // return; // //} // //var fbaUser = users.FirstOrDefault(); // //if (fbaUser == null) // //{ // // _log.Error("FBA User is not found."); // // return; // //} // fbaUser.Email = email; // membershipProvider.UpdateUser(fbaUser); // //_spRepository.UpdateUser(fbaUser.UserId, email).GetAwaiter().GetResult(); // _log.Information("FBA User has been updated"); // // update both emails and display name in Sharepoint // try // { // //var spUser = spWeb.EnsureUser(user.LoginName); // spUser.Email = email; // spUser.Name = displayName; // spUser.Update(); // _log.Information("SP User has been updated"); // } // catch (Exception ex) // { // _log.Error($"RegisterUser error. isBoardMemberWithoutEmail. Update user: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // } // else if (isGeneralLandlord || isGeneralTenant) // { // _log.Information($"membershipProvider.FindUsersByName: {email}"); // membershipProvider.FindUsersByName(email, 0, 100, out num) // .Cast() // .ToArray(); // //bool newUser = false; // if (num == 0) // { // //newUser = true; // // create new user to database // newPassword = SecurityHelper.GetRandomPassword().ToString(); // string question = Guid.NewGuid().ToString(); // string answer = Guid.NewGuid().ToString(); // //MembershipCreateStatus status; // _log.Information("Create FBA user"); // var newFBAUser = membershipProvider.CreateUser(email, newPassword, email, question, answer, true, null, out var status); // if (!status.Equals(MembershipCreateStatus.Success)) // { // //if (!_spRepository.CreateUser(email, password, email, question, answer, true).GetAwaiter().GetResult()) // //{ // // // //serversideError.Text = Resources.TaloyhtioCondoAutomation.RegisterBox_CreateError; // // // //serversideError.Visible = true; // _log.Error("FBA user is not created"); // return; // } // _log.Information($"FBA user Id({newFBAUser.ProviderUserKey}) password for Debug only: \"{email}\" \"{newPassword}\""); // registeredUserId = (Guid)newFBAUser.ProviderUserKey; // } // // 2018-05-14; now it should be possible also to ersiter existing users to new condos. So if user already exists // // only add him to appropriate group and send email // string fbaLogin = SecurityHelper.GetFBALoginName(membershipProviderName, email); // // update display name in Sharepoint // try // { // _log.Information("Create SP user"); // var spNewUser = spWeb.EnsureUser(fbaLogin); // spNewUser.Name = displayName; // spNewUser.Update(); // _log.Information("SP user created"); // } // catch (Exception ex) // { // _log.Error($"RegisterUser error. Create user: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // // add user to appropriate group // string groupName = isGeneralLandlord ? SecurityHelper.GetRegisteredLandlordsGroupName(spWeb) : SecurityHelper.GetRegisteredTenantsGroupName(spWeb); // spWeb.AllowUnsafeUpdates = true; // _log.Information($"Add user to group. fbaLogin: {fbaLogin}, email: {email}, groupName: {groupName}"); // SecurityHelper.AddUserToGroup(spWeb, fbaLogin, email, email, groupName); // //_log.Information($"strongAuth2: {JsonConvert.SerializeObject(registeredUser)}"); // //_log.Information("Send email"); // //_log.Information($"Send email1: {_emailService == null}"); // //_log.Information($"Send email2: {SPAdministrationWebApplication.Local == null}"); // //_log.Information($"Send email2: {SPAdministrationWebApplication.Local.OutboundMailServiceInstance == null}"); // //_log.Information($"Send email3: {SPAdministrationWebApplication.Local.OutboundMailSenderAddress}"); // //if (SPAdministrationWebApplication.Local.OutboundMailServiceInstance != null) // //{ // // if (newUser) // // { // // _emailService.SendRegisterNewEmail( // // SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address, // // SPAdministrationWebApplication.Local.OutboundMailSenderAddress, // // email, password, email); // // // login as new user // // //Microsoft.SharePoint.IdentityModel.SPClaimsUtility.AuthenticateFormsUser(new Uri(web.Url), email, password); // // } // // else // // { // // _emailService.SendRegisterExistingEmail( // // SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address, // // SPAdministrationWebApplication.Local.OutboundMailSenderAddress, // // email, email); // // } // //} // //else // //{ // // _log.Error(@"SPAdministrationWebApplication.Local.OutboundMailServiceInstance is not set up."); // //} // } // } // } // } // catch (Exception ex) // { // _log.Error($"RegisterUser error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // password = newPassword; // return registeredUserId; //} //public void CreateFlatFolders(string taloyhtioCondoUrl, Flat flat) //{ // RunSecured(() => // { // try // { // _log.Information($"Open PMS site: {taloyhtioCondoUrl}"); // //request.WebId = Guid.Parse("{ADDBF886-C3F0-4114-BD30-3F41E18C1ADF}"); // //request.PMCId = Guid.Parse("{AFB9E282-E66A-4A1D-8248-BF8E90DEAA27}"); // //request.CurrentUserName = "april16"; // //request.WebUrl = "/complete_eng/april16"; // using (var site = new SPSite(taloyhtioCondoUrl)) // { // _log.Information($"PMC site: {site.HostName}"); // _log.Information($"Open web"); // using (var spWeb = site.OpenWeb()) // "/complete_eng/april16")) // { // // add user to appropriate group // string groupName = SecurityHelper.GetRegisteredFlatGroupName(spWeb, flat.FlatTitle); // spWeb.AllowUnsafeUpdates = true; // _log.Information($"Add group. groupName: {groupName}"); // var spGroup = SecurityHelper.EnsureSiteGroup(spWeb, groupName); // //Spec: Subfolder name will be the same as flat title: A1, A2, etc. // _log.Information($"Create folder: {flat.FlatTitle} to list {webapi.Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE}"); // CreateFlatFolderToList(spWeb, spGroup, flat.FlatTitle, webapi.Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE); // _log.Information($"Create folder: {flat.FlatTitle} to list {webapi.Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE}"); // CreateFlatFolderToList(spWeb, spGroup, flat.FlatTitle, webapi.Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE); // } // } // } // catch (Exception ex) // { // _log.Error($"CreateFlatGroup error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); //} //public IEnumerable GetFlatDocsFoldersList(Guid pmcId, Guid condoId, IEnumerable userFlats, string rootFlatFolderTitle, IEnumerable folderIds) //{ // var result = new List(); // GetFoldersList(pmcId, condoId, userFlats, rootFlatFolderTitle, folderIds, Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE, // (id, title, date, isFolder, count, url) => { // result.Add(new FlatDocsFolder() // { // Id = id, // Title = title, // Date = date, // IsFolder = isFolder, // DocsCount = count, // ItemViewUrl = url // }); // }); // return result.AsEnumerable(); // //var result = new List(); // //if (userFlats?.Any() ?? false) // //{ // // RunSecured(() => // // { // // try // // { // // _log.Information($"Open PMS site: {pmcId}"); // // using (var site = new SPSite(pmcId)) // // { // // _log.Information($"Open web"); // // using (var spWeb = site.OpenWeb(condoId)) // // { // // //Find SP List // // var list = GetListByTitleSafely(spWeb, Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE); // // if (list == null) // // { // // _log.Error(string.Format("List '{0}' not found on web '{1}'. Folder for parsed data won't be created.", // // webapi.Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE, spWeb.Url)); // // return; // // } // // //Add root folder // // if (!folderIds?.Any() ?? true) // // { // // foreach (SPFolder item in list.RootFolder.SubFolders) // // { // // //_log.Information($"WWWWWWWWWWWWWWWWWWWWWWWWWWW: {item.Name}{rootFlatFolderTitle} {(item.Name?.Equals(rootFlatFolderTitle) ?? false)}"); // // if (item.Name?.Equals(rootFlatFolderTitle) ?? false) // // { // // folderIds = new[] { item.Item.ID }; // // break; // // } // // } // // } // // SPFolder parentFolder = FindFolder(list.RootFolder, folderIds.ToList()); // // if (parentFolder != null) return; // // if (parentFolder.SubFolders?.Count > 0) // // { // // foreach (SPFolder folder in parentFolder.SubFolders) // // { // // var title = folder.Name; // // if ((string.IsNullOrEmpty(title)) || // // (title.Equals("Attachments") || title.Equals("Item")) || // // ((!folderIds?.Any() ?? true) && (!userFlats?.Contains(title) ?? true))) // // continue; // // result.Add(new FlatDocsFolder() // // { // // Id = folder.Item.ID, // // Title = title, // // Date = DateTime.UtcNow, // // IsFolder = true, // // DocsCount = folder.ItemCount // // }); // // } // // } // // _log.Information($"parentFolder {parentFolder == null}"); // // var items = list.GetItems(new SPQuery { Folder = parentFolder }); // // _log.Information($"Items Count: {items.Count}"); // // foreach (SPListItem item in items) // // { // // if (item.Folder != null) continue; // // _log.Information($"Doc {item.Name} {item.DisplayName} {item.Title}"); // // result.Add(new FlatDocsFolder() // // { // // Id = item.ID, // // Title = item.Title, // // Date = DateTime.UtcNow, // // IsFolder = false, // // ItemViewUrl = $"Lists/{Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE}" // // }); // // } // // } // // } // // } // // catch (Exception ex) // // { // // _log.Error($"GetFlatDocsFoldersList error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // // } // // }); // //} // //return result.AsEnumerable(); //} //public IEnumerable GetMaterialRepairHistoryList(Guid pmcId, Guid condoId, IEnumerable userFlats, string rootFlatFolderTitle, IEnumerable folderIds) //{ // var result = new List(); // GetFoldersList(pmcId, condoId, userFlats, rootFlatFolderTitle, folderIds, Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE, // (id, title, date, isFolder, count, url) => { // result.Add(new MaterialRepairHistory() // { // Id = id, // Title = title, // Date = date, // IsFolder = isFolder, // DocsCount = count, // ItemViewUrl = url // }); // }); // return result.AsEnumerable(); // //var result = new List(); // //RunSecured(() => // //{ // // try // // { // // //_log.Information($"Open PMS site: {pmcId}"); // // using (var site = new SPSite(pmcId)) // // { // // //_log.Information($"Open web"); // // using (var spWeb = site.OpenWeb(condoId)) // // { // // var list = GetListByTitleSafely(spWeb, Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE); // // if (list == null) // // { // // _log.Error(string.Format("List '{0}' not found on web '{1}'. Folder for parsed data won't be created.", // // webapi.Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE, spWeb.Url)); // // return; // // } // // SPFolderCollection subFolders = null; // // SPFolder parentFolder = list.RootFolder; // // if (folderIds?.Any() ?? false) // // { // // parentFolder = FindFolder(parentFolder, folderIds.ToList(), 0); // // } // // if (parentFolder != null) // // { // // subFolders = parentFolder.SubFolders; // // } // // if (subFolders?.Count > 0) // // { // // foreach (SPFolder folder in subFolders) // // { // // var title = folder.Name; if (string.IsNullOrEmpty(title)) // // continue; // // if (title.Equals("Attachments") || title.Equals("Item")) // // continue; // // if ((!folderIds?.Any() ?? true && !title.Equals(rootFlatFolderTitle, StringComparison.InvariantCultureIgnoreCase)) && // // (!userFlats?.Contains(title) ?? true)) // // continue; // // var subFolder = new MaterialRepairHistory() { // // Id = folder.Item.ID, Title = title, Date = DateTime.UtcNow, IsFolder = true, // // DocsCount = folder.ItemCount // // }; // // result.Add(subFolder); // // } // // } // // if (folderIds?.Any() ?? false) // // { // // _log.Information($"parentFolder {parentFolder == null}"); // // var items = list.GetItems(new SPQuery { Folder = parentFolder }); // // _log.Information($"Items Count: {items.Count}"); // // foreach (SPListItem item in items) // // { // // if (item.Folder != null) continue; // // _log.Information($"Doc {item.Name} {item.DisplayName} {item.Title}"); // // var docItem = new MaterialRepairHistory() // // { // // Id = item.ID, // // Title = item.Title, // // Date = DateTime.UtcNow, // // IsFolder = false, // // ItemViewUrl = $"Lists/{Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE}" // // }; // // result.Add(docItem); // // } // // } // // } // // } // // } // // catch (Exception ex) // // { // // _log.Error($"GetFlatDocsFoldersList error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // // } // //}); // //return result.AsEnumerable(); //} //public void GetIdsByCondoUrl(string taloyhtioCondoUrl, out Guid PMCId, out Guid PMCCondoId) //{ // RunSecured(() => // { // try // { // // it is important to get current user before creating new SPSite under elevated privileges // // (after creating new SPSite SPWeb.CurrentUser will return system account) // //var web = SPContext.Current.Web; // //user = web.CurrentUser; // //request.WebId = Guid.Parse("{ADDBF886-C3F0-4114-BD30-3F41E18C1ADF}"); // //request.PMCId = Guid.Parse("{AFB9E282-E66A-4A1D-8248-BF8E90DEAA27}"); // //request.CurrentUserName = "april16"; // //request.WebUrl = "/complete_eng/april16"; // _log.Information($"Open PMC site: {taloyhtioCondoUrl}"); // using (var site = new SPSite(taloyhtioCondoUrl)) // { // _log.Information($"PMC site: {site.HostName}"); // _log.Information($"Open web"); // using (var spWeb = site.OpenWeb()) // "/complete_eng/april16")) // { // _pmcId = site.ID; // _pmcCondoId = spWeb.ID; // } // } // } // catch (Exception ex) // { // _log.Error($"GetIdsByCondoUrl error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // throw new SPCustomException("CreateFlatFolders error", ex); // } // }); // PMCId = _pmcId; // PMCCondoId = _pmcCondoId; //} //public IEmailSettings GetEmailSettings() { // EmailSettings result = null; // try // { // RunSecured(() => // { // if (SPAdministrationWebApplication.Local?.OutboundMailServiceInstance != null) // { // result = new EmailSettings() // { // SmtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address, // FromAddress = SPAdministrationWebApplication.Local.OutboundMailSenderAddress // }; // } // }); // } // catch (Exception) { } // return result; //} //public IEnumerable GetApprovers(Guid pmcId) //{ // var result = new List(); // RunSecured(() => // { // try // { // using (var site = new SPSite(pmcId)) // { // using (SPWeb web = site.RootWeb) // { // Thread.CurrentThread.CurrentCulture = new CultureInfo((int)web.Language); // Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)web.Language); // var list = GetListByTitleSafely(web, TaloyhtioCondoSites.List_Approvers); // if (list == null) // { // _log.Error($"List '{TaloyhtioCondoSites.List_Approvers}' not found on web '{web.Url}'. Folder for parsed data won't be created."); // return; // } // var userField = list.Fields.Cast() // .FirstOrDefault(f => f.Title == TaloyhtioCondoSites.List_Approvers_User); // if (userField == null || userField.Type != SPFieldType.User)// || item[TaloyhtioCondoSites.List_Sivustot_Responsible_User] == null) // { // _log.Information("User field is null or it's type is not User or it's value is null. Action won't be performed"); // return; // } // foreach (SPListItem item in list.Items) // { // _log.Information("User field found: fieldId = '{0}'. Item value: '{1}'", userField.Id, item[TaloyhtioCondoSites.List_Approvers_User].ToString()); // if (!(userField.GetFieldValue(item[TaloyhtioCondoSites.List_Approvers_User].ToString()) is SPFieldUserValue fieldValue)) // { // _log.Information("User field value is null. Action won't be performed"); // return; // } // var user = fieldValue.User; // if (user == null) // { // _log.Information("User from field value is null. Action won't be performed"); // return; // } // result.Add(user.Email); // _log.Information("User if found: '{0}'", user.Email); // } // } // } // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public IEnumerable> GetTaylohtioCondoNames(IEnumerable taylohtioCondoIds, Guid pmcId) //{ // var result = new List>(); // RunSecured(() => // { // try // { // taylohtioCondoIds.ToList().ForEach(x => // result.Add(new Tuple(x, GetCondoTitle(pmcId, x)))); // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public IEnumerable> GetCondos(Guid pmcId) //{ // var result = new List>(); // RunSecured(() => // { // try // { // using (var site = new SPSite(pmcId)) // { // foreach (SPWeb web in site.RootWeb.Webs) { // //if(condo.WebTemplateId == Common.Constants.SiteTemplates.CONDO_SITE_WEB_TEMPLATE_ID) // if (WebHelper.IsCondo(web)) // result.Add(new Tuple(web.ID, web.Title)); // } // } // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public string GetPMCLang(Guid pmcId) { // var result = Thread.CurrentThread.CurrentCulture.Name; // RunSecured(() => // { // try // { // using (var site = new SPSite(pmcId)) // { // result = new CultureInfo((int)site.RootWeb.Language).Name; // } // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public string GetTaylohtioPMCUrl(Guid pmcId) //{ // var result = string.Empty; // RunSecured(() => // { // try // { // using (var site = new SPSite(pmcId, SPUrlZone.Extranet)) // { // result = site.Url; // } // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public string GetTaylohtioPMCTitle(Guid pmcId) //{ // var result = string.Empty; // RunSecured(() => // { // try // { // using (var site = new SPSite(pmcId)) // { // result = site.RootWeb.Title; // } // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public string GetTaylohtioPMCCondoTitle(Guid pmcId, Guid condoId) //{ // var result = string.Empty; // RunSecured(() => // { // try // { // result = GetCondoTitle(pmcId, condoId); // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public IEnumerable> GetPMCList(Guid pmcId) //{ // var result = new List>(); // RunSecured(() => // { // try // { // using (var site = new SPSite(pmcId)) // { // var webApp = site.WebApplication; // foreach (SPSite pmc in webApp.Sites) // { // if (WebHelper.IsPmc(pmc.RootWeb) && (pmc.ID != webApp.Sites[0].ID)) // result.Add(new KeyValuePair(pmc.ID, pmc.RootWeb.Title)); // } // } // } // catch (Exception ex) // { // _log.Error($"GetTaylohtioCondoNames error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // return result; //} //public void ResolveFolderPath(Guid pmcId, Guid condoId, ListType listType, IEnumerable folderIds, out string listUrl, out string folderPath) //{ // var result = string.Empty; // var listTitle = listType == ListType.FlatMaterial ? // Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE : // Infrastructure.Common.Constants.FLATS_REPAIR_HISTORY_LIST_TITLE; // var resultListUrl = $"Lists/{listTitle}"; // RunSecured(() => // { // try // { // _log.Information($"Open PMS site: {pmcId}"); // using (var site = new SPSite(pmcId)) // { // _log.Information($"Open web"); // using (var spWeb = site.OpenWeb(condoId)) // { // var list = GetListByTitleSafely(spWeb, listTitle); // if (list == null) // { // _log.Error($"List '{listTitle}' not found on web '{spWeb.Url}'. Folder for parsed data won't be created."); // return; // } // SPFolder parentFolder = list.RootFolder; // result = GetFolderPath(parentFolder, folderIds.ToList(), 0); // //_log.Information($"SSSSSSSSSSSSSSSSSS{result}"); // } // } // } // catch (Exception ex) // { // _log.Error($"GetFlatDocsFoldersList error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // folderPath = result; // listUrl = resultListUrl; //} #region general //private void GetFoldersList(Guid pmcId, Guid condoId, IEnumerable userFlats, string rootFlatFolderTitle, IEnumerable folderIds, // string listTitle, Action func) //{ // //var result = new List(); // if (userFlats?.Any() ?? false) // { // RunSecured(() => // { // try // { // _log.Information($"Open PMS site: {pmcId}"); // using (var site = new SPSite(pmcId)) // { // _log.Information($"Open web"); // using (var spWeb = site.OpenWeb(condoId)) // { // //Find SP List // var list = GetListByTitleSafely(spWeb, listTitle); // if (list == null) // { // _log.Error($"List '{listTitle}' not found on web '{spWeb.Url}'. Folder for parsed data won't be created."); // return; // } // //Add root folder // if (!folderIds?.Any() ?? true) // { // foreach (SPFolder item in list.RootFolder.SubFolders) // { // //_log.Information($"WWWWWWWWWWWWWWWWWWWWWWWWWWW: {item.Name}{rootFlatFolderTitle} {(item.Name?.Equals(rootFlatFolderTitle) ?? false)}"); // if (item.Name?.Equals(rootFlatFolderTitle) ?? false) // { // folderIds = new[] { item.Item.ID }; // break; // } // } // } // SPFolder parentFolder = FindFolder(list.RootFolder, folderIds.ToList()); // if (parentFolder != null) return; // if (parentFolder.SubFolders?.Count > 0) // { // foreach (SPFolder folder in parentFolder.SubFolders) // { // var title = folder.Name; // if ((string.IsNullOrEmpty(title)) || // (title.Equals("Attachments") || title.Equals("Item")) || // ((!folderIds?.Any() ?? true) && (!userFlats?.Contains(title) ?? true))) // continue; // func(folder.Item.ID, title, DateTime.UtcNow, true, folder.ItemCount, null); // //result.Add( // // new FlatDocsFolder() // //{ // // Id = folder.Item.ID, // // Title = title, // // Date = DateTime.UtcNow, // // IsFolder = true, // // DocsCount = folder.ItemCount // //}); ; // } // } // _log.Information($"parentFolder {parentFolder == null}"); // var items = list.GetItems(new SPQuery { Folder = parentFolder }); // _log.Information($"Items Count: {items.Count}"); // foreach (SPListItem item in items) // { // if (item.Folder != null) continue; // _log.Information($"Doc {item.Name} {item.DisplayName} {item.Title}"); // func(item.ID, item.Title, DateTime.UtcNow, false, 0, $"Lists/{listTitle}"); // //result.Add( // //new FlatDocsFolder() // //{ // // Id = item.ID, // // Title = item.Title, // // Date = DateTime.UtcNow, // // IsFolder = false, // // ItemViewUrl = $"Lists/{Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE}" // //}); // } // } // } // } // catch (Exception ex) // { // _log.Error($"GetFlatDocsFoldersList error: {ex.Message} {ex.StackTrace} {ex.InnerException}", ex); // } // }); // } // //return result.AsEnumerable(); //} //private void RunSecured(CodeToRunElevated secureCode) //{ // var ctx = HttpContext.Current; // try // { // HttpContext.Current = null; // SPSecurity.RunWithElevatedPrivileges(secureCode); // } // finally // { // HttpContext.Current = null; // } //} //private SPFolder FindFolder(SPFolder folder, List folderIds, int idx = 0) //{ // //if (subFolders == null) return null; // var folderId = folderIds[idx]; // _log.Information($"{folder == null} {folder.SubFolders == null} {folder?.SubFolders?.Count} {folderId}"); // foreach (var subFolder in folder.SubFolders) // { // var f = subFolder as SPFolder; // _log.Information($"f: {f == null}"); // if (folderId.Equals(f?.Item?.ID)) // { // if (f?.SubFolders != null && folderIds.Count() > ++idx) // return FindFolder(f, folderIds, idx); // else // return f; // } // } // return null; //} //private string GetFolderPath(SPFolder folder, List folderIds, int idx) //{ // //if (subFolders == null) return null; // var folderId = folderIds[idx]; // //_log.Information($"{folder == null} {folder.SubFolders == null} {folder?.SubFolders?.Count} {folderId}"); // foreach (var subFolder in folder.SubFolders) // { // SPFolder f = subFolder as SPFolder; // if (folderId.Equals(f?.Item?.ID)) // { // _log.Information($"ЙЙЙЙЙЙЙЙЙЙЙЙЙЙЙЙЙ{f.Name}"); // if (f?.SubFolders != null && folderIds.Count() > ++idx) // return $"{f.Name}/{GetFolderPath(f, folderIds, idx)}"; // else // return f.Name; // } // } // return string.Empty; //} //private string GetPMCTitle(Guid pmcId) //{ // //_log.Information($"WWWWWWWWWWWWWW {pmcId}"); // using (var site = new SPSite(pmcId)) // { // //_log.Information($"QQQQQQQQQQQQQQQ {site==null} {site?.RootWeb?.Title}"); // return site.RootWeb.Title; // } //} //private string GetCondoTitle(Guid pmcId, Guid condoId) //{ // using (var site = new SPSite(pmcId)) // { // using (var spWeb = site.OpenWeb(condoId)) // { // return spWeb.Title; // } // } //} //private string GetCondoShortName(SPWeb web) //, SPUser user) //{ // if (web.AllProperties.ContainsKey(KEY_CONDO_SHORT_NAME)) // { // return web.AllProperties[KEY_CONDO_SHORT_NAME] as string; // } // if (web.Title.ToLower().StartsWith(CONDO_PREFIX.ToLower())) // { // return web.Title.Substring(CONDO_PREFIX.Length); // } // return string.Empty; //} //private string GetGeneralTentantUserName(SPWeb web) //, SPUser condoWeb) //{ // string shortName = GetCondoShortName(web); //, condoWeb); // return shortName.Trim(); //} //private string GetGeneralLandlordUserName(SPWeb web) //, SPUser user) //{ // string shortName = GetCondoShortName(web); //, user); // return string.Format(GENERAL_LANDLORD_NAME_TEMPLATE, shortName.Trim()); //} //private SPList GetListByTitleSafely(SPWeb web, string listTitle) //{ // if (web == null) // { // return null; // } // return web.Lists.Cast().FirstOrDefault(l => // string.Equals(l.Title, listTitle, StringComparison.InvariantCultureIgnoreCase)); //} //private SPFolder CreateFlatFolderToList(SPWeb web, SPGroup group, string folderName, string listName) //{ // try // { // #region Validation // if (string.IsNullOrEmpty(folderName)) // { // _log.Error("Folder name is empty. It won't be created for users parsing."); // return null; // } // //if (group == null) throw new ArgumentNullException(nameof(group)); // var list = GetListByTitleSafely(web, listName); // if (list == null) // { // _log.Error(string.Format("List '{0}' not found on web '{1}'. Folder for parsed data won't be created.", // Constants.FLATS_MATERIALS_LIST_TITLE, web.Url)); // return null; // } // var folder = web.GetFolder($"{list.RootFolder?.Url}/{folderName}"); // if (folder.Exists) // { // _log.Warning(string.Format("Folder '{0}' already exists on list '{1}' on web '{2}'. Something is wrong, can't continue.", // folderName, list.Title, web.Url)); // return null; // } // #endregion // _log.Information($"Add folder {folderName} to list {listName}"); // var newFolder = list.Items.Add("", SPFileSystemObjectType.Folder, folderName); // newFolder.Update(); // _log.Information($"AssignGroupRoleToSecurableObject to list {webapi.Infrastructure.Common.Constants.FLATS_MATERIALS_LIST_TITLE}"); // SecurityHelper.AssignGroupRoleToSecurableObject(web, list, SPRoleType.Editor, group, false); // return newFolder.Folder; // } // catch (Exception x) // { // _log.Error($"CreateFlatFolderToList error {x.Message} {x.StackTrace} {x.InnerException}"); // throw new SPCustomException("CreateFlatFolderToList error", x); // } //} #endregion } }