public Dictionary <string, Boolean> Get() { Dictionary <string, Boolean> permissions = new Dictionary <string, Boolean>(); using (ServerApplicationContext context = ServerApplicationContext.CreateContext()) { var currentUser = context.Application.User; if (currentUser.IsAuthenticated) { permissions.Add(Permissions.SecurityAdministration, currentUser.HasPermission(Permissions.SecurityAdministration)); currentUser.AddPermissions(Permissions.SecurityAdministration); foreach (Permission permission in context.DataWorkspace.SecurityData.Permissions) { if (permission.Id != Permissions.SecurityAdministration) { permissions.Add(permission.Id, currentUser.HasPermission(permission.Id)); } } } } return(permissions); }
// ======================================================================================================= // Helper - Get all the permissions for a particular role // Data: RoleName // Returns: List of Permisisons for the role, RolePermissionDTO // ======================================================================================================= private static IEnumerable <RolePermissionDTO> GetLightSwitchRolePermissions(string roleName) { try { if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC9"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; var result = dbContext.SecurityData.RolePermissions .Where(r => r.RoleName == roleName) .Select(rp => new RolePermissionDTO { RoleName = rp.RoleName, PermissionId = rp.PermissionId }) .Execute(); return(result); } } catch (Exception e) { throw new Exception(e.Message, e.InnerException); } }
public void Export(string filename, string email, int year, int month) { using (var helper = new SpreadsheetHelper(filename)) { if (!helper.MoveWorksheet(sheetName)) { throw new ApplicationException("不正なテンプレートです。" + sheetName + "のシートがありません"); } var worksheet = helper.CurrentSheet; helper.SetCellValue(emailAddressCell, email); using (var serverContext = ServerApplicationContext.CreateContext()) { var startDate = new DateTime(year, month, 1); helper.SetCellValue(startDateCell, startDate); var sb = new StringBuilder(); using (var workspace = serverContext.Application.CreateDataWorkspace()) { foreach (WorkTime item in workspace.ApplicationData.WorkTimeSet.Where(x => x.UserId == email && x.WorkDate.Year == year && x.WorkDate.Month == month)) { var rowIdx = item.WorkDate.Day - 1 + startPos; helper.SetCellValue(4, rowIdx, item.SickHolidy); helper.SetCellValue(9, rowIdx, item.StartTime); helper.SetCellValue(11, rowIdx, item.EndTime); helper.SetCellValue(16, rowIdx, item.Remark); } } } helper.Save(filename); } }
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["id"] != null) { int RecordId = int.Parse(Request.QueryString["id"].ToString()); using (ServerApplicationContext ctx = ServerApplicationContext.CreateContext()) { if (ctx.Application.User.HasPermission(Permissions.CanViewAppData)) { var fileDet = ctx.DataWorkspace.ApplicationData.si_application_adv_files_SingleOrDefault(RecordId); if (fileDet == null) { throw new HttpResponseException(HttpStatusCode.NoContent); } else { HttpResponse response = HttpContext.Current.Response; response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileDet.advFileName); response.TransmitFile(Server.MapPath(fileDet.advFileDirectory + fileDet.advFileName)); response.End(); } } } } }
public void Submit(string filename, string email, int year, int month) { using (var serverContext = ServerApplicationContext.CreateContext()) { using (var workspace = serverContext.Application.CreateDataWorkspace()) { var entried = workspace.ApplicationData.WorkTimeSet.Where(x => x.UserId == email && x.WorkDate.Year == year && x.WorkDate.Month == month).Select(x => x.WorkDate).Execute().ToList(); var holidays = HolidyManager.GenerateHoliday(year); foreach (var day in Enumerable.Range(1, DateTime.DaysInMonth(year, month))) { var targetDay = new DateTime(year, month, day); if (targetDay.DayOfWeek == DayOfWeek.Sunday || targetDay.DayOfWeek == DayOfWeek.Saturday) { continue; } if (holidays.ContainsKey(targetDay)) { continue; } if (!entried.Contains(targetDay)) { throw new ApplicationException(targetDay.ToString("d") + "の入力がありません。"); } } } } Export(filename, email, year, month); using (var serverContext = ServerApplicationContext.CreateContext()) { var appWebContext = serverContext.Application.SharePoint; using (var ctx = appWebContext.GetAppWebClientContext()) { var list = ctx.Web.Lists.GetByTitle("WorkTimeSheet"); var rootFolder = list.RootFolder; ctx.Load(rootFolder, x => x.Folders, x => x.ServerRelativeUrl); ctx.ExecuteQuery(); var subFolderName = year.ToString("0000") + month.ToString("00"); var subFolder = list.RootFolder.Folders.Where(x => x.Name == subFolderName).FirstOrDefault(); if (subFolder == null) { subFolder = rootFolder.Folders.Add(rootFolder.ServerRelativeUrl + "/" + subFolderName); ctx.Load(subFolder); ctx.ExecuteQuery(); } using (var st = new FileStream(filename, FileMode.Open)) { var info = new FileCreationInformation(); info.ContentStream = st; info.Overwrite = true; info.Url = subFolder.ServerRelativeUrl + "/" + email.Replace("@", "_") + ".xlsx"; var file = subFolder.Files.Add(info); ctx.ExecuteQuery(); } } } }
// ======================================================================================================= // Helper - Remove Permission from a role // Data: RoleName, LightSwitch PermissionId // Returns: Nothing // ======================================================================================================= private static void RemoveLightSwitchPermissionFromRole(string roleName, string permissionId) { try { if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC11"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; // Find our role/permission association entity var rolePermission = dbContext.SecurityData.RolePermissions_Single(roleName, permissionId); // Delete the entity and save rolePermission.Delete(); dbContext.SecurityData.SaveChanges(); } } catch (Exception e) { throw new Exception(e.Message, e.InnerException); } }
// ===================================================================================== // ===================================================================================== // Helper functions // Key item to note... there can only be 1 instance of the ServerApplicationContext! // ===================================================================================== // ===================================================================================== #region helpers // ======================================================================================================= // Helper - Get the permissions for this LightSwitch application // Data: None // Returns: List of PermissionDTOs // ======================================================================================================= private static IEnumerable <PermissionDTO> GetLightSwitchApplicationPermissions() { try { if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC7"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; var resultList = (from Permission p in dbContext.SecurityData.Permissions select new PermissionDTO { Id = p.Id, Name = p.Name }).ToList(); return(resultList); } } catch (Exception e) { throw new Exception(e.Message, e.InnerException); } }
// GET: odata/ActiveDirectoryUsers(5) public async Task <IHttpActionResult> GetActiveDirectoryUser([FromODataUri] string key, ODataQueryOptions <Models.ActiveDirectoryUser> queryOptions) { string fn = string.Format("{0}:{1}.{2}", this.GetType().Namespace, this.ControllerContext.ControllerDescriptor.ControllerName, this.ControllerContext.Request.GetActionDescriptor().ActionName); Debug.WriteLine(fn); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var ctx = ServerApplicationContext.Current; bool fContextCreated = false; SearchResultCollection aUser = null; //SearchResult user; try { bool fReturn = fReturn = false; if (null == ctx) { fContextCreated = true; ctx = ServerApplicationContext.CreateContext(); } //string permissionId = string.Format("{0}:{1}{2}", "LightSwitchApplication", "ActiveDirectoryUser", "CanRead"); //fReturn = ctx.Application.User.HasPermission(permissionId); //if (!fReturn) //{ // return StatusCode(HttpStatusCode.Unauthorized); //} _ldapSearch.Filter = string.Format("(&(objectClass=user)(|(cn={0})(name={0})(sn={0})(sAMAccountName={0})(displayName={0})(mail={0})))", key); aUser = _ldapSearch.FindAll(); var _list = new List <Models.ActiveDirectoryUser>(); foreach (SearchResult user in aUser) { var entity = ExtractActiveDirectoryUserProperties(user); _list.Add(entity); } return(Ok <IEnumerable <Models.ActiveDirectoryUser> >(_list)); } catch (Exception ex) { Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", ex.Source, ex.Message, ex.StackTrace)); return(BadRequest(ex.Message)); } finally { if (fContextCreated && (null != ctx)) { ctx.Dispose(); } if (null == aUser) { aUser.Dispose(); } } }
public LightSwitchApiControllerbase() { _context = ServerApplicationContext.Current; if (_context == null) { _context = ServerApplicationContext.CreateContext(); } }
public void ProcessRequest(HttpContext context) { using (var serverContext = ServerApplicationContext.CreateContext()) { context.Response.ContentType = "text/plain"; context.Response.Write(serverContext.Application.User.Email); } }
public ExpandedUserDTO GetUser(string id) { try { // Make sure we have a ServerApplicationContext, if unable to, throw an exception if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC2"); } using (ServerApplicationContext.Current) { // Go get our LightSwitch user data, LightSwitch deals only with LowerCase usernames var result = ServerApplicationContext.Current.DataWorkspace.SecurityData .UserRegistrations .Where(u => String.Equals(u.UserName, id, StringComparison.CurrentCultureIgnoreCase)) .Select(u => new ExpandedUserDTO { UserName = u.UserName, FullName = u.FullName }).Execute().First(); // Get our ASP Membership data var member = Membership.GetUser(id); // If we could not find the user, throw an exception if (member == null) { throw new Exception("Could not find the User"); } // Stuff the asp data into our DTO result.Email = member.Email; result.CreationDate = member.CreationDate; result.IsOnline = member.IsOnline; result.LastLoginDate = member.LastLoginDate; result.LastPasswordChangeDate = member.LastPasswordChangedDate; return(result); } } catch (Exception e) { // Again... if anything fails we return an error response for the client to deal with var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, e.Message); throw new HttpResponseException(response); } }
public IEnumerable <ExpandedUserDTO> GetUsers() { try { // Make sure we have a ServerApplicationContext, if unable to, throw an exception if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC1"); } using (ServerApplicationContext.Current) { // Go get the LightSwitch profile data for all users var lsUsers = ServerApplicationContext.Current.DataWorkspace.SecurityData .UserRegistrations .Select(u => new { u.UserName, u.FullName }) .Execute(); // Get all our other data for all users var membershipUsers = Membership.GetAllUsers().Cast <MembershipUser>(); // Now lets join the two sets, note that LightSwitch deals only with LowerCase UserNames var result = from member in membershipUsers from lsUser in lsUsers where String.Equals(member.UserName, lsUser.UserName, StringComparison.CurrentCultureIgnoreCase) select new ExpandedUserDTO { UserName = member.UserName, FullName = lsUser.FullName, Email = member.Email, IsOnline = member.IsOnline, IsLockedOut = member.IsLockedOut, LastLoginDate = member.LastLoginDate, LastPasswordChangeDate = member.LastPasswordChangedDate, CreationDate = member.CreationDate }; return(result); } } catch (Exception e) { // If there was some failure return an error response, client will deal with it var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, e.Message); throw new HttpResponseException(response); } }
//GET api/<controller/<action>/id public List <int> GetAnswersByUser(int id) { if (id < 1) { return(null); } using (var context = ServerApplicationContext.CreateContext()) { var user = "******"; //bei Sharepoint dann den Sharepoint-User mitgeben als Parameter?! var answers = context.DataWorkspace.ApplicationData.QuestionAnswers.GetQuery().Execute().Where(a => a.SurveyQuestion.Survey.Id == id && a.Person == user).ToList(); var answerIds = (from a in answers select a.Id).ToList(); return(answerIds); } }
// ======================================================================================================= // Helper - Add a permission to a role // Data: LightSwitch PermissionId and RoleName // Returns: bool // ======================================================================================================= private static bool AddLightSwitchPermissionToRole(string permissionId, string roleName) { try { if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC10"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; // Find our role... exception if not found var role = dbContext.SecurityData.Roles_Single(roleName); // Find our permission... exception if not found var permission = dbContext.SecurityData.Permissions_Single(permissionId); // Does the association already exist, if so, return if (dbContext.SecurityData.RolePermissions_SingleOrDefault(roleName, permissionId) != null) { return(true); } // It does not... add a new association entity var newPermissionAssoc = dbContext.SecurityData.RolePermissions.AddNew(); // Assign the role newPermissionAssoc.Role = role; // Assign the permission and save newPermissionAssoc.Permission = permission; dbContext.SecurityData.SaveChanges(); // We got this far, so success...return true return(true); } } catch (Exception e) { throw new Exception(e.Message, e.InnerException); } }
public void DeleteUser([FromBody] UserDTO jsonData) { try { jsonData.UserName = jsonData.UserName.ToLower(); // Make sure we have a ServerApplicationContext, if unable to, throw an exception if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC6"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; // Remove the user from all associated roles var userRoles = Roles.GetRolesForUser(jsonData.UserName); if (userRoles.Any()) { Roles.RemoveUserFromRoles(jsonData.UserName, userRoles); } // Now delete the User, LightSwitch will also take care of the ASP.NET tables var lsUser = dbContext.SecurityData.UserRegistrations_SingleOrDefault(jsonData.UserName); // Could not find the user... so return... no reason to let the client know if (lsUser == null) { return; } lsUser.Delete(); dbContext.SecurityData.SaveChanges(); } } catch (Exception e) { var response = Request.CreateErrorResponse(HttpStatusCode.Conflict, e.Message); throw new HttpResponseException(response); } }
// ======================================================================================================= // Helper - Get the permissions for an individual user // Data: UserName // Returns: List of PermissionDTOs // Comment: This could probably be done a bit better with some extra Linq // ======================================================================================================= private static IEnumerable <PermissionDTO> GetLightSwitchUserPermissions(string userName) { try { if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC8"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; // List to hold our permissions var permissionList = new List <PermissionDTO>(); // All the roles assigned to the user var assignedRoles = dbContext.SecurityData.RoleAssignments .Where(ra => ra.UserName == userName) .Select(r => r.Role) .Execute(); // Get all the Role Assignments var roleAssignments = assignedRoles.Select(r => r.RolePermissions); // Loop over our Assignments foreach (var r in roleAssignments) { permissionList.AddRange(r.Select(p => new PermissionDTO { Id = p.Permission.Id, Name = p.Permission.Name })); } return(permissionList); } } catch (Exception e) { throw new Exception(e.Message, e.InnerException); } }
public async Task <IHttpActionResult> Patch([FromODataUri] string key, Delta <Models.ActiveDirectoryUser> delta) { string fn = string.Format("{0}:{1}.{2}", this.GetType().Namespace, this.ControllerContext.ControllerDescriptor.ControllerName, this.ControllerContext.Request.GetActionDescriptor().ActionName); Debug.WriteLine(fn); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var ctx = ServerApplicationContext.Current; bool fContextCreated = false; try { bool fReturn = fReturn = false; if (null == ctx) { fContextCreated = true; ctx = ServerApplicationContext.CreateContext(); } string permissionId = string.Format("{0}:{1}{2}", "LightSwitchApplication", "ActiveDirectoryUser", "CanUpdate"); fReturn = ctx.Application.User.HasPermission(permissionId); if (!fReturn) { return(StatusCode(HttpStatusCode.Unauthorized)); } return(StatusCode(HttpStatusCode.NotImplemented)); } catch (Exception ex) { Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", ex.Source, ex.Message, ex.StackTrace)); throw; } finally { if (fContextCreated && (null != ctx)) { ctx.Dispose(); } } }
// GET api/<controller>/5 public List <List <string> > Get(int id) { if (id == 0 || id < 1) { return(null); } using (var context = ServerApplicationContext.CreateContext()) { var allAnswersForSurvey = context.DataWorkspace.ApplicationData.QuestionAnswers.GetQuery().Execute().Where(s => s.SurveyQuestion.Survey.Id == id).ToList(); var distinctPersons = (from p in allAnswersForSurvey select p.Person).Distinct().ToList(); var votingList = new List <List <string> >(); //header var header = new List <string>(); header.Add("Nr."); header.Add("Person"); header.AddRange(context.DataWorkspace.ApplicationData.SurveyQuestions.GetQuery().Execute().Where(q => q.Survey.Id == id).OrderBy(q => q.Id).Select(q => q.Question.ToString()).ToList()); votingList.Add(header); //votings per Person var rowCounter = 1; foreach (var person in distinctPersons) { var list = new List <string>(); //new TR (HTML) list.Add(rowCounter.ToString()); list.Add(person); var answers = allAnswersForSurvey.Where(a => a.Person == person).OrderBy(a => a.Id).Select(a => a.Answer).ToList(); foreach (var answer in answers) { list.Add(GetAnswer(answer)); } votingList.Add(list); rowCounter++; } return(votingList); } }
public void ProcessRequest(HttpContext context) { using (var serverContext = ServerApplicationContext.CreateContext()) { var from = context.Request.Form["from"]; var subject = context.Request.Form["subject"]; using (var workspace = serverContext.Application.CreateDataWorkspace()) { var item = workspace.ApplicationData.WorkTimeSet.AddNew(); item.UserId = from; var t = subject.Split('-'); if (t.Length < 2) { return; } item.StartTime = t[0]; item.EndTime = t[1]; workspace.ApplicationData.SaveChanges(); } } }
public object Get(int id) { using (ServerApplicationContext context = ServerApplicationContext.CreateContext()) { var query = context.DataWorkspace.ApplicationData.Orders .Where(o => o.Customer.Id == id) .GroupBy(o => o.CreationDate.Year) .Select(g => new { Label = g.Key, Value = g.Sum(o => o.OrderTotal) }) .OrderBy(g => g.Label); return(query.Execute().Select( g => new { Label = string.Format("'{0}", (g.Label - 2000)), Value = g.Value } ).ToArray()); } }
public ActiveDirectoryUsersController() { string fn = string.Format("{0}:{1}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name); Debug.WriteLine(fn); var ctx = ServerApplicationContext.Current; bool fContextCreated = false; try { bool fReturn = fReturn = false; if (null == ctx) { fContextCreated = true; ctx = ServerApplicationContext.CreateContext(); } var Now = DateTimeOffset.Now; if (60 >= (Now - _modified).TotalMinutes) { return; } lock (this) { _ldapConnectionPath = ConfigurationManager.AppSettings["ldapConnection.Path"]; //Debug.WriteLine(String.Format("_ldapConnectionPath: '{0}'", _ldapConnectionPath)); _ldapConnectionAuthenticationType = ConfigurationManager.AppSettings["ldapConnection.AuthenticationType"]; //Debug.WriteLine(String.Format("_ldapConnectionAuthenticationType: '{0}'", _ldapConnectionAuthenticationType)); _ldapConnectionUsername = ConfigurationManager.AppSettings["ldapConnection.Username"]; //Debug.WriteLine(String.Format("_ldapConnectionUsername: '******'", _ldapConnectionUsername)); _ldapConnectionPassword = ConfigurationManager.AppSettings["ldapConnection.Password"]; //Debug.WriteLine(String.Format("_ldapConnectionPassword: '******'", _ldapConnectionPassword)); _ldapConnection = new DirectoryEntry(); _ldapConnection.Path = _ldapConnectionPath; _ldapConnection.AuthenticationType = EnumUtil.Parse <AuthenticationTypes>(_ldapConnectionAuthenticationType); _ldapConnection.Username = _ldapConnectionUsername; _ldapConnection.Password = _ldapConnectionPassword; _ldapSearch = new DirectorySearcher(_ldapConnection); _ldapSearch.PropertiesToLoad.Add("*"); _ldapSearch.SizeLimit = 45; _ldapSearch.Sort = new SortOption("cn", SortDirection.Ascending); } _modified = Now; } catch (Exception ex) { Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", ex.Source, ex.Message, ex.StackTrace)); return; } finally { if (fContextCreated && (null != ctx)) { ctx.Dispose(); } } }
public UserDTO UpdateUser([FromBody] UserDTO jsonData) { try { var result = new UserDTO(); jsonData.UserName = jsonData.UserName.ToLower(); jsonData.Email = jsonData.Email.ToLower(); // Get our user var user = Membership.GetUser(jsonData.UserName); // If user was not found, throw an exception so the client can be notified if (user == null) { throw new Exception("User was not found"); } // First lets check if the account needs to be unlocked if (user.IsLockedOut && !jsonData.IsLockedOut) { user.UnlockUser(); } user.Email = jsonData.Email; // Update ASP.NET Membership Membership.UpdateUser(user); // If we have a fullname, go update the LightSwitch profile if (jsonData.FullName != "") { // Make sure we have a ServerApplicationContext, if unable to, throw an exception if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC5"); } using (ServerApplicationContext.Current) { // Find our LightSwitch user var lsUser = ServerApplicationContext.Current.DataWorkspace.SecurityData.UserRegistrations_Single(jsonData.UserName); // Was a password sent across? if (!string.IsNullOrEmpty(jsonData.Password)) { // Check the password for validity if (jsonData.Password.ToLower().Contains(jsonData.UserName) || !ServerApplicationContext.Current.DataWorkspace.SecurityData.IsValidPassword(jsonData.Password)) { throw new Exception("Not a valid password"); } // Change the password lsUser.Password = jsonData.Password; } // Update the profile property and save lsUser.FullName = jsonData.FullName; // Save the data ServerApplicationContext.Current.DataWorkspace.SecurityData.SaveChanges(); } } // If we got here, all was successful, so stuff our return DTO for client validation result.UserName = user.UserName; result.FullName = jsonData.FullName; result.Email = user.Email; result.Password = ""; result.IsLockedOut = user.IsLockedOut; result.IsOnline = user.IsOnline; return(result); } catch (Exception e) { var response = Request.CreateErrorResponse(HttpStatusCode.Conflict, e.Message); throw new HttpResponseException(response); } }
public UserDTO CreateUser([FromBody] UserDTO jsonData) { try { var result = new UserDTO(); // If no UserName then throw an exception so our catch can handle it if (jsonData.UserName == "") { throw new Exception("No UserName"); } // Keep our UserName as LowerCase jsonData.UserName = jsonData.UserName.ToLower(); // If no Password then throw an exception so our catch can handle it if (jsonData.Password == "") { throw new Exception("No Password"); } // Make sure we have a ServerApplicationContext, if unable to, throw an exception if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC4"); } using (ServerApplicationContext.Current) { // Check the password for validity if (jsonData.Password.ToLower().Contains(jsonData.UserName) || !ServerApplicationContext.Current.DataWorkspace.SecurityData.IsValidPassword(jsonData.Password)) { throw new Exception("Not a valid password"); } // First order of business is to create our LightSwitch user var newUser = ServerApplicationContext.Current.DataWorkspace.SecurityData.UserRegistrations.AddNew(); newUser.FullName = jsonData.FullName; newUser.UserName = jsonData.UserName; newUser.Password = jsonData.Password; ServerApplicationContext.Current.DataWorkspace.SecurityData.SaveChanges(); } // Successful creation of the user if we got this far // Go get our asp user to stuff data var user = Membership.GetUser(jsonData.UserName); if (user != null) { user.Email = jsonData.Email.ToLower(); Membership.UpdateUser(user); // So we're good to go... stuff our return DTO for validation on client side result.UserName = user.UserName; result.FullName = jsonData.FullName; result.Email = user.Email.ToLower(); result.IsLockedOut = user.IsLockedOut; } // Do not send back the password, so blank it out result.Password = ""; return(result); } catch (Exception e) { var response = Request.CreateErrorResponse(HttpStatusCode.Conflict, e.Message); throw new HttpResponseException(response); } }
public string GetExpandedUser(string id) { try { // LightSwitch calls deals with LowerCase UserNames id = id.ToLower(); // Make sure we have a ServerApplicationContext, if unable to, throw an exception if (ServerApplicationContext.Current == null) { ServerApplicationContext.CreateContext(); } if (ServerApplicationContext.Current == null) { throw new Exception("Could not create a ServerApplicationContext... SAC3"); } using (ServerApplicationContext.Current) { var dbContext = ServerApplicationContext.Current.DataWorkspace; // Get Our user data from LightSwitch, note LightSwitch only deals with LowerCase usernames var result = dbContext.SecurityData .UserRegistrations .Where(u => String.Equals(u.UserName, id, StringComparison.CurrentCultureIgnoreCase)) .Select(u => new ExpandedUserDTO { UserName = u.UserName, FullName = u.FullName }).Execute().First(); // Get the expanded data from the membership provider var member = Membership.GetUser(id); // Populate our DTO if (member != null) { result.Email = member.Email; result.CreationDate = member.CreationDate; result.LastLoginDate = member.LastLoginDate; result.LastPasswordChangeDate = member.LastPasswordChangedDate; result.IsOnline = member.IsOnline; } // Get all the roles assigned to this user var roles = dbContext.SecurityData.RoleAssignments.Where(r => r.UserName.ToLower() == id).Select(r => r.Role).Execute(); // Lets go thru each role object and build a composite for transfer var expandedRoles = roles.Select(r => new UserRolesDTO { RoleName = r.Name, Permissions = r.RolePermissions.Select(p => new PermissionDTO { Name = p.Permission.Name, Id = p.PermissionId }) }).ToList(); // Add the expanded roles to the expanded users result.Roles = expandedRoles; return(Newtonsoft.Json.JsonConvert.SerializeObject(result)); } } catch { var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found"); throw new HttpResponseException(response); } }
public void Import(string filename) { using (var helper = new SpreadsheetHelper(filename)) { if (!helper.MoveWorksheet(sheetName)) { throw new ApplicationException("不正なテンプレートです。" + sheetName + "のシートがありません"); } var worksheet = helper.CurrentSheet; using (var serverContext = ServerApplicationContext.CreateContext()) { var date = (DateTime)helper.GetCellValue(startDateCell, CellValues.Date); var userId = helper.GetCellValue(emailAddressCell) as string; if (string.IsNullOrEmpty(userId)) { throw new ApplicationException("ユーザが指定されていません"); } var sb = new StringBuilder(); for (int rowIdx = startPos; rowIdx < startPos + 31; rowIdx++) { using (var workspace = serverContext.Application.CreateDataWorkspace()) { try { string sickHoliday = helper.GetCellValue(4, rowIdx) as string; var startTimeObject = helper.GetCellValue(9, rowIdx); string startTime = startTimeObject is DateTime ? ((DateTime)startTimeObject).ToString("HH:mm") : startTimeObject as string; var endTimeObject = helper.GetCellValue(11, rowIdx); string endTime = endTimeObject is DateTime ? ((DateTime)endTimeObject).ToString("HH:mm") : endTimeObject as string; var item = workspace.ApplicationData.WorkTimeSet.AddNew(); string remark = helper.GetCellValue(16, rowIdx) as string; if (string.IsNullOrEmpty(startTime) && string.IsNullOrEmpty(endTime) && string.IsNullOrEmpty(remark) && string.IsNullOrEmpty(sickHoliday)) { continue; } item.UserId = userId; item.SickHolidy = sickHoliday; item.WorkDate = date.AddDays(rowIdx - startPos); item.StartTime = startTime; item.EndTime = endTime; item.Remark = remark; workspace.ApplicationData.SaveChanges(); } catch (Microsoft.LightSwitch.ValidationException vex) { foreach (var error in vex.ValidationResults) { sb.AppendLine(date.AddDays(rowIdx - startPos).ToString("d") + ":" + error.Message); } } } } if (sb.Length > 0) { throw new ApplicationException(sb.ToString()); } } } }