public DhtEngine(DhtListener listener) { if (listener == null) throw new ArgumentNullException("listener"); _messageLoop = new MessageLoop(this, listener); _timeout = TimeSpan.FromSeconds(15); // 15 second message timeout by default _tokenManager = new TokenManager(); }
public TransferLayer(ILayer lowerLayer, int blockSize) : base(lowerLayer) { _tokenManager = new TokenManager(); _incomplete = new Dictionary<string, Message>(); if (blockSize > 0) { _szx = BlockOption.EncodeSzx(blockSize); } }
/// <summary> /// Forces this component to add its plugin members /// </summary> public void Update() { _tokenManager = new TokenManager(); _tokenManager.Directories = _directories; _tokenManager.UpdateStore(); if (_mainMenu != null) { ToolStripItem[] items = _mainMenu.Items.Find(MessageStrings.Plugins, true); ToolStripMenuItem mi = null; if (items.Length > 0) mi = items[0] as ToolStripMenuItem; if (mi == null) mi = _mainMenu.Items.Add(MessageStrings.Plugins) as ToolStripMenuItem; IMapPluginArgs args = new GeoPluginArgs(_map, _legend, _mainMenu, _toolStrip, _progressHandler, _geoPlugins, _toolStripContainer, _panelManager); foreach (PluginToken token in _tokenManager.Tokens) { bool isGeoPlugin = false; Type[] interfaces = token.PluginType.GetInterfaces(); foreach (Type t in interfaces) { if (t == typeof(IMapPlugin)) { isGeoPlugin = true; break; } } ToolStripMenuItem tsmi = new ToolStripMenuItem(token.Name); tsmi.Click += new EventHandler(tsmi_Click); tsmi.Image = Images.InactivePlugin.ToBitmap(); tsmi.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; tsmi.Tag = token; mi.DropDownItems.Add(tsmi); if (token.Enabled == true && isGeoPlugin) { IMapPlugin gp = token.CreateInstance<IMapPlugin>(); if(gp != null) { gp.Initialize(args); _geoPlugins.Add(gp); mi.Checked = true; } } } } }
static void Main(string[] args) { TokenManager tokenManager = new TokenManager(); tokenManager.AddToken("yukan", "YukanZhang"); DateTime dt = DateTime.Now; tokenManager.VerifyUserTokenValid("yukan", out dt); tokenManager.AddToken("yang", "YangGe"); tokenManager.VerifyUserTokenValid("yukan", out dt); // Test Constructor TokenManager tm2 = new TokenManager(tokenManager); tm2.VerifyUserTokenValid("yang", out dt); tm2.VerifyUserTokenValid("yukan", out dt); Thread.Sleep(20); tokenManager.TokenManagerExit(); tm2.TokenManagerExit(); }
public void CheckTokenGenerator() { TokenManager m = new TokenManager(); m.Timeout = TimeSpan.FromMilliseconds(75); // 1 second timeout for testing purposes Node n = new Node(NodeId.Create(),new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25)); Node n2 = new Node(NodeId.Create(),new IPEndPoint(IPAddress.Parse("127.0.0.2"), 25)); BEncodedString s = m.GenerateToken(n); BEncodedString s2 = m.GenerateToken(n); Assert.AreEqual(s, s2, "#1"); Assert.IsTrue(m.VerifyToken(n, s),"#2"); Assert.IsFalse(m.VerifyToken(n2, s),"#3"); System.Threading.Thread.Sleep(100); Assert.IsTrue(m.VerifyToken(n, s), "#4"); System.Threading.Thread.Sleep(100); Assert.IsFalse(m.VerifyToken(n, s), "#5"); }
public IHttpActionResult PostUserImage(int pid, int picimg, string token) { using (ShoppingELFEntities context = new ShoppingELFEntities()) { SellerTable seller = new SellerTable(); string username = TokenManager.ValidateToken(token); seller = context.SellerTable.FirstOrDefault(m => m.email == username); if (seller != null && seller.Role == "Seller") { Dictionary <string, object> dict = new Dictionary <string, object>(); try { var httpRequest = HttpContext.Current.Request; foreach (string file in httpRequest.Files) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created); var postedFile = httpRequest.Files[file]; if (postedFile != null && postedFile.ContentLength > 0) { IList <string> AllowedFileExtensions = new List <string> { ".jpg", ".gif", ".png", ".jpeg" }; var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.')); var extension = ext.ToLower(); if (!AllowedFileExtensions.Contains(extension)) { var message = string.Format("Please Upload image of type .jpg,.gif,.png."); dict.Add("error", message); return(BadRequest("Please Upload image of type .jpg,.gif,.png.,.jpeg")); } else { var filePath = HttpContext.Current.Server.MapPath("~/ProductImage/" + postedFile.FileName); postedFile.SaveAs(filePath); string imagepath = "/ProductImage/" + postedFile.FileName; int image = new ProductRepository().ImageUpload(pid, picimg, imagepath); if (image == 2) { return(NotFound()); } if (image == 0) { return(BadRequest("Your image might be greater than the 1mb ,please upload a valid image")); } } } var message1 = "/ProductImage/" + postedFile.FileName; return(Ok(message1)); } var res = string.Format("Please Upload a image."); dict.Add("error", res); return(NotFound()); } catch (Exception ex) { var res = string.Format("please check your internet connection"); dict.Add("error", res); return(NotFound()); } } else { return(Unauthorized()); } } }
/* * Description:Adds an online user to OnlineUser table * Params:Login message with the credentials to be validated * Output:Succes, Bad Password, Not registered message */ public OnlineUser AddOnlineUserRecord(LogInUserMsg userInfo) { OnlineUser onlineUser = new OnlineUser(); bool verifiedCredentials = Connector.checkUserPass(userInfo.username, userInfo.passwordHash); if (_context.athletes.Any(a => a.username == userInfo.username)) { string id_athlete = _context.athletes.Where(a => a.username == userInfo.username).Select(u => u.id).SingleOrDefault(); if (verifiedCredentials) { if (_context.onlineusers.Any(ou => ou.id_athlete_fk == id_athlete)) { var entity = _context.onlineusers.FirstOrDefault(ou => ou.id_athlete_fk == id_athlete); return(entity); } else { onlineUser.id_athlete_fk = id_athlete; onlineUser.token = TokenManager.generateToken(12); _context.onlineusers.Add(onlineUser); _context.SaveChanges(); return(onlineUser); } } else { onlineUser.token = "BadPassword"; return(onlineUser); } } else if (_context.organizers.Any(o => o.username == userInfo.username)) { string id_organizer = _context.organizers.Where(o => o.username == userInfo.username).Select(u => u.id).SingleOrDefault(); if (verifiedCredentials) { if (_context.onlineusers.Any(ou => ou.id_organizer_fk == id_organizer)) { var entity = _context.onlineusers.FirstOrDefault(ou => ou.id_organizer_fk == id_organizer); return(entity); } else { onlineUser.id_organizer_fk = id_organizer; onlineUser.token = TokenManager.generateToken(12); _context.onlineusers.Add(onlineUser); _context.SaveChanges(); return(onlineUser); } } else { onlineUser.token = "BadPassword"; return(onlineUser); } } else { Console.WriteLine("NotRegistered"); onlineUser.token = "NotRegistered"; return(onlineUser); } }
public async Task <ResponseObject <bool> > Put(RequestPut <TBMPackageEditModel> requestObject) { var user = TokenManager.GetCurentUserbyToken(Request.Headers); return(await _service.PutAsync(requestObject, user)); }
public SecurityService(ISecurityRepository repository, IOptions <AppSettings> appSettings) { _repository = repository; _tokenManager = new TokenManager(); _appSettings = appSettings.Value; }
public AccountController(UsersManager usersManager, TokenManager tokenManager, ActiveDirectoryManager activeDirectoryManager) { this._usersManager = usersManager; this._tokenManager = tokenManager; this._activeDirectoryManager = activeDirectoryManager; }
public Parser(string name, Tokenizer tok, Stream input) { _name = name; _tokens = new TokenManager(tok, input); }
public string Save(string token) { token = TokenManager.readToken(HttpContext.Current.Request); string message = ""; var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { string agentObject = ""; agents agentObj = null; IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "itemObject") { agentObject = c.Value.Replace("\\", string.Empty); agentObject = agentObject.Trim('"'); agentObj = JsonConvert.DeserializeObject <agents>(agentObject, new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" }); break; } } try { agents agent; using (incposdbEntities entity = new incposdbEntities()) { var agentEntity = entity.Set <agents>(); if (agentObj.agentId == 0) { ProgramInfo programInfo = new ProgramInfo(); int agentMaxCount = 0; if (agentObj.type == "c") { agentMaxCount = programInfo.getCustomerCount(); } else if (agentObj.type == "v") { agentMaxCount = programInfo.getVendorCount(); } int agentCount = entity.agents.Where(x => x.type == agentObj.type).Count(); if (agentCount >= agentMaxCount && agentMaxCount != -1) { message = "-1"; return(TokenManager.GenerateToken(message)); } else { agentObj.createDate = DateTime.Now; agentObj.updateDate = DateTime.Now; agentObj.updateUserId = agentObj.createUserId; agentObj.balanceType = 0; agent = agentEntity.Add(agentObj); } } else { agent = entity.agents.Where(p => p.agentId == agentObj.agentId).First(); agent.accType = agentObj.accType; agent.address = agentObj.address; agent.code = agentObj.code; agent.company = agentObj.company; agent.email = agentObj.email; agent.image = agentObj.image; agent.mobile = agentObj.mobile; agent.name = agentObj.name; agent.notes = agentObj.notes; agent.phone = agentObj.phone; agent.type = agentObj.type; agent.maxDeserve = agentObj.maxDeserve; agent.fax = agentObj.fax; agent.updateDate = DateTime.Now;// server current date agent.updateUserId = agentObj.updateUserId; agent.isActive = agentObj.isActive; agent.balance = agentObj.balance; agent.balanceType = agentObj.balanceType; agent.isLimited = agentObj.isLimited; agent.payType = agentObj.payType; } entity.SaveChanges(); message = agent.agentId.ToString(); } return(TokenManager.GenerateToken(message)); } catch { message = "0"; return(TokenManager.GenerateToken(message)); } } }
/// <summary> /// Begins authorization process and redirects client to the LinkedIn authorization page. /// </summary> private void BeginAuthorization() { try { // Store token manager in the session TokenManager = new TokenManager((string)Parameters["ApiKey"], (string)Parameters["ApiSecret"]); LinkedInHelper.BeginAuthorization(TokenManager, URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "tokenManagerKey", TokenManagerStoreKey)); } catch (LinkedInApiUnauthorizedException) { // The keys in LinkedIn application are not valid ShowError(GetString("sm.linkedin.account.msg.unauthorized")); } catch (Exception ex) { LogAndShowError("LinkedInCompanyAccessToken", "AUTH_BEGIN", ex); } }
public async Task<bool> Remove( HubScriptItem HSI, string AccessToken = null ) { TaskCompletionSource<bool> TCS = new TaskCompletionSource<bool>(); TokenManager TokMgr = new TokenManager(); AESManager AESMgr = new AESManager(); if ( AccessToken == null ) AccessToken = ( string ) TokMgr.GetAuthById( HSI.Id )?.Value; RCache.POST( Shared.ShRequest.Server , Shared.ShRequest.ScriptRemove( AccessToken, HSI.Id ) , ( e2, QId ) => { try { JsonStatus.Parse( e2.ResponseString ); TCS.TrySetResult( true ); Worker.UIInvoke( () => SearchSet.Remove( HSI ) ); TokMgr.UnassignId( HSI.Id ); AESMgr.UnassignId( HSI.Id ); } catch ( Exception ex ) { HSI.ErrorMessage = ex.Message; TCS.TrySetResult( false ); } } , ( a, b, ex ) => { HSI.ErrorMessage = ex.Message; TCS.TrySetResult( false ); } , false ); return await TCS.Task; }
public async void Search( string Query, IEnumerable<string> AccessTokens = null ) { if ( AccessTokens == null ) AccessTokens = new TokenManager().AuthList.Remap( x => ( string ) x.Value ); Searching = true; SHSearchLoader SHLoader = new SHSearchLoader( Query, AccessTokens ); SearchSet.ConnectLoader( SHLoader ); SearchSet.UpdateSource( await SHLoader.NextPage() ); Searching = false; }
void Awake() { tm = TokenManager.Instance; }
public void ConfigureServices(IServiceCollection services) { #region DbContext services.AddDbContext <MEMOContext>(o => o.UseSqlServer(Configuration.GetConnectionString("LocalConnection"))); #endregion #region Identity services.AddIdentity <User, IdentityRole <Guid> >(o => { o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonAlphanumeric = false; o.Password.RequiredLength = 6; }) .AddEntityFrameworkStores <MEMOContext>() .AddDefaultTokenProviders(); string secret = Configuration.GetValue <string>("AppSettings:Secret"); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateLifetime = true, ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)) #if (DEBUG) , ClockSkew = TimeSpan.Zero #endif }; }); #endregion #region ProblemDetails services.AddProblemDetails(options => { options.IncludeExceptionDetails = ctx => false; options.Map <TranslationException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <EntityInsertException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <EntityUpdateException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <EntityDeleteException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <AuthorizationException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <EntityNotFoundException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <LoginFailedException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); options.Map <RegistrationFailedException>(ex => new ProblemDetails { Title = ex.Name, Detail = ex.Message, Status = StatusCodes.Status404NotFound }); }); #endregion #region ModelServices services.AddTransient <IAuthenticationService, AuthenticationService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IDictionaryService, DictionaryService>(); services.AddTransient <ITranslationService, TranslationService>(); services.AddTransient <ILanguageService, LanguageService>(); services.AddTransient <IAttributeService, AttributeService>(); #endregion #region Singletons services.AddSingleton(AutoMapperConfig.Configure()); var tokenManager = new TokenManager(secret); services.AddSingleton(tokenManager); services.AddSingleton(new AuthorizationManager(tokenManager)); #endregion #region MVC services.AddControllers(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore); #endregion }
/// <summary> /// Forces this component to add its plugin members /// </summary> public void Update() { _tokenManager = new TokenManager(); _tokenManager.Directories = _directories; _tokenManager.UpdateStore(); if (_mainMenu != null) { //ToolStripItem[] items = _mainMenu.Items.Find("Extensions", true); //ToolStripMenuItem mi = null; //if (items.Length > 0) mi = items[0] as ToolStripMenuItem; ToolStripMenuItem mi = _mainMenu.Items.Add(MessageStrings.Extensions) as ToolStripMenuItem; ToolStripMenuItem pluginMenu = null; if (mi != null) { if (mi.DropDownItems.ContainsKey(MessageStrings.Plugins)) { pluginMenu = mi.DropDownItems[MessageStrings.Plugins] as ToolStripMenuItem; } else { pluginMenu = mi.DropDownItems.Add(MessageStrings.Plugins) as ToolStripMenuItem; if (pluginMenu != null) { pluginMenu.Image = Images.PluginSubmenu.ToBitmap(); pluginMenu.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; } } } //IMapPluginArgs args = new GeoPluginArgs(_map, _legend, _mainMenu, _toolStrip, _progressHandler, _geoPlugins, _toolStripContainer); foreach (PluginToken token in _tokenManager.Tokens) { if (token.CanBecome(typeof(IMapPlugin))) { ToolStripMenuItem tsmi = new ToolStripMenuItem(token.Name); tsmi.Click += tsmi_Click; tsmi.Image = Images.InactivePlugin.ToBitmap(); tsmi.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; tsmi.Tag = token; if (pluginMenu != null) pluginMenu.DropDownItems.Add(tsmi); // Plugins don't activate right away. } else { // If it isn't a plug-in, it should be a provider, which should load. ActivateToken(token); } } } }
public LogsController(ILogger <LogsController> logger, TokenManager tokenManager, ISysLogService logsService) { _logger = logger; _tokenManager = tokenManager; _logsService = logsService; }
public async Task <ResponseObject <TBMMaterialFileAddModel, bool> > Post(RequestObject <TBMMaterialFileAddModel> requestObject) { var user = TokenManager.GetCurentUserbyToken(Request.Headers); return(await _service.PostAsync(requestObject, user)); }
public string Delete(string token) { token = TokenManager.readToken(HttpContext.Current.Request); string message = ""; var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { int agentId = 0; int userId = 0; Boolean final = false; IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "itemId") { agentId = int.Parse(c.Value); } else if (c.Type == "userId") { userId = int.Parse(c.Value); } else if (c.Type == "final") { final = bool.Parse(c.Value); } } if (!final) { try { using (incposdbEntities entity = new incposdbEntities()) { var tmpAgent = entity.agents.Where(p => p.agentId == agentId).First(); tmpAgent.isActive = 0; tmpAgent.updateDate = DateTime.Now; tmpAgent.updateUserId = userId; message = entity.SaveChanges().ToString(); } return(TokenManager.GenerateToken(message)); } catch { return(TokenManager.GenerateToken("0")); } } else { try { using (incposdbEntities entity = new incposdbEntities()) { var tmpAgent = entity.agents.Where(p => p.agentId == agentId).First(); entity.agents.Remove(tmpAgent); message = entity.SaveChanges().ToString(); } return(TokenManager.GenerateToken(message)); } catch { return(TokenManager.GenerateToken("0")); } } } }
/// <summary> /// Token管理 /// </summary> /// <param name="tokenManager"></param> public TokenController(TokenManager tokenManager) { this.tokenManager = tokenManager; }
public string GetItemToDestroy(string token) { token = TokenManager.readToken(HttpContext.Current.Request); var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { int branchId = 0; IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "itemId") { branchId = int.Parse(c.Value); } } using (incposdbEntities entity = new incposdbEntities()) { var List = (from c in entity.inventoryItemLocation.Where(c => c.amountDestroyed > 0 && c.isDestroyed == false && c.Inventory.branchId == branchId && c.Inventory.inventoryType == "n" && c.Inventory.isActive == 1) join l in entity.itemsLocations on c.itemLocationId equals l.itemsLocId join u in entity.itemsUnits on l.itemUnitId equals u.itemUnitId join un in entity.units on u.unitId equals un.unitId join lo in entity.locations on l.locationId equals lo.locationId select new InventoryItemLocationModel() { id = c.id, isDestroyed = c.isDestroyed, amount = c.amount, amountDestroyed = c.amountDestroyed, quantity = c.realAmount, itemLocationId = c.itemLocationId, inventoryId = c.inventoryId, isActive = c.isActive, notes = c.notes, createDate = c.createDate, updateDate = c.updateDate, createUserId = c.createUserId, updateUserId = c.updateUserId, canDelete = true, itemId = u.items.itemId, itemName = u.items.name, unitId = un.unitId, itemUnitId = u.itemUnitId, unitName = un.name, section = lo.sections.name, location = lo.x + lo.y + lo.z, itemType = u.items.type, inventoryDate = c.Inventory.createDate, inventoryNum = c.Inventory.num, avgPurchasePrice = u.items.avgPurchasePrice, }) .ToList().OrderBy(x => x.location).ToList(); return(TokenManager.GenerateToken(List)); } } }
public AccountController(UsersManager usersManager, TokenManager tokenManager) { this._usersManager = usersManager; this._tokenManager = tokenManager; }
public async Task <ResponseObject <bool> > Copy(TBMMaterialFileCopyModel requestObject) { var user = TokenManager.GetCurentUserbyToken(Request.Headers); return(await _service.Copy(requestObject, user)); }
public async Task <ResponseObject <TSMRolePermissionsAddModel, bool> > Post(RequestObject <TSMRolePermissionsAddModel> requestObject) { var userId = TokenManager.GetUserIDbyToken(HttpContext.Request.Headers); return(await _service.PostAsync(requestObject, userId)); }
public EmployeesToView GetByLogin(string login) { return(new EmployeesToView(officeDB.Employees.FirstOrDefault(t => t.Login == login), TokenManager.GetStatus(login))); }
public async Task <ResponseObject <int, bool> > Delete(RequestObject <int> requestObject) { var userId = TokenManager.GetUserIDbyToken(HttpContext.Request.Headers); return(await _service.DeleteAsync(requestObject, userId)); }
// // public void AIBeast(){ // if (basearrow == false) { // Vector3 objectPos = new Vector3 (0, baseposY, 0); //error on this line // tokenManager.createNewTokenAI (objectPos); // timer = 0f; // basearrow = true; // // } // // timer += Time.deltaTime; // // if (timer >= 2f) { // float xpos = Random.Range(Global.left,Global.right); // float ypos = Random.Range(Global.bottom,Global.top); // // //Debug.Log (xpos); // Random.Range(0,360); // Vector3 objectPos = new Vector3 (xpos, ypos, 0); //error on this line // tokenManager.createNewTokenAI (objectPos); // timer = 0f; // } // // } //public List<Token> getTokenList() { // return tokenList; //} // Update is called once per frame void Update() { sorrow += sorrowgen; if (tokenManager == null) tokenManager = new TokenManager (this, token); tokenManager.trimOldTokens (maxTokensLimit); if (HumanPlayer == false) { //Debug.Log ("AI exists"); // AIBeast (); ai.pulse(); } // if (this.HumanPlayer == false) { // Debug.Log ("AI expect player 1: " + PlayerNumber); // // } }
public async Task <ActionResult> JoinEmbedded(string name, string auth) { if (string.IsNullOrEmpty(name)) { return(RedirectToAction("Index", "Rooms")); } // Join var room = await db.Rooms.FirstOrDefaultAsync(c => c.Name == name); if (room == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // ユーザーを取得できれば取得 var viewModel = new StatusMessageViewModel <JoinRoomViewModel>() { Item = new JoinRoomViewModel() { Room = room } }; var appUser = await GetApplicationUser(); bool isBroadcaster = (appUser != null && room.Owner.Id == appUser.Id); viewModel.Item.IsBroadcaster = isBroadcaster; if (!room.IsLive) { if (appUser == null || !appUser.OwnerRooms.Contains(room)) { viewModel.Message = "現在ルームはオフラインです。管理者以外は入室できません。"; viewModel.Type = MessageType.Error; return(View(viewModel)); } else if (isBroadcaster) { var instance = RoomManager.GetInstance(); if (instance.GetRoomInfo(room.Id) == null) { // まだ入れませんよ viewModel.Message = "あなたはこのルームの管理者です。ルームに入室するには、まずエディタからログインしてセッションを確立してください。"; viewModel.Type = MessageType.Error; return(View(viewModel)); } } } viewModel.Item.CanJoin = true; if (room.IsPrivate && !isBroadcaster) { // 認証する if (!String.IsNullOrWhiteSpace(auth)) { string passCode = auth; // 値が違う場合 if (passCode != room.AccessCode) { viewModel.Type = MessageType.Error; viewModel.Message = "認証コードが違います"; return(View(viewModel)); } } else { viewModel.Type = MessageType.Warning; viewModel.Message = "このルームは認証が必要です"; return(View(viewModel)); } } // アクセスを許可 -> Tokenを発行 var tokenManager = TokenManager.GetInstance(); var token = tokenManager.CreateToken(room.Id); await db.SaveChangesAsync(); TempData["token"] = token; return(RedirectToAction("LiveEmbedded", new { name = name })); }
public async Task <ResponseObject <bool> > Delete(RequestDelete <DeleteModel> requestObject) { var user = TokenManager.GetCurentUserbyToken(Request.Headers); return(await _service.DeleteAsync(requestObject, user)); }
public async Task <IHttpActionResult> Put(int id, [FromBody] PaymentReq req) { try { string errorMessage = "UnknowError"; string errorCode = ErrorCodeEnum.UnknownError.ToString(); #region token var header = Request.Headers; if (header.Authorization == null) { return(StatusCode(HttpStatusCode.Unauthorized)); } var token = header.Authorization.Parameter; Employee employee; if (string.IsNullOrWhiteSpace(token) || !TokenManager.ValidateToken(token, out employee)) { return(StatusCode(HttpStatusCode.Unauthorized)); } #endregion if (!Operator.IsAdmin(employee)) { return(Ok(new RequestErrorCode(false, ErrorCodeEnum.Error_NotHavePermision.ToString(), "Khong co quyen"))); } var entityData = req.GetEntity(); #region Validate if (!ValidateUpdate(entityData, out errorCode, out errorMessage)) { return(Ok(new RequestErrorCode(false, errorCode, errorMessage))); } #endregion #region Check exist var obj = MemoryInfo.GetPayment(id); if (obj == null) { return(Ok(new RequestErrorCode(false, ErrorCodeEnum.DataNotExist.ToString(), "Khong ton tai"))); } #endregion req.Id = obj.Id; // gan lai id de update #region Process req.UpdatedAt = DateTime.Now; req.UpdatedBy = employee.Id; UpdateEntitySql updateEntitySql = new UpdateEntitySql(); var lstCommand = new List <EntityCommand>(); lstCommand.Add(new EntityCommand { BaseEntity = new Entity.Entity(req.GetEntity()), EntityAction = EntityAction.Update }); var isOkDone = updateEntitySql.UpdateDefault(lstCommand); if (!isOkDone) { return(Ok(new RequestErrorCode(false, errorCode, errorMessage))); } #endregion // update memory MemorySet.UpdateAndInsertEntity(req.GetEntity()); var result = new RequestErrorCode(true); result.DataResult = req; return(Ok(result)); } catch (Exception ex) { Logger.Write(ex.ToString()); } return(BadRequest("Unknow")); }
/// <summary> /// 新增T_SM_UserAccount数据 /// </summary> /// <param name="requestObject">返回响应结果对象,包括响应代码,新增操作结果</param> /// <returns></returns> public async Task <ResponseObject <string> > PostAsync(RequestPost <TSMUserAccountAddModel> requestObject) { var currDb = _db.Instance; try { //如果没有新增数据,返回错误信息 if (requestObject.PostData == null && requestObject.PostDataList == null) { return(ResponseUtil <string> .FailResult(null, "PostData,PostDataList不能都为null")); } var result = false; string token = string.Empty; currDb.BeginTran(); //批量新增的优先级高于单条数据新增,且只会执行一个新增操作 if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0) { } else { //注册账号信息 var addModel = _mapper.Map <TSMUserAccountDbModel>(requestObject.PostData); addModel.Salt = RandCodeCreate.GenerateRandomNumber(32); addModel.Passwd = EncryptUtil.EnAESBykey(addModel.Passwd, addModel.Salt); addModel.Status = 1; if (string.IsNullOrWhiteSpace(addModel.EmailAccount)) { addModel.EmailAccount = null; } if (string.IsNullOrWhiteSpace(addModel.TelAccount)) { addModel.TelAccount = null; } //生成用户详情记录 TSMUserInfoDbModel tSMUserInfoDbModel = new TSMUserInfoDbModel(); int cid = await _db.Instance.Insertable(tSMUserInfoDbModel).ExecuteReturnIdentityAsync(); addModel.UserInfoId = cid; int id = _db.Instance.Insertable(addModel).ExecuteReturnIdentity(); var palyloads = new Dictionary <string, object> { { "UserID", id }, { "ID", Guid.NewGuid().ToString() }, { "CompanyID", 0 }, { "UserName", addModel.AccountName } }; token = TokenManager.CreateTokenByHandler(palyloads, 60 * 24); currDb.CommitTran(); } //返回执行结果 return(ResponseUtil <string> .SuccessResult(token)); } catch (Exception ex) { //返回异常结果 currDb.RollbackTran(); return(ResponseUtil <string> .FailResult(null, ex.Message)); } }
public async Task <IHttpActionResult> Delete(int id) { try { string errorMessage = "UnknowError"; string errorCode = ErrorCodeEnum.UnknownError.ToString(); #region token var header = Request.Headers; if (header.Authorization == null) { return(StatusCode(HttpStatusCode.Unauthorized)); } var token = header.Authorization.Parameter; Employee employee; if (string.IsNullOrWhiteSpace(token) || !TokenManager.ValidateToken(token, out employee)) { return(StatusCode(HttpStatusCode.Unauthorized)); } #endregion if (!Operator.IsAdmin(employee)) { return(Ok(new RequestErrorCode(false, ErrorCodeEnum.Error_NotHavePermision.ToString(), "Khong co quyen"))); } #region Check exist var obj = MemoryInfo.GetPayment(id); if (obj == null) { return(Ok(new RequestErrorCode(false, ErrorCodeEnum.DataNotExist.ToString(), "Khong ton tai"))); } #endregion bool isHasDeleteProperties = obj.GetType().GetProperty("IsDeleted") != null; if (!isHasDeleteProperties) { return(Ok(new RequestErrorCode(false, ErrorCodeEnum.DataNotExist.ToString(), "Khong ton tai"))); } obj.IsDeleted = 1; #region Process UpdateEntitySql updateEntitySql = new UpdateEntitySql(); var lstCommand = new List <EntityCommand>(); var lstPaymentFee = MemoryInfo.GetListPaymentFeeByField(obj.Id.ToString(), PaymentFee.PaymentFeeFields.IdPayment); foreach (var paymentFee in lstPaymentFee) { lstCommand.Add(new EntityCommand { BaseEntity = new Entity.Entity(paymentFee), EntityAction = EntityAction.Delete }); MemorySet.RemoveMemory(paymentFee); } lstCommand.Add(new EntityCommand { BaseEntity = new Entity.Entity(obj), EntityAction = EntityAction.Update }); bool isOkDone = updateEntitySql.UpdateDefault(lstCommand); if (!isOkDone) { return(Ok(new RequestErrorCode(false, errorCode, errorMessage))); } #endregion // update memory MemorySet.UpdateAndInsertEntity(obj); var result = new RequestErrorCode(true); result.DataResult = obj; return(Ok(result)); } catch (Exception ex) { Logger.Write(ex.ToString()); } return(BadRequest("Unknow")); }
public async Task <ResponseMessage <HumanInfoPartPositionResponse> > CreateAsync(UserInfo user, HumanInfoPartPositionRequest humanInfoPartPostionRequest, CancellationToken cancellationToken = default(CancellationToken)) { ResponseMessage <HumanInfoPartPositionResponse> response = new ResponseMessage <HumanInfoPartPositionResponse>(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (humanInfoPartPostionRequest == null) { throw new ArgumentNullException(nameof(humanInfoPartPostionRequest)); } var humaninfo = await _humanInfoStore.GetAsync(a => a.Where(b => b.Id == humanInfoPartPostionRequest.HumanId && !b.IsDeleted), cancellationToken); if (humaninfo == null) { response.Code = ResponseCodeDefines.NotFound; response.Message = "操作的人事信息未找到"; return(response); } var org = await _permissionExpansionManager.GetOrganizationOfPermission(user.Id, "HumanPartPosition"); if (org == null || org.Count == 0 || !org.Contains(humanInfoPartPostionRequest.DepartmentId) || !org.Contains(humaninfo.DepartmentId)) { response.Code = ResponseCodeDefines.NotAllow; response.Message = "没有权限"; return(response); } if (string.IsNullOrEmpty(humanInfoPartPostionRequest.Id)) { humanInfoPartPostionRequest.Id = Guid.NewGuid().ToString(); } var gatwayurl = ApplicationContext.Current.AppGatewayUrl.EndsWith("/") ? ApplicationContext.Current.AppGatewayUrl.TrimEnd('/') : ApplicationContext.Current.AppGatewayUrl; GatewayInterface.Dto.ExamineSubmitRequest examineSubmitRequest = new GatewayInterface.Dto.ExamineSubmitRequest(); examineSubmitRequest.ContentId = humanInfoPartPostionRequest.Id; examineSubmitRequest.ContentType = "HumanPartPosition"; examineSubmitRequest.ContentName = humaninfo.Name; examineSubmitRequest.Content = "新增员工人事兼职信息"; examineSubmitRequest.Source = user.FilialeName; examineSubmitRequest.SubmitDefineId = humanInfoPartPostionRequest.Id; examineSubmitRequest.CallbackUrl = gatwayurl + "/api/humanpartposition/humanpartpositioncallback"; examineSubmitRequest.StepCallbackUrl = gatwayurl + "/api/humanpartposition/HumanPartPositionStepCallback"; examineSubmitRequest.Action = "HumanPartPosition"; examineSubmitRequest.TaskName = $"新增员工人事兼职信息:{humaninfo.Name}"; examineSubmitRequest.Desc = $"新增员工人事兼职信息"; GatewayInterface.Dto.UserInfo userInfo = new GatewayInterface.Dto.UserInfo() { Id = user.Id, KeyWord = user.KeyWord, OrganizationId = user.OrganizationId, OrganizationName = user.OrganizationName, UserName = user.UserName }; examineSubmitRequest.UserInfo = userInfo; string tokenUrl = $"{ApplicationContext.Current.AuthUrl}/connect/token"; string examineCenterUrl = $"{ApplicationContext.Current.ExamineCenterUrl}"; Logger.Info($"新增员工人事兼职信息提交审核,\r\ntokenUrl:{tokenUrl ?? ""},\r\nexamineCenterUrl:{examineCenterUrl ?? ""},\r\nexamineSubmitRequest:" + (examineSubmitRequest != null ? JsonHelper.ToJson(examineSubmitRequest) : "")); var tokenManager = new TokenManager(tokenUrl, ApplicationContext.Current.ClientID, ApplicationContext.Current.ClientSecret); var response2 = await tokenManager.Execute(async (token) => { return(await _restClient.PostWithToken <ResponseMessage>(examineCenterUrl, examineSubmitRequest, token)); }); if (response2.Code != ResponseCodeDefines.SuccessCode) { response.Code = ResponseCodeDefines.ServiceError; response.Message = "向审核中心发起审核请求失败:" + response2.Message; Logger.Info($"新增员工人事兼职信息提交审核失败:" + response2.Message); return(response); } response.Extension = _mapper.Map <HumanInfoPartPositionResponse>(await Store.CreateAsync(user, _mapper.Map <HumanInfoPartPosition>(humanInfoPartPostionRequest), cancellationToken)); return(response); }
public async Task <IHttpActionResult> Post([FromBody] PaymentReq req) { try { string errorMessage = "UnknowError"; string errorCode = ErrorCodeEnum.UnknownError.ToString(); #region token var header = Request.Headers; if (header.Authorization == null) { return(StatusCode(HttpStatusCode.Unauthorized)); } var token = header.Authorization.Parameter; Employee employee; if (string.IsNullOrWhiteSpace(token) || !TokenManager.ValidateToken(token, out employee)) { return(StatusCode(HttpStatusCode.Unauthorized)); } #endregion if (!Operator.IsAdmin(employee)) { return(Ok(new RequestErrorCode(false, ErrorCodeEnum.Error_NotHavePermision.ToString(), "Khong co quyen"))); } var entityData = req.GetEntity(); #region Validate if (!Validate(entityData, out errorCode, out errorMessage)) { return(Ok(new RequestErrorCode(false, errorCode, errorMessage))); } #endregion #region Tạo key var oldKey = Memory.Memory.GetMaxKey(entityData.GetName()); int newKey = oldKey + 1; // set key req.Id = newKey; #endregion #region Process req.CreatedAt = DateTime.Now; req.CreatedBy = employee.Id; req.IsDeleted = 0; UpdateEntitySql updateEntitySql = new UpdateEntitySql(); var lstCommand = new List <EntityCommand>(); if (req.ListDataTemp != null) { foreach (var paymentFee in req.ListDataTemp) { paymentFee.IdPayment = newKey; paymentFee.IsDeleted = 0; lstCommand.Add(new EntityCommand { BaseEntity = new Entity.Entity(paymentFee), EntityAction = EntityAction.Insert }); MemorySet.UpdateAndInsertEntity(paymentFee); } } lstCommand.Add(new EntityCommand { BaseEntity = new Entity.Entity(req.GetEntity()), EntityAction = EntityAction.Insert }); bool isOkDone = updateEntitySql.UpdateDefault(lstCommand); if (!isOkDone) { return(Ok(new RequestErrorCode(false, errorCode, errorMessage))); } #endregion // update memory MemorySet.UpdateAndInsertEntity(req.GetEntity()); var result = new RequestErrorCode(true); result.DataResult = req; return(Ok(result)); } catch (Exception ex) { Logger.Write(ex.ToString()); } return(BadRequest("Unknow")); }
public HttpResponseMessage Authenicate(HttpRequestMessage request, [FromBody] UserInformation userInformation) { TransactionalInformation transaction = new TransactionalInformation(); if (request.Headers.Authorization == null) { transaction.ReturnMessage.Add("Your session is invalid."); transaction.ReturnStatus = false; var badResponse = Request.CreateResponse <TransactionalInformation>(HttpStatusCode.Unauthorized, transaction); return(badResponse); } string tokenString = request.Headers.Authorization.ToString(); bool principal = TokenManager.ValidateToken(tokenString); if (!principal) { transaction.ReturnMessage.Add("Your session is invalid."); transaction.ReturnStatus = false; var badResponse = Request.CreateResponse <TransactionalInformation>(HttpStatusCode.Unauthorized, transaction); return(badResponse); } int userID = TokenManager.GetUserID(Request.Headers.Authorization.ToString()); if (userID == 0) { transaction.ReturnMessage.Add("Your session is invalid."); transaction.ReturnStatus = false; var badResponse = Request.CreateResponse <TransactionalInformation>(HttpStatusCode.Unauthorized, transaction); return(badResponse); } UserBusinessService userBusinessService = new UserBusinessService(_userDataService); User user = userBusinessService.Authenicate(userID, out transaction); if (transaction.ReturnStatus == false) { var badResponse = Request.CreateResponse <TransactionalInformation>(HttpStatusCode.BadRequest, transaction); return(badResponse); } userInformation.UserID = user.UserID; userInformation.EmailAddress = user.EmailAddress; userInformation.FirstName = user.FirstName; userInformation.LastName = user.LastName; userInformation.AddressLine1 = user.AddressLine1; userInformation.AddressLine2 = user.AddressLine2; userInformation.City = user.City; userInformation.State = user.State; userInformation.ZipCode = user.ZipCode; userInformation.IsAuthenicated = true; userInformation.ReturnStatus = true; var response = Request.CreateResponse <UserInformation>(HttpStatusCode.OK, userInformation); response.Headers.Add("Access-Control-Expose-Headers", "Authorization"); response.Headers.Add("Authorization", tokenString); return(response); }
public async Task <IHttpActionResult> Post() { try { string errorMessage = "UnknowError"; string errorCode = ErrorCodeEnum.UnknownError.ToString(); #region token var header = Request.Headers; if (header.Authorization == null) { return(StatusCode(HttpStatusCode.Unauthorized)); } var token = header.Authorization.Parameter; Employee employee; if (string.IsNullOrWhiteSpace(token) || !TokenManager.ValidateToken(token, out employee)) { return(StatusCode(HttpStatusCode.Unauthorized)); } #endregion #region Tạo key var oldKey = Memory.GetMaxKey(Image.EntityName()); int newKey = oldKey + 1; #endregion #region Luu vao forlder resource var httpRequest = HttpContext.Current.Request; Dictionary <HttpPostedFile, string> dicUpload = new Dictionary <HttpPostedFile, string>(); foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; if (postedFile != null && postedFile.ContentLength > 0) { int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB IList <string> AllowedFileExtensions = new List <string> { ".jpg", ".png" }; var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.')); var extension = ext.ToLower(); if (!AllowedFileExtensions.Contains(extension)) { var message = string.Format("Please Upload image of type .jpg,.png."); return(Ok(new RequestErrorCode(false, errorCode, message))); } else if (postedFile.ContentLength > MaxContentLength) { var message = string.Format("Please Upload a file upto 1 mb."); return(Ok(new RequestErrorCode(false, errorCode, message))); } else { dicUpload[postedFile] = PasswordGenerator.GetRandomString(12, true) + extension; } } } #endregion #region Process var lstCommand = new List <EntityCommand>(); List <Image> lstResponse = new List <Image>(); foreach (var temp in dicUpload) { var filePath = AppGlobal.NexusConfig.FolderSaveImages + "/" + temp.Value; var filePosted = temp.Key; filePosted.SaveAs(filePath); var data = new Image { CreatedAt = DateTime.Now, CreatedBy = employee.Id, Id = newKey, Url = temp.Value }; lstCommand.Add(new EntityCommand { BaseEntity = new Entity(data), EntityAction = EntityAction.Insert }); // update memory MemorySet.UpdateAndInsertEntity(data); // gan lai response tra ve cho client var objRes = data.Clone() as Image; objRes.Url = AppGlobal.NexusConfig.BaseUrl + temp.Value; lstResponse.Add(objRes); newKey++; } UpdateEntitySql updateEntitySql = new UpdateEntitySql(); bool isOkDone = updateEntitySql.UpdateDefault(lstCommand); if (!isOkDone) { return(Ok(new RequestErrorCode(false, errorCode, errorMessage))); } #endregion var result = new RequestErrorCode(true); result.ListDataResult.AddRange(lstResponse); return(Ok(result)); } catch (Exception ex) { Logger.Write(ex.ToString()); } return(BadRequest("Unknow")); }
public string GetActiveForAccount(string token) { token = TokenManager.readToken(HttpContext.Current.Request); string type = ""; string payType = ""; var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "type") { type = c.Value; } if (c.Type == "payType") { payType = c.Value; } } using (incposdbEntities entity = new incposdbEntities()) { var agentsList = entity.agents .Where(p => p.type == type && (p.isActive == 1 || (p.isActive == 0 && payType == "p" && p.balanceType == 0) || (p.isActive == 0 && payType == "d" && p.balanceType == 1))) .Select(p => new { p.agentId, p.name, p.code, p.company, p.address, p.email, p.phone, p.mobile, p.image, p.type, p.accType, p.balance, p.balanceType, p.notes, p.maxDeserve, p.fax, p.isActive, p.createDate, p.isLimited, p.payType }) .ToList(); //var agentsList2 = (from a in entity.agents.Where(a => a.type == type && a.isActive == 0) // join i in entity.invoices.Where(i => i.deserved > 0) on a.agentId equals i.agentId into ai // from aii in ai.DefaultIfEmpty() // select new // { // agentId = a.agentId, // name = a.name, // code = a.code, // company = a.company, // address = a.address, // email = a.email, // phone = a.phone, // mobile = a.mobile, // image = a.image, // type = a.type, // accType = a.accType, // balance = a.balance, // balanceType = a.balanceType, // notes = a.notes, // maxDeserve = a.maxDeserve, // fax = a.fax, // isActive = a.isActive, // createDate = a.createDate, // isLimited = a.isLimited, // payType = a.payType, // }).ToList(); //agentsList.AddRange(agentsList2); return(TokenManager.GenerateToken(agentsList)); } } }
public LoginController(TokenManager tokenManager, IUserService userService) { _tokenManager = tokenManager; _userService = userService; }
public string Get(string token) { token = TokenManager.readToken(HttpContext.Current.Request); string type = ""; Boolean canDelete = false; var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "type") { type = c.Value; } } using (incposdbEntities entity = new incposdbEntities()) { var agentsList = entity.agents .Where(p => p.type == type) .Select(p => new AgentModel { agentId = p.agentId, name = p.name, code = p.code, company = p.company, address = p.address, email = p.email, phone = p.phone, mobile = p.mobile, image = p.image, type = p.type, accType = p.accType, balance = p.balance, balanceType = p.balanceType, notes = p.notes, isActive = p.isActive, createDate = p.createDate, updateDate = p.updateDate, maxDeserve = p.maxDeserve, fax = p.fax, isLimited = p.isLimited, payType = p.payType }) .ToList(); if (agentsList.Count > 0) { for (int i = 0; i < agentsList.Count; i++) { canDelete = false; if (agentsList[i].isActive == 1) { int agentId = (int)agentsList[i].agentId; var invoicesL = entity.invoices.Where(x => x.agentId == agentId).Select(b => new { b.invoiceId }).FirstOrDefault(); var cachTransferL = entity.cashTransfer.Where(x => x.agentId == agentId).Select(x => new { x.cashTransId }).FirstOrDefault(); if ((invoicesL is null) && (cachTransferL is null)) { canDelete = true; } } agentsList[i].canDelete = canDelete; } } return(TokenManager.GenerateToken(agentsList)); } } }
public string Save(string token) { token = TokenManager.readToken(HttpContext.Current.Request); var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { string message = ""; string newObject = ""; int inventoryId = 0; List <InventoryItemLocationModel> Object = null; IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "itemObject") { newObject = c.Value.Replace("\\", string.Empty); newObject = newObject.Trim('"'); Object = JsonConvert.DeserializeObject <List <InventoryItemLocationModel> >(newObject, new JsonSerializerSettings { DateParseHandling = DateParseHandling.None }); } else if (c.Type == "inventoryId") { inventoryId = int.Parse(c.Value); } } using (incposdbEntities entity = new incposdbEntities()) { List <inventoryItemLocation> items = entity.inventoryItemLocation.Where(x => x.inventoryId == inventoryId).ToList(); if (items == null || items.Count == 0)// add first time { foreach (InventoryItemLocationModel il in Object) { inventoryItemLocation tmp = new inventoryItemLocation(); if (il.createUserId == 0 || il.createUserId == null) { Nullable <int> id = null; tmp.createUserId = id; } if (il.amountDestroyed == 0 || il.amountDestroyed == null) { Nullable <int> id = 0; tmp.amountDestroyed = id; } tmp.inventoryId = inventoryId; tmp.amount = il.amount; tmp.amountDestroyed = il.amountDestroyed; tmp.isDestroyed = il.isDestroyed; tmp.isFalls = il.isFalls; tmp.realAmount = il.quantity; tmp.cause = il.cause; tmp.notes = il.notes; tmp.itemLocationId = il.itemLocationId; tmp.createDate = DateTime.Now; tmp.updateDate = DateTime.Now; tmp.updateUserId = il.createUserId; entity.inventoryItemLocation.Add(tmp); message = tmp.id.ToString(); } entity.SaveChanges(); return(TokenManager.GenerateToken(message)); } else // edit saved inventory details { foreach (InventoryItemLocationModel il in Object) { inventoryItemLocation invItem = entity.inventoryItemLocation.Find(il.id); invItem.amount = il.amount; invItem.isDestroyed = il.isDestroyed; invItem.isFalls = il.isFalls; invItem.amountDestroyed = il.amountDestroyed; invItem.cause = il.cause; invItem.notes = il.notes; invItem.updateDate = DateTime.Now; invItem.updateUserId = il.updateUserId; message = invItem.id.ToString(); } entity.SaveChanges(); return(TokenManager.GenerateToken(message)); } } message = "0"; return(TokenManager.GenerateToken(message)); } }
public AggregationReportData GetTrendReport() { AggregationReportData response = new AggregationReportData(); response.SalList = new List <BasicReportData.OverallSALTable>(); response.DocumentLibraryTable = new List <DocumentLibraryTable>(); TokenManager tm = new TokenManager(); var aggregationID = tm.PayloadInt("aggreg"); if (aggregationID == null) { return(response); } var aggManager = new BusinessLogic.AggregationManager(); var assessmentList = aggManager.GetAssessmentsForAggregation((int)aggregationID); var aggregation = aggManager.GetAggregation((int)aggregationID); response.AggregationName = assessmentList.Aggregation.AggregationName; response.Information = new AggInformation() { Assessment_Date = aggregation.AggregationDate, Assessment_Name = aggregation.AggregationName, Assessor_Name = aggregation.AssessorName }; foreach (var a in assessmentList.Assessments) { ReportsDataManager reportsDataManager = new ReportsDataManager(a.AssessmentId); // Incorporate SAL values into response var salTable = reportsDataManager.GetSals(); var entry = new BasicReportData.OverallSALTable(); response.SalList.Add(entry); entry.Alias = a.Alias; entry.OSV = salTable.OSV; entry.Q_CV = ""; entry.Q_IV = ""; entry.Q_AV = ""; entry.LastSalDeterminationType = salTable.LastSalDeterminationType; if (salTable.LastSalDeterminationType != "GENERAL") { entry.Q_CV = salTable.Q_CV; entry.Q_IV = salTable.Q_IV; entry.Q_AV = salTable.Q_AV; } // Document Library var documentLibraryTable = reportsDataManager.GetDocumentLibrary(); foreach (var docEntry in documentLibraryTable) { docEntry.Alias = a.Alias; response.DocumentLibraryTable.Add(docEntry); } } return(response); }
public string Delete(string token) { token = TokenManager.readToken(HttpContext.Current.Request); string message = ""; var strP = TokenManager.GetPrincipal(token); if (strP != "0") //invalid authorization { return(TokenManager.GenerateToken(strP)); } else { int id = 0; int userId = 0; Boolean final = false; IEnumerable <Claim> claims = TokenManager.getTokenClaims(token); foreach (Claim c in claims) { if (c.Type == "itemId") { id = int.Parse(c.Value); } else if (c.Type == "userId") { userId = int.Parse(c.Value); } else if (c.Type == "final") { final = bool.Parse(c.Value); } } if (final) { try { using (incposdbEntities entity = new incposdbEntities()) { inventoryItemLocation Deleterow = entity.inventoryItemLocation.Find(id); entity.inventoryItemLocation.Remove(Deleterow); message = entity.SaveChanges().ToString(); return(TokenManager.GenerateToken(message)); } } catch { message = "0"; return(TokenManager.GenerateToken(message)); } } else { try { using (incposdbEntities entity = new incposdbEntities()) { inventoryItemLocation Obj = entity.inventoryItemLocation.Find(id); Obj.isActive = 0; Obj.updateUserId = userId; Obj.updateDate = DateTime.Now; message = entity.SaveChanges().ToString(); return(TokenManager.GenerateToken(message)); } } catch { message = "0"; return(TokenManager.GenerateToken(message)); } } } }