cant retrieve data from firebase realtime in ASP.NET webforms C# - c#

I have login page in ASP.NET webforms using C#.
What I've tried is - this is my admin account model:
public class AdminAccount
{
public int Idno { get; set; }
public string Lname { get; set; }
public string Fname { get; set; }
public string Mname { get; set; }
public string Bdate { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string WRS_Name { get; set; }
public string Pass { get; set; }
public string Proof { get; set; }
}
My account.aspx.cs:
public void btnLogin_Click(object sender, EventArgs e)
{
// Get the email and password entered by the user
string username = txt_username.Text;
string password = txt_password.Text;
// Check if the email and password are valid
FirebaseResponse response;
response = twoBigDB.Get("ADMIN/" + username);
Model.AdminAccount obj = response.ResultAs<Model.AdminAccount>();
if (obj.Username == username && obj.Pass == password)
{
Session["username"] = username;
Session["password"] = password;
Session["WRSname"] = obj.WRS_Name;
// Login successful, redirect to admin homepage
Response.Redirect("/Admin/AdminIndex.aspx");
}
else
{
Response.Write("<script>alert('Invalid username or password');</script>");
}
}
My expected output is inside my if condition would be true, Username can fetch data from firebase realtime and with username input by the user.

Related

Saving data in the database using Entity Framework

I am trying to save data in the database using Entity Framework and this code, but I keep getting this error:
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at GDEProject.Pages.Profile.Update_Click(Object sender, EventArgs e) in
C:\Users\RATAU\Documents\Projects\GDEProject\GDEProject\GDEProject\Pages\Profile.aspx.cs:line 48
This is the code I am using:
public partial class Profile : System.Web.UI.Page
{
Entities2 db = new Entities2();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Update_Click(object sender, EventArgs e)
{
if (ModelState.IsValid)
{
try
{
PROFILE user = new PROFILE();
user.IdNumber = IdNumber.Text;
user.PersalNumber = ParselNumber.Text;
user.Title = Title.Text;
user.Initials = Initial.Text;
user.Name = FirstName.Text;
user.Surname = LastName.Text;
user.Age = Age.Text;
user.Race = Race.Text;
user.EmailAddress = Email.Text;
user.CellPhone = Phonenumber.Text;
user.TelephoneNumber = Telephone.Text;
user.Nationality = dropNationality.SelectedValue.ToString();
user.Gender = dropGender.SelectedValue.ToString();
user.Disability = Disability.SelectedValue.ToString();
user.DisabilityType = DisabilityType.Text;
db.PROFILEs.Add(user);
db.SaveChanges();
ErrorMessage.Text = "saved";
}
catch (Exception ee)
{
ErrorMessage.Text = ("error" + ee);
}
}
else
{
ErrorMessage.Text="modelstate failed";
}
}
the class of profile is as follows:
public partial class PROFILE
{
public string Nationality { get; set; }
public string IdNumber { get; set; }
public string PersalNumber { get; set; }
public string Title { get; set; }
public string Initials { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Race { get; set; }
public string Language { get; set; }
public string EmailAddress { get; set; }
public string CellPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Disability { get; set; }
public string DisabilityType { get; set; }
public string Message { get; set; }
}
}
Please assist

How to add mention to slack attachment message?

I am using this example to upload message with attachment to slack:
How to upload any file on Slack via Slack-App in c#
I want to add user mention to the text variable.
I used both format id and name version but it didn't work.
It displays as plain text with no notification to users
parameters3["text"] = "<#userName>";
update:
public class SlackAttachment
{
public string fallback { get; set; }
public string color { get; set; }
public string pretext { get; set; }
public string author_name { get; set; }
public string author_link { get; set; }
public string author_icon { get; set; }
public string title { get; set; }
public string title_link { get; set; }
public string text { get; set; }
public string image_url { get; set; }
public string thumb_url { get; set; }
public string footer { get; set; }
public string mrkdwn_in {get; set;}
public string footer_icon { get; set; }
}
// a slack file class
class SlackFile
{
public String id { get; set; }
public String name { get; set; }
public String permalink_public { get; set; }
public string permalink { get; set; }
}
// reponse from file methods
class SlackFileResponse
{
public bool ok { get; set; }
public String error { get; set; }
public SlackFile file { get; set; }
}
// reponse from message methods
class SlackMessageResponse
{
public bool ok { get; set; }
public String error { get; set; }
public String channel { get; set; }
public String ts { get; set; }
}
this is my caller
public static void salesCongrat(string imgUrl, string msg)
{
string postedMessage = "Outside message text";
var sampleAttachment = new SlackAttachment[]
{
new SlackAttachment {
fallback = "browser cannot display this",
text = "<#UEMTUFSM>",
color = "e5345e",
pretext = "",
author_name = " ",
author_icon = "",
author_link = "",
title = msg,
title_link = "",
mrkdwn_in = "[\"text\"]",
image_url= imgeuURL,
footer = $"Posted at {DateTime.Now.Day}/" +
$"{DateTime.Now.Month}/{DateTime.Now.Year}/ " +
$"{DateTime.Now.Hour}:{DateTime.Now.Minute }",
footer_icon = ""
},
};
var attachmentsJson = JsonConvert.SerializeObject(sampleAttachment);
var data = new NameValueCollection();
data["token"] = myToken;
data["channel"] = channelName;
data["as_user"] = "true";
data["text"] = postedMessage;
data["attachments"] = attachmentsJson;
var client = new WebClient();
var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
Console.WriteLine(responseInString);
}
file response :
{"ok":true,"channel":"","ts":"","message":{"bot_id":"","type":"message","text":"Outside message text","user":"","ts":"","attachments":[{"author_name":" ","fallback":"browser cannot display this","text":"<#>","title":" ","footer":"Posted at 1\/4\/2019\/ 18:47","id":1,"color":"e5345e"}]}}
Your code is posting the mention ("<#アユ三君>", lets assume its a user ID) in the main message, but not in the attachment as your title suggests.
To include the mention in the attachment you need to put it in the initialization for your attachment object.
Examples:
var sampleAttachment = new SlackAttachment[]
{
new SlackAttachment
{
fallback = "browser cannot display this",
text = "<#U12345678>",
color = "e5345e",
title = msg,
image_url = imgeURL,
footer = $"Posted at {DateTime.Now.Day}"
}
};
Your mention will be empty and shown with a "private user info" tool tip, when Slack can not find the user ID. To double-check that your user ID is valid you can call users.list in your browser to get a list of all existing user Ids. Make sure to use the same token, that you are using in your app.
Example:
https://slack.com/api/users.list?token=MYTOKEN

Checking if the object passed in to an Interface param has an additional property

I have two User classes, User, and TenantUser that implement an IUser interface:
public interface IUser
{
int Id { get; set; }
string Username { get; set; }
string Email { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
}
public class User : IUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class TenantUser : IUser
{
public int Id { get; set; }
public int TenantId { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
The only difference is that TenantUser has one extra property: TenantId
When I am coding I am doing something like the following:
IUser user;
user = getAdminUser("username", "password");
if (user == null)
{
user = getTenantUser("username", "password");
if (user == null)
return Unauthorized();
}
Then when I proceed with my code I will need to check if TenantId is a property on the user object, if it, is get the value. Is this possible?
You could add TenantId to another interface and implement it in the TenantUser. Then just try to cast to that interface:
Given:
interface ITenant
{
int TenantId { get; set; }
}
public class TenantUser : IUser, ITenant
{ ... }
You can do:
if(user is ITenant tenant)
{
// access tenant.TenantId
}

Model doesn't accept its value

This code doesn't accept the values I give with the user's department data. If i replace user.Department.ID with just a simple int variable, it works fine. This is also the problem with user.Department.Code and user.Department.Title. I don't know what's the problem. Is it in my models?
This is the code. The system queries for the user data. I believe that the query is fine. I'm using a connection string with MS Access btw.
try
{
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
UserModel user = new UserModel();
if (!reader.IsDBNull(0))
{
user.Id = reader.GetInt32(0);
}
if (!reader.IsDBNull(1))
{
user.Department.Id = reader.GetInt32(1);
}
if (!reader.IsDBNull(2))
{
user.Department.Code = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
user.Department.Title = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
user.FamilyName = reader.GetString(4);
}
if (!reader.IsDBNull(5))
{
user.GivenName = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
user.MiddleName = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
user.NameSuffix = reader.GetString(7);
}
if (!reader.IsDBNull(8))
{
user.Type = reader.GetString(8);
}
CurrentUser = user;
CanLogin = true;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception Error");
}
Here is my Usermodel...
class UserModel
{
public int Id { get; set; }
public DepartmentModel Department { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string NameSuffix { get; set; }
public string Type { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName(bool isFamilyNameFirst)
{
StringBuilder fullname = new StringBuilder();
if(isFamilyNameFirst)
{
fullname.Append(FamilyName).Append(", ").Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(NameSuffix);
}
else
{
fullname.Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(FamilyName).Append(" ").Append(NameSuffix);
}
return fullname.ToString();
}
}
And my Department Model..
class DepartmentModel
{
public int Id { get; set; }
public InstitutionModel Institution { get; set; }
public string Code { get; set; }
public string Title { get; set; }
}
The Department property never initialize any where, you an do it in user constructor:
class UserModel
{
public UserModel()
{
this.Department = new DepartmentModel();
}
public int Id { get; set; }
public DepartmentModel Department { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string NameSuffix { get; set; }
public string Type { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName(bool isFamilyNameFirst)
{
StringBuilder fullname = new StringBuilder();
if(isFamilyNameFirst)
{
fullname.Append(FamilyName).Append(", ").Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(NameSuffix);
}
else
{
fullname.Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(FamilyName).Append(" ").Append(NameSuffix);
}
return fullname.ToString();
}
}
Or
UserModel user = new UserModel() {Department = new DepartmentModel()};

MVC 5 GetUserId() returns null

I have created a custom User class implementing IUser.
When I register everything completes fine, the tables are created (if they don't exist) and all looks ok, but, as the subject states, I cannot get User.GetUserId() to work.
It always returns null which is really annoying.
Here is my User class:
public class User : IUser
{
public User()
{
this.LastLoginDate = DateTime.UtcNow;
this.DateCreated = DateTime.UtcNow;
}
public User(string userName)
{
this.Id = Guid.NewGuid().ToString();
this.UserName = userName;
this.CreatedBy = this.Id;
this.LastLoginDate = DateTime.UtcNow;
this.DateCreated = DateTime.UtcNow;
this.IsApproved = true;
}
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredUserName")]
public string UserName { get; set; }
public string Id { get; set; }
[Required] public string CompanyId { get; set; }
[Required] public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public DateTime LastLoginDate { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredTitle")]
public string Title { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredFirstName")]
public string Forename { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredLastName")]
public string Surname { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredEmail")]
public string Email { get; set; }
public string JobTitle { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public string Photo { get; set; }
public string LinkedIn { get; set; }
public string Twitter { get; set; }
public string Facebook { get; set; }
public string Google { get; set; }
public string Bio { get; set; }
public string CompanyName { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredCredentialId")]
public string CredentialId { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredSecurityCode")]
public bool IsLockedOut { get; set; }
public bool IsApproved { get; set; }
[Display(Name = "Can only edit own assets")]
public bool CanEditOwn { get; set; }
[Display(Name = "Can edit assets")]
public bool CanEdit { get; set; }
[Display(Name = "Can download assets")]
public bool CanDownload { get; set; }
[Display(Name = "Require approval to upload assets")]
public bool RequiresApproval { get; set; }
[Display(Name = "Can approve assets")]
public bool CanApprove { get; set; }
[Display(Name = "Can synchronise assets")]
public bool CanSync { get; set; }
public bool AgreedTerms { get; set; }
public bool Deleted { get; set; }
}
public class UserContext : IdentityStoreContext
{
public UserContext(DbContext db)
: base(db)
{
this.Users = new UserStore<User>(this.DbContext);
}
}
public class UserDbContext : IdentityDbContext<User, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
Here is my Register function:
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Create a profile, password, and link the local login before signing in the user
var companyId = Guid.NewGuid().ToString();
var user = new Skipstone.Models.User(model.UserName)
{
CompanyId = companyId,
Title = model.Title,
Forename = model.Forename,
Surname = model.Surname,
Email = model.Email,
CompanyName = model.CompanyName,
CredentialId = model.CredentialId
};
if (await IdentityStore.CreateLocalUser(user, model.Password))
{
// Create our company
var company = new Company()
{
Id = companyId,
CreatedBy = user.Id,
ModifiedBy = user.Id,
Name = model.CompanyName
};
using (var service = new CompanyService())
{
service.Save(company);
}
await AuthenticationManager.SignIn(HttpContext, user.Id, isPersistent: false);
var test = User.Identity.IsAuthenticated; // returns true
var u = User.Identity.GetUserId(); // returns null
return RedirectToAction("Setup", new { id = companyId });
}
else
{
ModelState.AddModelError("", "Failed to register user name: " + model.UserName);
}
}
catch (IdentityException e)
{
ModelState.AddModelError("", e.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
var test returns true, so it knows the user is now logged in.
var u is null, so User.Identity.GetUserId() is not working as it should.
Does anyone have any idea why?
I can post more code on request :)
Update 1
By creating a fresh project and testing with defaults, I have found that called User.Identity returns null when in the Register method.
But in the fresh project, calling it anywhere else returns the right information, but in my project I get null for everything.
Update 2
It is definately related to the custom User class.
I created one on my fresh project and the same thing happens.
So, something is wrong :) now I just have to figure out what!?!
I assume somewhere in your project there is a row of database connection initialization, something like this:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true)
So, make sure that you use "Id" instead of "UserId" in this line

Categories