public async Task <GetPointResult> GetPointAsync(GetPointRequest getPointRequest, CancellationToken cancellationToken = default(CancellationToken)) { if (getPointRequest == null) { throw new ArgumentNullException("getPointRequest"); } var geohash = S2Manager.GenerateGeohash(getPointRequest.GeoPoint); var hashKey = S2Manager.GenerateHashKey(geohash, _config.HashKeyLength); var getItemRequest = getPointRequest.GetItemRequest; getItemRequest.TableName = _config.TableName; var hashKeyValue = new AttributeValue { N = hashKey.ToString(CultureInfo.InvariantCulture) }; getItemRequest.Key[_config.HashKeyAttributeName] = hashKeyValue; getItemRequest.Key[_config.RangeKeyAttributeName] = getPointRequest.RangeKeyValue; GetItemResponse getItemResult = await _config.DynamoDBClient.GetItemAsync(getItemRequest, cancellationToken).ConfigureAwait(false); var getPointResult = new GetPointResult(getItemResult); return(getPointResult); }
public GetItemResponse<Contact> GetContactByName(IDRequest request) { try { var response = new GetItemResponse<Contact>(); var db = ImardaDatabase.CreateDatabase(Util.GetConnName<Contact>()); string custName = request.GetString("custName"); using (IDataReader dr = db.ExecuteDataReader("SPGetContactByName", request.ID, custName)) { response = new GetItemResponse<Contact>(); if (dr.Read()) { response.Item = (GetFromData<Contact>(dr)); } return response; } } catch (Exception ex) { return ErrorHandler.Handle<GetItemResponse<Contact>>(ex); } }
public GetItemResponse<SecurityEntity> GetSecurityEntity(IDRequest request) { var response = new GetItemResponse<SecurityEntity>(); try { response = GenericGetEntity<SecurityEntity>(request); if (response != null && response.Item != null) { SecurityEntity entity = response.Item; Guid applicationID; request.Get<Guid>("appid", out applicationID); //fill in permission list entity.PermissionList = GetSecurityPermissionList(applicationID, entity); // fill in the parent id list entity.ImmediateParentsIds = GetEntityRelationships(entity.ID); response.Item = entity; } } catch (Exception ex) { return ErrorHandler.Handle<GetItemResponse<SecurityEntity>>(ex); } return response; }
/// <summary> /// Validates if the user provided credentials are correct for their user account /// </summary> /// <param name="loginInfo">Uses GCUser.LoginInfo.Email to validate the email address</param> /// <param name="password">Password to validate with hash</param> /// <returns>0 if successful, otherwise > 0</returns> public int ValidateCredentials(GCUser.LoginInfo loginInfo, string password) { int response = (int)DBEnum.DBResponseCodes.DEFAULT_VALUE; GetItemResponse giResponse = new GetItemResponse(); // check to see if the user exists (Email needs to be set prior to submitting) if ((int)DBEnum.DBResponseCodes.SUCCESS == SetUserLoginInfo(loginInfo)) { if (pwh.ValidatePassword(password, string.Format("{0}:{1}:{2}:{3}", loginInfo.Encryption, loginInfo.Iterations, loginInfo.SaltHash, loginInfo.PasswordHash))) { logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("User: {0} authenticated.", loginInfo.Email)); response = (int)DBEnum.DBResponseCodes.SUCCESS; } else { logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("User: {0} failed to authenticate.", loginInfo.Email)); response = (int)DBEnum.DBResponseCodes.INVALID_USERNAME_PASSWORD; } } // User does not exist or something failed to set (either way return error) else { logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("User: {0} failed to authenticate.", loginInfo.Email)); response = (int)DBEnum.DBResponseCodes.DOES_NOT_EXIST; } return(response); }
/// <summary> /// PRIVATE: Retrieves the user information from GCLogin DB /// </summary> /// <param name="email">email of user</param> /// <param name="returnResponse">out GetItemResponse</param> /// <returns>0 if successful, otherwise > 0</returns> private int GetUserLoginInfo(string email, out GetItemResponse returnResponse) { // Gets the user's login information from GCLogin Table and sets it in returnResponse int response = dbManager.GetItem(primaryKey, email, TABLE, out returnResponse); // Checks the error response switch (response) { // Success case (int)DBEnum.DBResponseCodes.SUCCESS: logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Successfully retrieved email: {0} data from table: {1}", email, TABLE)); break; // User Does Not Exist case (int)DBEnum.DBResponseCodes.DOES_NOT_EXIST: logger.WriteLog(GameLogger.LogLevel.Warning, string.Format("Email: {0} in table: {1} does not exist.", email, TABLE)); break; case (int)DBEnum.DBResponseCodes.DYNAMODB_EXCEPTION: logger.WriteLog(GameLogger.LogLevel.Error, string.Format("DynamoDB Exception Error when fetching email {0} in table: {1}", email, TABLE)); break; } return(response); }
public async Task Function_FunctionHandler_Publishes_Notification_For_Bad_Endpoint() { // Arrange const string endpoint = "bad.endpoint"; var fakeDdbClient = A.Fake <IAmazonDynamoDB>(); var fakeSnsClient = A.Fake <IAmazonSimpleNotificationService>(); var function = new Function(fakeDdbClient, fakeSnsClient); var response = new GetItemResponse { Item = new Dictionary <string, AttributeValue> { { "value", new AttributeValue(new List <string> { endpoint }) } } }; A.CallTo(() => fakeDdbClient.GetItemAsync(A <string> .Ignored, A <Dictionary <string, AttributeValue> > .Ignored, A <CancellationToken> .Ignored)) .Returns(response); var context = new TestLambdaContext(); // Act await function.FunctionHandler(context); // Assert A.CallTo(() => fakeSnsClient.PublishAsync(A <PublishRequest> .That.Matches(r => r.Message.Contains(endpoint)), A <CancellationToken> .Ignored)) .MustHaveHappenedOnceExactly(); }
public async Task Function_FunctionHandler_Can_Be_Invoked_With_Valid_Endpoint() { // Arrange const string endpoint = "http://example.com"; var fakeDdbClient = A.Fake <IAmazonDynamoDB>(); var fakeSnsClient = A.Fake <IAmazonSimpleNotificationService>(); var function = new Function(fakeDdbClient, fakeSnsClient); var response = new GetItemResponse { Item = new Dictionary <string, AttributeValue> { { "value", new AttributeValue(new List <string> { endpoint }) } } }; A.CallTo(() => fakeDdbClient.GetItemAsync(A <string> .Ignored, A <Dictionary <string, AttributeValue> > .Ignored, A <CancellationToken> .Ignored)) .Returns(response); var context = new TestLambdaContext(); // Act await function.FunctionHandler(context); // Assert A.CallTo(() => fakeSnsClient.PublishAsync(A <PublishRequest> .Ignored, A <CancellationToken> .Ignored)).MustNotHaveHappened(); }
public async Task <Project> GetProjectByIdForUserAsync(string username, string projectId) { // Query for all Project records owned by this user. var getRequest = new GetItemRequest { TableName = this.projectsTableName, Key = new Dictionary <string, AttributeValue> { { "Id", new AttributeValue { S = projectId } }, { "OwningUser", new AttributeValue { S = username } }, } }; GetItemResponse results = await this.dynamoDB.GetItemAsync(getRequest); // Convert the NoSql document into a domain model. Dictionary <string, AttributeValue> document = results.Item; Guid id = Guid.Parse(document["Id"].S); var project = new Project(id, document["OwningUser"].S, document["Priority"].S, document["Status"].S, document["Title"].S, document["Type"].S); return(project); }
public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { string coinSymbol = ""; string testVariable = null; Table table = Table.LoadTable(client, tableName); Dictionary <string, string> queryStrings = (Dictionary <string, string>)input.QueryStringParameters; if (queryStrings != null) { queryStrings.TryGetValue("coinName", out coinSymbol); } else { if (testVariable != null) { coinSymbol = testVariable; } coinSymbol = "bitcoin"; } GetItemResponse response = await client.GetItemAsync(tableName, new Dictionary <string, AttributeValue> { { "id", new AttributeValue { S = coinSymbol } } }); Document doc = Document.FromAttributeMap(response.Item); Coin coin = JsonConvert.DeserializeObject <Coin>(doc.ToJson()); return(JsonConvert.SerializeObject(coin)); }
public static async Task AssertItemAsync( this IAmazonDynamoDB db, string tableName, Dictionary <string, AttributeValue> key, Dictionary <string, AttributeValue> expectedItem ) { GetItemRequest request = new GetItemRequest { TableName = tableName, Key = key, ConsistentRead = true }; GetItemResponse response = await db .GetItemAsync(request) .ConfigureAwait(false); if (!response.IsItemSet) { Assert.Fail("Item should exist."); } AttributeValueAssert.AreEqual( actual: response.Item, expected: expectedItem ); }
public async Task <Profile> GetUserByDiscord(DiscordUser discordUser) { // Attempt to pull a discord login GetItemResponse discordLoginResponse = await _client.GetItemAsync(new GetItemRequest { TableName = _tableName, Key = new Dictionary <string, AttributeValue> { { "pk", new AttributeValue { S = $"DISCORD#{discordUser.id}" } }, { "sk", new AttributeValue { S = "login" } } } }); // User doesn't exist if (!discordLoginResponse.IsItemSet) { throw new UserNotFoundException(); } // Return the user try { return(await GetUser(discordLoginResponse.Item["userId"].S)); } catch (UserNotFoundException) { // Discord exists but not user profile? This is bad. // FIXME Oh no Console.WriteLine($"[Database] Discord User exists, but profile doesnt! DiscordID = {discordUser.id}"); throw new DefaultDatabaseException(); } }
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetItemResponse response = new GetItemResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ConsumedCapacity", targetDepth)) { var unmarshaller = ConsumedCapacityUnmarshaller.Instance; response.ConsumedCapacity = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Item", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller <string, AttributeValue, StringUnmarshaller, AttributeValueUnmarshaller>(StringUnmarshaller.Instance, AttributeValueUnmarshaller.Instance); response.Item = unmarshaller.Unmarshall(context); continue; } } return(response); }
public GetPointResult(GetItemResponse getItemResult) { if (getItemResult == null) { throw new ArgumentNullException("getItemResult"); } GetItemResult = getItemResult; }
public async Task TestColsAddAsync() { string id = Guid.NewGuid().ToString(); Console.WriteLine(id); Dictionary <string, AttributeValue> keyItem = new Dictionary <string, AttributeValue> { { "Id", new AttributeValue { S = id } } }; PutItemResponse putResponse = await DDBClient.PutItemAsync(TableName, keyItem); Assert.AreEqual(putResponse.HttpStatusCode, HttpStatusCode.OK); Dictionary <string, AttributeValueUpdate> updateItem = new Dictionary <string, AttributeValueUpdate> { { "Col1", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { N = "0" } } } }; UpdateItemResponse updateResponse = await DDBClient.UpdateItemAsync(TableName, keyItem, updateItem); Assert.AreEqual(updateResponse.HttpStatusCode, HttpStatusCode.OK); Dictionary <string, AttributeValueUpdate> updateItem2 = new Dictionary <string, AttributeValueUpdate> { { "Col1", new AttributeValueUpdate { Action = AttributeAction.PUT, Value = new AttributeValue { N = "1" } } } }; UpdateItemResponse updateResponse2 = await DDBClient.UpdateItemAsync(TableName, keyItem, updateItem2); Assert.AreEqual(updateResponse2.HttpStatusCode, HttpStatusCode.OK); GetItemResponse getItemResponse = await DDBClient.GetItemAsync(TableName, keyItem); Assert.AreEqual(getItemResponse.HttpStatusCode, HttpStatusCode.OK); bool isId = getItemResponse.Item.TryGetValue("Id", out AttributeValue id2); Assert.IsTrue(isId); Assert.AreEqual(id, id2.S); bool isCol1 = getItemResponse.Item.TryGetValue("Col1", out AttributeValue co1); Assert.IsTrue(isCol1); Assert.AreEqual("1", co1.N); }
private static string?GetPayload(GetItemResponse response) { if (!response.Item.TryGetValue(PayloadAttribute, out AttributeValue? payload)) { return(null); } return(payload?.S); }
private void HandleGetItem(GetItemRequest request) { if (cache.ContainsKey(request.Id) && cache[request.Id] == request.ETag) { Sender.Tell(GetItemResponse.HasNotBeenModified(request.Id, request.ETag)); return; } store.Forward(request); }
private void HandleGetItem(GetItemRequest request) { var item = items.SingleOrDefault(x => x.Id == request.Id); var message = item == null ? GetItemResponse.DoesNotExist(request.Id) : GetItemResponse.FromStore(item.Id, item.Code, item.Description, item.Value, item.ETag); Sender.Tell(message); }
public ContactsResponse ToContactContract(GetItemResponse response) { return(new ContactsResponse { Email = response.Item["Email"].S, Phone = response.Item["Phone"].S, FullName = response.Item["FullName"].S, }); }
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetItemResponse response = new GetItemResponse(); context.Read(); response.GetItemResult = GetItemResultUnmarshaller.GetInstance().Unmarshall(context); return response; }
public async Task <Team> GetAsync(string id, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); GetItemRequest getItem = DynamoDbParser.GetGetItemRequest(id); GetItemResponse responseItem = await client.GetItemAsync(getItem, cancellationToken); return(DynamoDbParser.GetTeam(responseItem)); }
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetItemResponse response = new GetItemResponse(); context.Read(); UnmarshallResult(context, response); return(response); }
public MovieResponse ToMovieContract(GetItemResponse response) { return(new MovieResponse { MovieName = response.Item["MovieName"].S, Description = response.Item["Description"].S, Actors = response.Item["Actors"].SS, Ranking = Convert.ToInt32(response.Item["Ranking"].N), TimeRanked = response.Item["RankedDateTime"].S }); }
private ImageMetadata ToImageMetadateDTO(GetItemResponse itemResponse) { var response = new ImageMetadata(); response.ImageMetadataId = itemResponse.Item[nameof(response.ImageMetadataId)].S; response.Length = itemResponse.Item[nameof(response.Length)].N; response.Width = itemResponse.Item[nameof(response.Width)].N; response.Height = itemResponse.Item[nameof(response.Height)].N; return(response); }
public liepa.rastija.lt.GetItemResult GetItem(int xmlId) { GetItemRequest inValue = new GetItemRequest(); inValue.Body = new GetItemRequestBody(); inValue.Body.xmlId = xmlId; GetItemResponse retVal = ((IRastijaService)(this)).GetItem(inValue); return(retVal.Body.GetItemResult); }
/// <summary> /// Llama al Data Core para el retorno del listado de los items, arma la entidad (json) que va a retornar /// </summary> /// <returns></returns> public static GetItemResponse getItems() { GetItemResponse response = new GetItemResponse(); response.items = ItemDC.getItems(); response.code = 100; response.message = "OK"; return(response); }
/** * Add a new country or update an existing one. */ public static async Task <bool> UpdateCountry(AmazonDynamoDBClient dbClient, string loggedInUserId, Country country) { Debug.Untested(); Debug.AssertValid(dbClient); Debug.AssertID(loggedInUserId); Debug.Assert(Helper.IsValidCountryCode(country.Code)); Debug.Assert(country.Currencies.Count > 0); // Check that the system is not locked. await SystemHelper.CheckSystemNotLocked(dbClient); // Get the existing country bool created = false; Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>(); key.Add(FIELD_COUNTRIES_CODE, new AttributeValue(country.Code)); GetItemResponse getResponse = await dbClient.GetItemAsync(DATASET_COUNTRIES, key); Debug.AssertValid(getResponse); Debug.AssertValidOrNull(getResponse.Item); if (getResponse.Item != null) { // The country exists so update it. Dictionary <string, AttributeValueUpdate> attributeUpdates = new Dictionary <string, AttributeValueUpdate>(); attributeUpdates.Add(FIELD_COUNTRIES_NAME, new AttributeValueUpdate(new AttributeValue(country.Name), AttributeAction.PUT)); attributeUpdates.Add(FIELD_COUNTRIES_CURRENCIES, new AttributeValueUpdate(new AttributeValue(country.Currencies), AttributeAction.PUT)); attributeUpdates.Add(FIELD_COUNTRIES_AVAILABLE, new AttributeValueUpdate(new AttributeValue { BOOL = country.Available }, AttributeAction.PUT)); UpdateItemResponse updateResponse = await dbClient.UpdateItemAsync(DATASET_COUNTRIES, key, attributeUpdates); Debug.AssertValid(updateResponse); //??++CHECK RESPONSE? } else { // The country does not exist so create it. Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>(); item.Add(FIELD_COUNTRIES_CODE, new AttributeValue(country.Code)); item.Add(FIELD_COUNTRIES_NAME, new AttributeValue(country.Name)); item.Add(FIELD_COUNTRIES_CURRENCIES, new AttributeValue(country.Currencies)); item.Add(FIELD_COUNTRIES_AVAILABLE, new AttributeValue { BOOL = country.Available }); PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_COUNTRIES, item); Debug.AssertValid(putResponse); //??++CHECK RESPONSE? created = true; } AddCountryAudit(dbClient, loggedInUserId, CountryAuditRecord.AuditChangeType.create, country); return(created); }
private ListChangeRequest DeserializeChangeRequest(GetItemResponse response) { var result = new ListChangeRequest( new Guid(response.Item["RequestId"].S), DateTime.Parse(response.Item["RequestDate"].S), response.Item["ProjectName"].S, response.Item["RequestedBy"].S, response.Item["Practice"].S, response.Item["ChangeType"].S, response.Item["Description"].S); return(result); }
public GetItemResponse GetItem(GetItemRequest request) { GetItemResponse viewModel = new GetItemResponse(); try { // If the list isn't configurated in the settings, the application will not show it if (!_configuration.ItemDetails.Any(il => il.ItemTypeOriginId.Equals(request.ItemTypeOriginId))) { throw new Exception(string.Format("{1}{2}", _localizationErrorKey, "DetailNotConfigurated")); } viewModel.Item = _dataContext.OR_Items .Where(i => i.OriginId.Equals(request.OriginId)) .Where(i => i.ItemTypeOriginId.Equals(request.ItemTypeOriginId)) .Select(i => new GetItemResponse.ItemDetails() { Id = i.Id, OriginId = i.OriginId, ItemTypeOriginId = i.ItemTypeOriginId, CreationDate = formatDate(i.CreationDate), LastEditDate = formatDate(i.LastEditDate), Properties = _dataContext.OR_Properties .Where(p => p.RelatedOriginId == i.OriginId) .Where(p => _configuration.ItemDetails .Single(il => il.ItemTypeOriginId.Equals(request.ItemTypeOriginId)) .VisibleFields.Select(vf => vf.Name) .ToList() .Contains(p.Name)) .Select(p => new GetItemResponse.Property() { Id = p.Id, OriginId = p.OriginId, Name = p.Name, Value = p.Value }) .OrderBy(p => p.Name) .ToList() }) .FirstOrDefault(); } catch (Exception exc) { viewModel.ResultInfo.Result = Base.ResultInfoDto.ResultEnum.Error; viewModel.ResultInfo.ErrorMessage = exc.Message; } return(viewModel); }
/** * Get an identity global setting database item by ID. */ internal static async Task <Dictionary <string, AttributeValue> > GetIdentityGlobalSettingDBItemByName(AmazonDynamoDBClient dbClient, string name) { Debug.Untested(); Debug.AssertValid(dbClient); Debug.AssertString(name); Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>(); key.Add(FIELD_IDENTITY_GLOBAL_SETTINGS_NAME, new AttributeValue(name)); GetItemResponse getResponse = await dbClient.GetItemAsync(DATASET_IDENTITY_GLOBAL_SETTINGS, key); Debug.AssertValid(getResponse); Debug.AssertValidOrNull(getResponse.Item); return(getResponse.Item); }
protected override GetItemJsonResponse CreateErrorResponse(Exception exception, ResponseCodeType codeType) { base.TraceError("GetItemAnonymous:CreateErrorResponse. Exception:{0}", new object[] { exception }); GetItemResponse getItemResponse = new GetItemResponse(); ServiceError error = new ServiceError(base.GetExceptionMessage(exception), codeType, 0, ExchangeVersion.Latest); getItemResponse.AddResponse(new ResponseMessage(ServiceResultCode.Error, error)); return(new GetItemJsonResponse { Body = getItemResponse }); }
/** * Get a link database item by ID. */ internal static async Task <Dictionary <string, AttributeValue> > GetLinkDBItemById(AmazonDynamoDBClient dbClient, string linkId) { Debug.Untested(); Debug.AssertValid(dbClient); Debug.AssertID(linkId); Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>(); key.Add(FIELD_LINKS_ID, new AttributeValue(linkId)); GetItemResponse getResponse = await dbClient.GetItemAsync(DATASET_LINKS, key); Debug.AssertValid(getResponse); Debug.AssertValidOrNull(getResponse.Item); return(getResponse.Item); }
/// <summary> /// Generic method to get model from a database /// </summary> /// <param name="RequestObj"></param> /// <param name="Table">Table Name</param> /// <returns></returns> private async Task <GetItemResponse> DefaultGetItem(Dictionary <string, AttributeValue> RequestObj, string Table) { try { GetItemRequest get = new GetItemRequest(Table, RequestObj); GetItemResponse Result = await DynamoClient.GetItemAsync(get); return(Result); } catch (Exception ex) { string err = ex.ToString(); return(null); } }
public GetItemResponse<NotificationItem> GetNotificationItem(IDRequest request) { try { var response = new GetItemResponse<NotificationItem>(); var service = ImardaProxyManager.Instance.IImardaCRMProxy; ChannelInvoker.Invoke(delegate(out IClientChannel channel) { channel = service as IClientChannel; response = service.GetNotificationItem(request); }); return response; } catch (Exception ex) { return ErrorHandler.Handle<GetItemResponse<NotificationItem>>(ex); } }
public GetItemResponse<ApplicationFeatureOwner> GetApplicationFeatureOwner(IDRequest request) { try { var response = new GetItemResponse<ApplicationFeatureOwner>(); var service = ImardaProxyManager.Instance.IImardaSecurityProxy; ChannelInvoker.Invoke(delegate(out IClientChannel channel) { channel = service as IClientChannel; response = service.GetApplicationFeatureOwner(request); }); return response; } catch (Exception ex) { return ErrorHandler.Handle<GetItemResponse<ApplicationFeatureOwner>>(ex); } }
public BusinessMessageResponse ProcessDeviceUpdate(ProcessDeviceUpdateRequest request) { var response = new BusinessMessageResponse(); try { GetItemResponse<Unit> unitResponse = new GetItemResponse<Unit>(); unitResponse = GetUnitByTrackID(new TrackIDRequest(request.Update.TrackID)); //unitResponse.Item.ID if (unitResponse.Item != null) { // Add Unit Trace UnitTrace unitTrace = new UnitTrace(); Update update = request.Update; unitTrace.OwnerID = unitResponse.Item.OwnerID; unitTrace.UnitID = unitResponse.Item.ID; unitTrace.CompanyID = unitResponse.Item.CompanyID; unitTrace.Active = true; unitTrace.ID = SequentialGuid.NewDbGuid(); unitTrace.SpeedKph = decimal.Parse(update.Speed); unitTrace.PeakSpeedKph = decimal.Parse(update.PeakSpeed); unitTrace.TrackID = update.TrackID; unitTrace.Hdop = byte.Parse(update.HDOP); float rssi; if (!float.TryParse(update.RSSI, out rssi)) rssi = 0f; unitTrace.Rssi = rssi; //unitTrace.MsgID = update.MessageID; /*if (unitTrace.MsgID = "I") { unitTrace.Ignition = true; } else { unitTrace.Ignition = false; }*/ unitTrace.IPAddress = update.Host; unitTrace.Direction = update.Direction; unitTrace.EventType = update.MessageType; unitTrace.Lat = decimal.Parse(update.Lat); //Replace with safe parse unitTrace.Lng = decimal.Parse(update.Lon); //Replace with safe parse unitTrace.DisplayDate = DateTime.UtcNow; unitTrace.GPSDate = DateTime.UtcNow; unitTrace.ReceivedDate = DateTime.UtcNow; SaveRequest<UnitTrace> saveRequest = new SaveRequest<UnitTrace>(); saveRequest.Item = unitTrace; response = SaveUnitTrace(saveRequest); } else { response.ErrorCode = "99"; response.Status = false; response.StatusMessage = "ProcessDeviceUpdate Failed"; } } catch { response.ErrorCode = "99"; response.Status = false; response.StatusMessage = "ProcessDeviceUpdate Failed"; } return response; /* request.Update. /*var response = new BusinessMessageResponse(); */ //UnitTrace_000 unittrace = new UnitTrace_000(); //unittrace.UnitID = request.Update.DeviceID; //SaveRequest<UnitTrace_000> saveRequest = new SaveRequest<UnitTrace_000>(); //saveRequest.Item = unittrace; // response = SaveUnitTrace_000(saveRequest); }
public GetItemResponse<SecurityEntity> GetSecurityEntityByLoginUserName(IDRequest request) { try { var response = new GetItemResponse<SecurityEntity>(); var db = ImardaDatabase.CreateDatabase(Util.GetConnName<SecurityEntity>()); string username = request.Get("username", string.Empty); using (IDataReader dr = db.ExecuteDataReader("SPGetSecurityEntityByLoginUserName", username,0)) { if (dr.Read()) { response.Item = GetFromData<SecurityEntity>(dr, false); } else { //failed to find login username response.Status = false; response.StatusMessage = "User name [" + username + "] was not found."; } return response; } } catch (Exception ex) { return ErrorHandler.Handle<GetItemResponse<SecurityEntity>>(ex); } }
public GetItemResponse<SessionObject> GetSessionObject(SessionRequest request) { var response = new GetItemResponse<SessionObject>(); LogonLog logonLog = new LogonLog(); logonLog.ID = SequentialGuid.NewDbGuid(); logonLog.ApplicationID = request.ApplicationID; logonLog.HostIPAddress = request.HostIPAddress; logonLog.FailureCode = AuthenticationResult.Undefined; logonLog.LoginUsername = request.Username.Truncate(50); try { SessionObject sessionObj = null; //look for session in cache, if exists return it. sessionObj = SessionObjectCache.Instance.GetSession(request.SessionID); if (sessionObj != null) { //we must clone otherwise wcf may mess up the channel return new GetItemResponse<SessionObject>(sessionObj.Clone()); } if (sessionObj == null) { if (request.SessionID != Guid.Empty) { _Log.InfoFormat("Session {0} not in cache", request.SessionID); //log the session expiry - this must be a seperate log with a sepereate id see IM-4806 LogonLog expiryLog = new LogonLog(); expiryLog.ID = SequentialGuid.NewDbGuid(); expiryLog.ApplicationID = request.ApplicationID; expiryLog.HostIPAddress = request.HostIPAddress; expiryLog.FailureCode = AuthenticationResult.Undefined; expiryLog.LoginUsername = request.Username.Truncate(50); expiryLog.Logon = LogonType.SessionExpired; expiryLog.SessionObjectID = request.SessionID; expiryLog.SecurityEntityID = request.SecurityEntityID; //companyid and userid are unknown SaveLogonLog(new SaveRequest<LogonLog>(expiryLog)); } SecurityEntity entity; bool impersonation = false; if (request.SecurityEntityID != Guid.Empty) { var seResponse = GetSecurityEntity(new IDRequest(request.SecurityEntityID)); ErrorHandler.Check(seResponse); entity = seResponse.Item; impersonation = true; logonLog.Logon = LogonType.Impersonation; if (entity != null) { logonLog.FailureCode = AuthenticationResult.Success; logonLog.LoginUsername = entity.LoginUsername; } else { logonLog.FailureCode = AuthenticationResult.Undefined; logonLog.LoginUsername = "******"; } } else { logonLog.FailureCode = Authenticate(request.Username, request.Password, request.Mode, request.EntityType, out entity); logonLog.Logon = LogonType.UserLogon; } string msg = string.Format("SecurityEntity: {0} for `{1}` -> {2}/{3}", entity, request.Username, logonLog.Logon, logonLog.FailureCode); _Log.Info(msg); response.StatusMessage = msg; if (entity == null) { response.Status = false; logonLog.FailureCode = AuthenticationResult.SecurityEntityNotFound; logonLog.Success = false; logonLog.SessionObjectID = Guid.Empty; logonLog.SecurityEntityID = Guid.Empty; } else { logonLog.CompanyID = entity.CompanyID; logonLog.SecurityEntityID = entity.ID; logonLog.UserID = entity.UserID; if (logonLog.FailureCode == AuthenticationResult.Success) { var permissionList = GetSecurityPermissionList(request.ApplicationID, entity) .ConvertAll<Guid>(permission => permission.SecurityObjectID); // Check if this it is the Imarda Admin Console trying to log in thru the provioning service // in that case Flags == 2, and the IAC login security object must be linked to the security entity of the user if (request.Mode == LoginMode.IAC && !permissionList.Contains(AuthToken.ImardaAdminServiceLogin)) { msg = string.Format("IAC login {0} failed, IAC permission for {1} not found", request.Username, entity); _Log.Info(msg); response.Status = false; response.StatusMessage = msg; logonLog.FailureCode = AuthenticationResult.IACPermissionNotFound; logonLog.Success = false; logonLog.SessionObjectID = Guid.Empty; SaveLogonLog(new SaveRequest<LogonLog>(logonLog)); return response; } sessionObj = new SessionObject { ApplicationID = request.ApplicationID, SessionID = Guid.NewGuid(), CRMID = entity.CRMId, SecurityEntityID = entity.ID, CompanyID = entity.CompanyID, Username = entity.LoginUsername, Password = entity.LoginPassword, PermissionsList = permissionList, Impersonation = impersonation, TimeZoneKey = entity.TimeZone, EntityName = entity.EntityName, EntityType = entity.EntityType, EnableTimeZoneSelect = entity.EnableTimeZoneSelect, }; logonLog.Success = true; logonLog.SessionObjectID = sessionObj.SessionID; SessionObjectCache.Instance.StoreSession(sessionObj); _Log.InfoFormat("Store new session: {0}", sessionObj); } } SaveLogonLog(new SaveRequest<LogonLog>(logonLog)); } return new GetItemResponse<SessionObject>(sessionObj) {ErrorCode = logonLog.FailureCode.ToString()}; // StatusMessage = response.StatusMessage}; } catch (Exception ex) { return ErrorHandler.Handle<GetItemResponse<SessionObject>>(ex); } }