public List <Group> GetAllActiveGroups() { var result = new Result(); var groupList = new List <Group>(); try { var whereColumns = new List <ConditionColumn> { new ConditionColumn { ColumnName = GlobalAppSettings.DbColumns.DB_Group.IsActive, Condition = Conditions.Equals, Value = true } }; result = _dataProvider.ExecuteReaderQuery( _queryBuilder.SelectAllRecordsFromTable(GlobalAppSettings.DbColumns.DB_Group.DB_TableName, whereColumns)); if (result.Status) { groupList = result.DataTable.AsEnumerable() .Select(row => new Group { GroupId = row.Field <int>(GlobalAppSettings.DbColumns.DB_Group.GroupId), GroupName = row.Field <string>(GlobalAppSettings.DbColumns.DB_Group.Name), GroupDescription = row.Field <string>(GlobalAppSettings.DbColumns.DB_Group.Description), GroupColor = row.Field <string>(GlobalAppSettings.DbColumns.DB_Group.Color), CanDelete = (row.Field <int>(GlobalAppSettings.DbColumns.DB_Group.GroupId) == 1) ? false : true }).ToList(); } return(groupList); } catch (Exception e) { LogExtension.LogError("Error while getting group list", e, MethodBase.GetCurrentMethod(), " Status - " + result.Status); return(groupList); } }
protected override void OnStart(string[] args) { LogExtension.LogInfo("Service started", MethodBase.GetCurrentMethod()); try { timer.Interval = 180000; timer.Elapsed += RecurringTrigger; timer.Start(); base.OnStart(args); ProcessStartTime = DateTime.UtcNow; ProcessEndTime = DateTime.UtcNow.AddMinutes(3); new Task(() => new SchedulerJob().ProcessInitSchedules(ProcessStartTime, ProcessEndTime)).Start(); } catch (Exception e) { LogExtension.LogError("Exception is thrown while starting service", e, MethodBase.GetCurrentMethod()); } }
public static void CreateZipFromFile(string sourceFilePath, string outputFilePath) { sourceFilePath = sourceFilePath.Replace("\\\\", "\\"); outputFilePath = outputFilePath.Replace("\\\\", "\\"); try { using (ZipArchive zipArchive = ZipFile.Open(outputFilePath, ZipArchiveMode.Create)) { zipArchive.CreateEntryFromFile(sourceFilePath, new FileInfo(sourceFilePath).Name, CompressionLevel.Fastest); } } catch (Exception exception) { LogExtension.LogError("Unable to create zip from file", exception, MethodBase.GetCurrentMethod(), " SourceFilePath - " + sourceFilePath + " OutputFilePath - " + outputFilePath); } }
public void ProcessSchedules(DateTime startTime, DateTime endTime) { LogExtension.LogInfo( "Processing schedules between " + startTime.ToString(CultureInfo.InvariantCulture) + " and " + endTime.ToString(CultureInfo.InvariantCulture), MethodBase.GetCurrentMethod()); var tasks = new List <Task>(); var cancellationTokenSource = new CancellationTokenSource(); var scheduleJobs = scheduleJobProcessor.GetScheduleJobs(startTime, endTime); tasks.Add(Task.Factory.StartNew(() => Parallel.ForEach(scheduleJobs, scheduleJob => new Task(() => scheduleJobProcessor.ProcessSchedule(scheduleJob.ScheduleId), cancellationTokenSource.Token, TaskCreationOptions.LongRunning).Delay(GetDifferenceTimeSpan(scheduleJob.CurrentScheduleTime)) .TimeOutAfter(cancellationTokenSource, scheduleJob.ScheduleId)))); Task.WaitAll(tasks.ToArray()); }
public List <Group> SearchUserInGroupwithGroupId(int userId, int groupId) { var groupList = new List <Group>(); var whereColumns = new List <ConditionColumn> { new ConditionColumn { ColumnName = GlobalAppSettings.DbColumns.DB_UserGroup.UserId, Condition = Conditions.Equals, Value = userId }, new ConditionColumn { ColumnName = GlobalAppSettings.DbColumns.DB_UserGroup.GroupId, Condition = Conditions.Equals, LogicalOperator = LogicalOperators.AND, Value = groupId } }; try { var result = _dataProvider.ExecuteReaderQuery( _queryBuilder.SelectAllRecordsFromTable(GlobalAppSettings.DbColumns.DB_UserGroup.DB_TableName, whereColumns)); if (result.Status) { groupList = result.DataTable.AsEnumerable() .Select(r => new Group { GroupId = r.Field <int>(GlobalAppSettings.DbColumns.DB_UserGroup.GroupId) }).ToList(); } return(groupList); } catch (Exception e) { LogExtension.LogError("Error while getting group list with whereConditionColumns", e, MethodBase.GetCurrentMethod(), " UserId - " + userId + " GroupId - " + groupId); return(groupList); } }
public Result ExecuteBulkQuery(string query, string connectionString) { var result = new Result(); if (!string.IsNullOrWhiteSpace(connectionString)) { using (var connection = new SqlCeConnection(connectionString)) { string[] splitter = new string[] { ";" }; var querySplit = query.Split(splitter, StringSplitOptions.RemoveEmptyEntries); for (var a = 0; a < querySplit.Length; a++) { using (var command = new SqlCeCommand(querySplit[a], connection)) { try { command.Connection.Open(); result.ReturnValue = command.ExecuteNonQuery(); } catch (Exception e) { result.Status = false; result.Exception = e; LogExtension.LogError("Exception on ExecuteBulkQuery", e, MethodBase.GetCurrentMethod(), " Query - " + query + " ConnectionString - " + connection); } finally { command.Connection.Close(); command.Dispose(); } } } } } else { var exception = new Exception("Invalid Connection string"); result.Status = false; result.Exception = exception; throw exception; } result.Status = true; return(result); }
public void ReschedulePastSchedulerJobs(DateTime currentTime) { if (!File.Exists(GlobalAppSettings.GetSchedulerExportPath() + "config.xml")) { return; } try { var serviceStopTime = DeserializeTime(GlobalAppSettings.GetSchedulerExportPath() + "config.xml"); var lastProcessedDate = Convert.ToDateTime(serviceStopTime.ScheduleEndTime, CultureInfo.InvariantCulture); var pastSchedules = scheduleJobProcessor.GetFailedJobs(lastProcessedDate, currentTime); scheduleJobProcessor.RescheduleUnProcessedJobs(pastSchedules); File.Delete(GlobalAppSettings.GetSchedulerExportPath() + "config.xml"); } catch (Exception e) { LogExtension.LogError("Exception while re scheduling past schedules", e, MethodBase.GetCurrentMethod()); } }
/// <summary> /// /// </summary> /// <param name="toAddress"></param> /// <param name="subject"></param> /// <param name="body"></param> public void SendEmail(string toAddress, string subject, string body) { try { var messageThread = new Thread(SendEmail); MailMessage.From = new MailAddress(GlobalAppSettings.SystemSettings.MailSettingsAddress); MailMessage.Subject = subject; MailMessage.Body = body; MailMessage.IsBodyHtml = true; MailMessage.To.Add(toAddress); messageThread.Start(); } catch (Exception e) { LogExtension.LogError("Exception is thrown while sending Email", e, MethodBase.GetCurrentMethod(), " ToAddress - " + toAddress + " Subject - " + subject + " Body - " + body); } }
public bool SetData(string key, string itemId, ItemInfo itemData, out string errMsg) { errMsg = string.Empty; try { if (itemData.Data != null) { System.IO.File.WriteAllBytes(this.GetFilePath(itemId, key), itemData.Data); } else if (itemData.PostedFile != null) { var fileName = itemId; if (string.IsNullOrEmpty(itemId)) { fileName = System.IO.Path.GetFileName(itemData.PostedFile.FileName); } using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { itemData.PostedFile.OpenReadStream().CopyTo(stream); byte[] bytes = stream.ToArray(); var writePath = this.GetFilePath(fileName, key); if (System.IO.File.Exists(writePath)) { System.IO.File.Delete(writePath); } System.IO.File.WriteAllBytes(writePath, bytes); stream.Close(); stream.Dispose(); } } } catch (Exception ex) { LogExtension.LogError(ex.Message, ex, MethodBase.GetCurrentMethod()); errMsg = ex.Message; return(false); } return(true); }
protected virtual bool PrepareGroupForLifeExtension(IdentityStoreObject grp) { bool flag; try { if (!Helper.AppConfiguration.get_IsGroupAttestationEnabled()) { TimeSpan lastNotificationSpan = new TimeSpan(); string lastSentValue = this.GetAttributeValue("IMGLastSentExpireNotificationDate", grp.get_AttributesBusinessObject()).get_Value(); if (!string.IsNullOrEmpty(lastSentValue)) { DateTime lastSentDate = Helper.ParseDateTime(lastSentValue); if (lastSentDate.Date == DateTime.MinValue.Date) { GroupsProcessor.logger.ErrorFormat("PrepareGroupForLifeExtension: Invalid date format {0}", lastSentValue); } lastNotificationSpan = DateTime.Now.Subtract(lastSentDate); } else if ((Helper.AppConfiguration.get_GenerateSevenDaysToExpiryReport() ? true : Helper.AppConfiguration.get_GenerateOnedayToExpiryReport())) { DateTime date = DateTime.Now.AddDays(7); date = date.Date; this.SetAttributeValue("XGroupExpirationDate", date.ToString("yyyy MMMM dd HH:mm:ss"), grp.get_AttributesBusinessObject()); flag = true; return(flag); } } else { flag = false; return(flag); } } catch (Exception exception) { Exception ex = exception; LogExtension.LogException(GroupsProcessor.logger, string.Format("An Error occured while performing GLM Expiry operation on group: {0} Reason: {1}", this.GetAttributeValue(Helper.KnownProviderAttributes.get_DisplayName(), grp.get_AttributesBusinessObject()).get_Value() ?? string.Empty, ex.Message), ex); } flag = false; return(flag); }
/// <summary> /// 在应用程序由最终用户正常启动时进行调用。 /// 将在启动应用程序以打开特定文件等情况下使用。 /// </summary> /// <param name="e">有关启动请求和过程的详细信息。</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // 不要在窗口已包含内容时重复应用程序初始化, // 只需确保窗口处于活动状态 if (rootFrame == null) { _appLogger.Info("初始化界面框架"); // 创建要充当导航上下文的框架,并导航到第一页 rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: 从之前挂起的应用程序加载状态 } _appLogger.Info("给窗口内容设置页面框架"); // 将框架放在当前窗口中 Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // 当导航堆栈尚未还原时,导航到第一页, // 并通过将所需信息作为导航参数传入来配置 // 参数 _appLogger.Info("正在跳转主页面"); rootFrame.Navigate(typeof(UIFramework), e.Arguments); } // 确保当前窗口处于活动状态 Window.Current.Activate(); LogExtension.SetupLogger(this.GetType().Assembly, LoggerMembers.Ui); _appLogger.Info("启动流程执行完成"); } }
private string IsValidConnection(string connectionString) { using (var connection = new SqlConnection(connectionString)) { try { connection.Open(); LogExtension.LogInfo("SQL server connected successfully", MethodBase.GetCurrentMethod()); return(_serializer.Serialize(new { result = true, Message = "Success" })); } catch (SqlException ex) { LogExtension.LogInfo("Invalid connection properties", MethodBase.GetCurrentMethod()); LogExtension.LogError("Error in checking wheteher a valid conection exists", ex, MethodBase.GetCurrentMethod()); var outMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; return(_serializer.Serialize(new { result = false, Message = outMessage })); } } }
public ServiceConfiguration GetConfigurations() { ServiceConfiguration serviceConfiguration; LogExtension.EnterMethod(SettingsSecureFileStore.logger, MethodBase.GetCurrentMethod()); try { string encXml = SerializationHelper.ReadFromFile(SettingsSecureFileStore.FilePath); serviceConfiguration = ServiceConfiguration.FromXml(CryptographyHelper.DecryptFromLocalMachine(encXml)); return(serviceConfiguration); } catch (Exception exception) { Exception ex = exception; SettingsSecureFileStore.logger.Error(ex.Message, ex); } LogExtension.EnterMethod(SettingsSecureFileStore.logger, MethodBase.GetCurrentMethod()); serviceConfiguration = null; return(serviceConfiguration); }
public DataResponse IsGroupAlreadyExist(string groupName) { var dataResponse = new DataResponse(); try { var whereColumns = new List <ConditionColumn> { new ConditionColumn { ColumnName = GlobalAppSettings.DbColumns.DB_Group.Name, Condition = Conditions.Equals, Value = groupName }, new ConditionColumn { ColumnName = GlobalAppSettings.DbColumns.DB_Group.IsActive, Condition = Conditions.Equals, LogicalOperator = LogicalOperators.AND, Value = true } }; var result = _dataProvider.ExecuteReaderQuery( _queryBuilder.SelectAllRecordsFromTable(GlobalAppSettings.DbColumns.DB_Group.DB_TableName, whereColumns)); dataResponse.Success = result.Status; if (result.Status) { dataResponse.Value = (result.DataTable.Rows.Count != 0); } return(dataResponse); } catch (Exception e) { dataResponse.Success = false; LogExtension.LogError("Error while validating group name", e, MethodBase.GetCurrentMethod(), " GroupName - " + groupName); return(dataResponse); } }
static bool ParseLineToObject(string line, Dictionary <string, int> fieldDictionary, FieldInfo[] fieldInfos, object targetObject, bool strict) { string[] values = EnumerateCSVLine(line).ToArray(); bool setAny = false; foreach (string field in fieldDictionary.Keys) { int index = fieldDictionary[field]; if (index < values.Length) { string value = values[index]; setAny = SetField(field, value, fieldInfos, targetObject) || setAny; } else if (strict) { LogExtension.Warning(string.Format("CSVParser : {0}번째 줄을 파싱하는데 Fields가 충분하지 않습니다.", line)); } } return(setAny); }
public void ProcessJob(TaskScheduling task) { try { ServicesAdministrationServiceClient adminClient = new ServicesAdministrationServiceClient(true); ServicesSearchServiceClient searchClient = new ServicesSearchServiceClient(false); IdentityStore store = adminClient.GetIdentityStoreById(task.get_IdentityStoreId(), true); KnownAttributes knownAttributes = searchClient.GetKnownAttributes(task.get_IdentityStoreId()); List <PermissionAnalyzerServer> servers = new List <PermissionAnalyzerServer>(); Dictionary <string, Dictionary <int, string> > configurations = this.LoadConfigurations(store, adminClient, servers, knownAttributes); List <Schema> schema = adminClient.GetIdentityStoreSchema(task.get_IdentityStoreId()); if (servers.Count > 0) { (new Imanami.PermissionReplicationService.PermissionReplicationService(store, configurations, schema, knownAttributes)).ReplicatePermissions(1, servers); } } catch (Exception exception) { LogExtension.LogException(PermissionAnalyzer.logger, "Error While Replicating Permissions.", exception); } PermissionAnalyzer.logger.InfoFormat("Job processed successfully.", Array.Empty <object>()); }
public bool DisposeObjects() { try { string targetFolder = HttpContext.Current.Server.MapPath("~/"); targetFolder += "Cache"; if (Directory.Exists(targetFolder)) { string[] dirs = Directory.GetDirectories(targetFolder); for (var index = 0; index < dirs.Length; index++) { string[] files = Directory.GetFiles(dirs[index]); var fileCount = 0; for (var fileIndex = 0; fileIndex < files.Length; fileIndex++) { FileInfo fi = new FileInfo(files[fileIndex]); if (fi.LastAccessTimeUtc < DateTime.UtcNow.AddDays(-2)) { fileCount++; } } if (files.Length == 0 || (files.Length == fileCount)) { Directory.Delete(dirs[index], true); } } } return(true); } catch (Exception ex) { LogExtension.LogError(ex.Message, ex, MethodBase.GetCurrentMethod()); } return(false); }
public Result ExecuteNonQuery(string query) { var result = new Result(); if (!string.IsNullOrWhiteSpace(_connectionString)) { using (var connection = new SqlCeConnection(_connectionString)) { using (var command = new SqlCeCommand(query, connection)) { try { command.Connection.Open(); result.ReturnValue = command.ExecuteNonQuery(); } catch (Exception e) { result.Status = false; result.Exception = e; LogExtension.LogError("Exception on ExecuteNonQuery", e, MethodBase.GetCurrentMethod(), " Query - " + query + " ConnectionString - " + connection); } finally { command.Connection.Close(); command.Dispose(); } } } } else { var exception = new Exception("Invalid Connection string"); result.Status = false; result.Exception = exception; throw exception; } result.Status = true; return(result); }
protected void Application_Error(object sender, EventArgs e) { try { var exception = Server.GetLastError(); LogExtension.LogError("Application Error - Server's Last Error", exception, MethodBase.GetCurrentMethod()); var httpException = exception as HttpException; var httpStatusCode = (exception is HttpException) ? httpException.GetHttpCode() : 0; var routeData = new RouteData(); if (httpStatusCode == 404) { routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "HttpError404"); LogExtension.LogError("Application Error 404", httpException, MethodBase.GetCurrentMethod()); } else { routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "HttpError500"); LogExtension.LogError("Application Error 500", httpException, MethodBase.GetCurrentMethod()); } Server.ClearError(); Response.Clear(); IController errorController = new ErrorController(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } catch (Exception ex) { LogExtension.LogError("Error in Application Error ", ex, MethodBase.GetCurrentMethod()); } }
public Result ExecuteScalarQuery(string query, string connectionString, Guid?guid = null) { var result = new Result(); if (!string.IsNullOrWhiteSpace(connectionString)) { var connection = new SqlCeConnection(connectionString); var command = new SqlCeCommand(query, connection); try { connection.Open(); command.ExecuteNonQuery(); command.CommandText = "SELECT @@IDENTITY"; result.ReturnValue = (String.IsNullOrWhiteSpace(guid.ToString())) ? command.ExecuteScalar() : guid; } catch (Exception e) { result.Status = false; result.Exception = e; LogExtension.LogError("Exception on ExecuteScalarQuery", e, MethodBase.GetCurrentMethod(), " Query - " + query + " ConnectionString - " + connection + " Guid - " + guid); } finally { connection.Close(); command.Dispose(); } } else { var exception = new Exception("Invalid Connection string"); result.Status = false; result.Exception = exception; throw exception; } result.Status = true; return(result); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { try { var settings = new SystemSettingsSerializer().Deserialize(GlobalAppSettings.GetConfigFilepath() + ServerSetup.Configuration); if (filterContext.HttpContext.Request.Url != null) { string[] segments = filterContext.HttpContext.Request.Url.Segments; if (settings == null || (segments.Length == 2 && (segments[1].ToLower() == "startup" || segments[1].ToLower() == "login")) || (segments.Length == 3 && ((segments[1].ToLower() == "error/" && segments[2].ToLower() == "httperror500") || (segments[1].ToLower() == "user/" && segments[2].ToLower() == "avatar")))) { base.OnActionExecuting(filterContext); } else if (GlobalAppSettings.IsLatestVersion) { new DatabaseSchemaUpdater(); GlobalAppSettings.IsLatestVersion = DatabaseSchemaUpdater.IsLatestVersion(); if (GlobalAppSettings.IsLatestVersion) { LogExtension.LogError("Application Error 500 - Error in updating database schema", null, MethodBase.GetCurrentMethod()); filterContext.Result = new ViewResult { ViewName = "../Error/HttpError500" }; } base.OnActionExecuting(filterContext); } else { base.OnActionExecuting(filterContext); } } } catch (Exception e) { LogExtension.LogError("Exception occured in AppicationVersionValidationActionFilter :", e, MethodBase.GetCurrentMethod()); } }
public EmailConfiguration() { try { SmtpClient = new SmtpClient { Host = GlobalAppSettings.SystemSettings.MailSettingsHost, Port = GlobalAppSettings.SystemSettings.MailSettingsPort, UseDefaultCredentials = false, Credentials = new NetworkCredential(GlobalAppSettings.SystemSettings.MailSettingsAddress, GlobalAppSettings.SystemSettings.MailSettingsPassword), EnableSsl = GlobalAppSettings.SystemSettings.MailSettingsIsSecureAuthentication }; MailMessage = new MailMessage { IsBodyHtml = true }; } catch (Exception e) { LogExtension.LogError("Exception is thrown while configuring Email", e, MethodBase.GetCurrentMethod(), " Host - " + SmtpClient.Host + " Port - " + SmtpClient.Port + " UseDefaultCredentials - " + SmtpClient.UseDefaultCredentials + " MailSettingsAddress - " + GlobalAppSettings.SystemSettings.MailSettingsAddress + " MailSettingsPassword - " + GlobalAppSettings.SystemSettings.MailSettingsPassword + " EnableSsl - " + GlobalAppSettings.SystemSettings.MailSettingsIsSecureAuthentication); } }
public static string GetReportServerVersionOfInstalledMachine() { string version; try { var result = GlobalAppSettings.DataProvider.ExecuteReaderQuery(GlobalAppSettings.QueryBuilder.SelectAllRecordsFromTable(GlobalAppSettings.DbColumns.DB_ApplicationVersion.DB_TableName)); if (result != null && result.DataTable != null && result.DataTable.Rows.Count > 0) { version = result.DataTable.Rows[0].Field <string>("VersionNumber").ToLower(); } else { version = "1.1.0.1"; } } catch (Exception ex) { version = null; LogExtension.LogError("Error in getting ReportServer version of installed machine", ex, MethodBase.GetCurrentMethod()); } return(version); }
public static IOrderedEnumerable <KeyValuePair <string, string> > GetScriptToExecute(List <Version> versionList, string installedVersionNumber) { var scriptToInstall = new Dictionary <string, string>(); try { foreach (var version in versionList) { if (String.Compare(version.VersionNumber, installedVersionNumber) == 0) { break; } scriptToInstall.Add(version.VersionNumber, version.ScriptName); } } catch (Exception ex) { LogExtension.LogError("Error in getting script to excute", ex, MethodBase.GetCurrentMethod()); } return(scriptToInstall.OrderBy(k => k.Key)); }
public ServiceStopTime DeserializeTime(string path) { var xmlSerializer = new XmlSerializer(typeof(ServiceStopTime)); try { if (File.Exists(path)) { ServiceStopTime data; using (var reader = new StreamReader(path)) { data = (ServiceStopTime)xmlSerializer.Deserialize(reader); reader.Close(); } return(data); } } catch (Exception ex) { LogExtension.LogError("Exception while deserializing service stop time", ex, MethodBase.GetCurrentMethod()); } return(null); }
public void LogError(string errorCode, string message, Exception exception, string errorDetail, string methodName, string className) { LogExtension.LogError(message, exception, System.Reflection.MethodBase.GetCurrentMethod(), errorCode + "-" + errorDetail); }
public void LogError(string message, Exception exception, MethodBase methodType, ErrorType errorType) { LogExtension.LogError(message, exception, methodType, errorType == ErrorType.Error ? "Error" : "Info"); }
public Dictionary <string, Dictionary <int, string> > LoadConfigurations(IdentityStore store, ServicesAdministrationServiceClient _client, List <PermissionAnalyzerServer> servers, KnownAttributes knownAttributes) { Dictionary <string, Dictionary <int, string> > strs; try { try { PermissionAnalyzerConfigurationService permissionAnalyzerConfigurationService = new PermissionAnalyzerConfigurationService(store.get_IdentityStoreId()); Dictionary <string, Dictionary <int, string> > strs1 = new Dictionary <string, Dictionary <int, string> >(); IdentityStorePermissionAnalyzerConfiguration permissionConfigurations = permissionAnalyzerConfigurationService.GetPermissionConfigurations(); if ((permissionConfigurations == null || permissionConfigurations.get_Servers() == null ? false : permissionConfigurations.get_Servers().Count > 0)) { if (permissionConfigurations.get_IncludeFutureServers()) { List <PermissionAnalyzerServer> allServers = permissionAnalyzerConfigurationService.GetCriteriaBasedServers(permissionConfigurations); IEnumerable <string> strs2 = ( from x in allServers select x.get_ServerID()).Except <string>( from y in permissionConfigurations.get_Servers() select y.get_ServerID()); IEnumerable <PermissionAnalyzerServer> latestServers = from server in allServers where strs2.Any <string>((string id) => server.get_ServerID().Equals(id, StringComparison.InvariantCultureIgnoreCase)) select server; if ((latestServers == null ? false : latestServers.Count <PermissionAnalyzerServer>() > 0)) { permissionConfigurations.get_Servers().AddRange(latestServers); } } if ((Helper.CurrentTask.get_Targets() == null ? false : Helper.CurrentTask.get_Targets().Count > 0)) { permissionConfigurations.set_Servers(( from server in permissionConfigurations.get_Servers() where Helper.CurrentTask.get_Targets().Any <SchedulingTarget>((SchedulingTarget target) => target.get_Target().Equals(server.get_ServerID(), StringComparison.InvariantCultureIgnoreCase)) select server).ToList <PermissionAnalyzerServer>()); Helper.CurrentTask.get_Targets().Clear(); } permissionConfigurations.get_Servers().ForEach((PermissionAnalyzerServer server) => { if (permissionConfigurations.get_ExcludedServers() != null) { if (permissionConfigurations.get_ExcludedServers().Any <string>((string excludedServer) => excludedServer.Equals(server.get_ServerID(), StringComparison.InvariantCultureIgnoreCase))) { return; } } if (!string.IsNullOrEmpty(server.get_ScheduleJob())) { if (!server.get_ScheduleJob().Equals(PermissionAnalyzerConfigurationService.GetScheduleName())) { return; } } if (server.get_Credentials() == null) { server.set_Credentials(new PermissionAnalyzerServerCredentials()); } server.get_Credentials(); if (server.get_IsServiceAccountConfigured()) { server.get_Credentials().set_UserName(store.get_IdentityStoreConfigurationValues()["UserName"]); server.get_Credentials().set_Password(store.get_IdentityStoreConfigurationValues()["Password"]); } server.get_Credentials().set_ServerName(server.get_Server()); if ((server.get_FileShare() == null ? false : server.get_FileShare().get_Shares() != null)) { List <string> serverShares = new List <string>(); if (!server.get_IsServiceAccountConfigured()) { server.get_Credentials().set_Password(CryptographyHelper.DecryptFromLocalMachine(server.get_Credentials().get_Password())); } try { serverShares = permissionAnalyzerConfigurationService.GetNetworkShareResourcesList(server.get_Credentials()); } catch (Exception exception) { } if (!server.get_IsServiceAccountConfigured()) { server.get_Credentials().set_Password(CryptographyHelper.EncryptForLocalMachine(server.get_Credentials().get_Password())); } serverShares.ForEach((string latestShare) => { if (!server.get_FileShare().get_Shares().Any <PermissionAnalyzerServerShare>((PermissionAnalyzerServerShare x) => x.get_ShareID().Equals(latestShare, StringComparison.InvariantCultureIgnoreCase))) { List <PermissionAnalyzerServerShare> shares = server.get_FileShare().get_Shares(); PermissionAnalyzerServerShare permissionAnalyzerServerShare = new PermissionAnalyzerServerShare(); permissionAnalyzerServerShare.set_IsSelected(true); permissionAnalyzerServerShare.set_Share(latestShare); permissionAnalyzerServerShare.set_ShareID(latestShare); shares.Add(permissionAnalyzerServerShare); } }); } this.SetConfigurations(store, server, strs1); servers.Add(server); }); } strs = strs1; return(strs); } catch (Exception exception1) { Exception ex = exception1; LogExtension.LogException(PermissionAnalyzer.logger, ex.Message, ex); } } finally { (new ServicesSchedulingServiceClient(false)).Update(Helper.CurrentTask); } strs = new Dictionary <string, Dictionary <int, string> >(); return(strs); }
/// <summary> /// Add System Admin /// </summary> /// <param name="userName">User name</param> /// <param name="firstName">Full name of user</param> /// <param name="lastName">Last name of user</param> /// <param name="emailId">Email Id</param> /// <param name="password">Password</param> public static void AddSystemAdmin(string userName, string firstName, string lastName, string emailId, string password) { LogExtension.LogInfo("Creating system admin", MethodBase.GetCurrentMethod()); var encrypt = new Cryptography(); var umpUser = new User(); var userManagement = new UserManagement(GlobalAppSettings.QueryBuilder, GlobalAppSettings.DataProvider); var groupManagement = new GroupManagement(GlobalAppSettings.QueryBuilder, GlobalAppSettings.DataProvider); umpUser.Password = Convert.ToBase64String(encrypt.Encryption(password)); umpUser.CreatedDate = DateTime.UtcNow; umpUser.ModifiedDate = DateTime.UtcNow; umpUser.IsActive = true; umpUser.IsDeleted = false; umpUser.ResetPasswordCode = "default"; umpUser.ActivationCode = "default"; umpUser.UserName = userName; umpUser.FirstName = firstName.Trim(); umpUser.LastName = lastName.Trim(); umpUser.DisplayName = (umpUser.FirstName.Trim() + " " + umpUser.LastName.Trim()).Trim(); umpUser.Email = emailId; umpUser.IsActivated = true; var activationCode = String.Empty; var activationExpirationDate = new DateTime(); LogExtension.LogInfo("Adding user in user table", MethodBase.GetCurrentMethod()); var result = userManagement.AddUser(umpUser, out activationExpirationDate, out activationCode); if (result.Status) { LogExtension.LogInfo("Adding user in user table succesful", MethodBase.GetCurrentMethod()); LogExtension.LogInfo("Adding user in super admin group table", MethodBase.GetCurrentMethod()); var userGroup = groupManagement.AddUserInGroup(Convert.ToInt32(result.ReturnValue), 1); LogExtension.LogInfo("Is user added in super admin?" + userGroup, MethodBase.GetCurrentMethod()); //var permissionSet = new PermissionSet(); //permissionSet.AddPermissionToGroup(new Permission //{ // PermissionAccess = PermissionAccess.Create, // PermissionEntity = PermissionEntity.AllCategories, // TargetId = 1 //}); //permissionSet.AddPermissionToGroup(new Permission //{ // PermissionAccess = PermissionAccess.Create, // PermissionEntity = PermissionEntity.AllReports, // TargetId = 1 //}); //permissionSet.AddPermissionToGroup(new Permission //{ // PermissionAccess = PermissionAccess.Create, // PermissionEntity = PermissionEntity.AllSchedules, // TargetId = 1 //}); //permissionSet.AddPermissionToGroup(new Permission //{ // PermissionAccess = PermissionAccess.Create, // PermissionEntity = PermissionEntity.AllDataSources, // TargetId = 1 //}); //permissionSet.AddPermissionToGroup(new Permission //{ // PermissionAccess = PermissionAccess.Create, // PermissionEntity = PermissionEntity.AllFiles, // TargetId = 1 //}); } else { LogExtension.LogInfo("Error in adding user in user table", MethodBase.GetCurrentMethod()); } }
public static void InsertSampleReports() { try { //var itemManagement = new ItemManagement(); //var item = new Item(); var userManagement = new UserManagement(); var userDetail = userManagement.FindUserByUserId(1); var baseUrl = new UriBuilder(HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port).ToString(); var dataSourceId = Guid.Empty; //#region AddCategory //var category = new ItemDetail() //{ // Name = "Sample Reports", // Description = "Check our sample reports in this category", // CreatedById = userDetail.UserId, // CreatedDate = DateTime.UtcNow.ToString(GlobalAppSettings.GetDateTimeFormat()), // ItemType = ItemType.Category, // ModifiedById = userDetail.UserId, // ModifiedDate = DateTime.UtcNow.ToString(GlobalAppSettings.GetDateTimeFormat()) //}; //item.AddNewCategory(category); //#endregion //#region Add Data Sources //List<FileInfo> dataSourceList = // new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\SampleReports").GetFiles("*.rds").ToList(); //dataSourceList = dataSourceList.OrderByDescending(o => o.Name).ToList(); //foreach (var dataSource in dataSourceList) //{ // DataSourceDefinition dataSourceDefinition; // var xmlSerializer = new XmlSerializer(typeof(DataSourceDefinition)); // using (var reader = new StreamReader(dataSource.FullName)) // { // dataSourceDefinition = (DataSourceDefinition)xmlSerializer.Deserialize(reader); // reader.Close(); // } // var itemRequest = new ItemRequest // { // Description = "This is a sample data source.", // DataSourceDefinition = dataSourceDefinition, // ItemType = ItemType.Datasource, // Name = Path.GetFileNameWithoutExtension(dataSource.Name), // UserName = userDetail.UserName, // Password = userDetail.Password // }; // using (var webclient = new WebClient()) // { // var serializer = new DataContractJsonSerializer(typeof(ItemRequest)); // var memoryStream = new MemoryStream(); // serializer.WriteObject(memoryStream, itemRequest); // var data = Encoding.UTF8.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length); // webclient.Headers["Content-type"] = "application/json"; // webclient.Encoding = Encoding.UTF8; // var apiResult = webclient.UploadString(baseUrl.TrimEnd('/') + "/api/reportserverapi/add-data-source", "POST", data); // var itemResponse = JsonConvert.DeserializeObject<ItemResponse>(apiResult); // dataSourceId = itemResponse.PublishedItemId; // } //} //#endregion //#region AddReports //var temporaryDirectory = Path.Combine(GlobalAppSettings.GetItemsPath() + "Temporary_Files"); //if (Directory.Exists(temporaryDirectory) == false) //{ // Directory.CreateDirectory(temporaryDirectory); //} //List<FileInfo> reportList = // new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\SampleReports").GetFiles("*.rdl").ToList(); //reportList = reportList.OrderByDescending(o => o.Name).ToList(); //foreach (var report in reportList) //{ // var xmlDocument = new XmlDocument(); // xmlDocument.Load(report.FullName); // var dataSourceNodes = xmlDocument.GetElementsByTagName("DataSource"); // foreach (var dataSourceNode in dataSourceNodes) // { // var xmlLinkedNode = dataSourceNode as XmlLinkedNode; // foreach (var childNodes in xmlLinkedNode.ChildNodes) // { // var xmlChildLinkedNode = childNodes as XmlLinkedNode; // if (xmlChildLinkedNode.Name == "DataSourceReference") // { // xmlChildLinkedNode.InnerText = dataSourceId.ToString(); // } // } // } // var tempReportName = temporaryDirectory + "\\" + report.Name; // xmlDocument.Save(tempReportName); // var itemRequest = new ItemRequest // { // CategoryId = itemManagement.GetItemDetailsFromItemName(category.Name, ItemType.Category).Id, // DataSourceMappingInfo = new List<DataSourceMappingInfo> // { // new DataSourceMappingInfo // { // DataSourceId = dataSourceId, // Name = Path.GetFileNameWithoutExtension(dataSourceList.FirstOrDefault().Name) // } // }, // Description = "This is a sample report.", // ItemContent = File.ReadAllBytes(tempReportName), // ItemType = ItemType.Report, // Name = Path.GetFileNameWithoutExtension(tempReportName), // UserName = userDetail.UserName, // Password = userDetail.Password // }; // using (var webclient = new WebClient()) // { // var serializer = new DataContractJsonSerializer(typeof(ItemRequest)); // var memoryStream = new MemoryStream(); // serializer.WriteObject(memoryStream, itemRequest); // var data = Encoding.UTF8.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length); // webclient.Headers["Content-type"] = "application/json"; // webclient.Encoding = Encoding.UTF8; // var apiResult = webclient.UploadString(baseUrl.TrimEnd('/') + "/api/reportserverapi/add-report", "POST", data); // var itemResponse = JsonConvert.DeserializeObject<ItemResponse>(apiResult); // } //} //LogExtension.LogInfo("Sample reports has been added successfully.", MethodBase.GetCurrentMethod()); //#endregion } catch (Exception ex) { LogExtension.LogError("Error in adding sample reports.", ex, MethodBase.GetCurrentMethod()); } }