How to get the userID of a logged in user? - asp.net-mvc-3

I'm trying to get the userid of the currently logged in user. Here is my code:
public int GetUserID(string _UserName)
{
using (var context = new TourBlogEntities1())
{
var UserID = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return Int32.Parse(UserID.ToString()); //error is showing here
}
}
I'm calling the method from my controller using this:
public ActionResult NewPost(NewPost model)
{
var Business = new Business();
var entity = new Post();
entity.PostTitle = model.PostTitle;
entity.PostStory = model.PostStory;
entity.UserID = Business.GetUserID(User.Identity.Name);
Business.NewPost(entity);
Business.ViewPost(entity);
return View("ViewPost", model);
}
The error is showing as "input string is not in correct format". Please help. Thanks.

Your query returns an IEnumerable. You need to get only the single record:
using (var context = new TourBlogEntities1())
{
var userIds = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return userIds.Single();
}
By the way the .Single() method will throw an exception if there are more than 1 records matching the criteria. Hopefully you have an unique constraint on the Username field inside your database.

CreatedBy = this.HttpContext.User.Identity.Name,

Related

Oracle sequence EF Core 6.0?

I need to get a NEXTVAL from a SEQUENCE in an Oracle database. The modelbuilder does have a
builder.HasSequence("TABLE_SEQ");
But I have no clue on how to use that. The only way I can think of is scalar executing a raw SQL to retrieve the next value. Is that the way to go or are there better ways to do this?
I've found several posts that say I should use context.Database.SqlQuery() but in my solution that is missing. Do I need to add a library to get this functionality for EF 6.0?
Examples I found:
Example 1:
public int GetNewCertificateTradeRequestIdentity()
{
using var command = _context.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT ts.seq_certificate_trade_request.NEXTVAL FROM DUAL";
_context.Database.OpenConnection();
using var reader = command.ExecuteReader();
reader.Read();
return reader.GetInt32(0);
}
Example 2:
users = await context.Database.SqlQuery<User>("Select * from User", new object[] { }).ToListAsync();
Both the _context.Database.GetDbConnection() context.Database.SqlQuery<x> are missing. Where can I find them?
Ok, in EF6 you have the context.Database.GetDbConnection().CreateCommand(). With that command you can execute a query on the database and receive the result. I've also found a solution for getting the tablename from the EF6 Metadata and added an extension method to handle that. Now I can do the the following:
private Tijdverantwoording Create(decimal? mdwid, decimal? deelprjid, Datum? date)
{
if (mdwid == null || deelprjid == null || date == null) throw new ArgumentNullException();
Weekstaatstatus weekstaatStatus = _WeekstaatStatusService.GetOrCreate(mdwid.Value, date.Jaarweekcode, WeekStaatStatussen.InBewerking, DateTime.Now);
var tijdverantwoording = new Tijdverantwoording
{
Tijdverantwoordingid = GetId<Tijdverantwoording>(), // <= Generate id
Mdwid = mdwid.Value,
Deelprjid = deelprjid.Value,
Datum = date.DagDatum,
Syncstatus = (decimal)SyncStatuses.InBewerking,
Syncdate = DateTime.Now.Date,
Weekstaatstatusid = weekstaatStatus.Weekstaatstatusid
};
_modelContext.Tijdverantwoordingen.Add(tijdverantwoording);
return tijdverantwoording;
}
The base class used for a service.
using Microsoft.EntityFrameworkCore;
using MyProjects.Core.Extensions;
using MyProjects.Core.Model;
namespace MyProjects.Core.Services
{
public class ServiceBase
{
private ModelContext? _modelContext;
public ServiceBase(ModelContext modelContext)
{
_modelContext = modelContext;
}
public decimal GetId<T>()
where T : class
{
var command = _modelContext.Database.GetDbConnection().CreateCommand();
var tableName = _modelContext.TableName(typeof(T));
command.CommandType = System.Data.CommandType.Text;
command.CommandText = $"SELECT {tableName}_SEQ.NEXTVAL FROM DUAL";
_modelContext.Database.OpenConnection();
try
{
var result = (decimal?)command.ExecuteScalar();
return result.Value;
}
finally
{
_modelContext.Database.CloseConnection();
}
}
}
}
And the extension method
using Microsoft.EntityFrameworkCore;
namespace MyProjects.Core.Extensions
{
public static class DatabaseExtensions
{
public static string? TableName(this DbContext context, Type type)
{
var entityType = context.Model.FindEntityType(type);
return entityType?.GetTableName() ?? throw new NullReferenceException($"Can't find name for type {type.Name}");
}
}
}

Handling Null in MVC Model

I am facing DateTime null Error. My data comes from SQL server through stored procedures in MVC project. In MVC, Employee model receive the data in List and pass it to the View through the Employee Controller. Following is the code:
public List<Employee> GetEmployeesByUserName(string username)
{
SqlConnection conn = new SqlConnection(Startup.MTSConn);
List<Employee> empList = new List<Employee>();
using (conn)
{
using (SqlCommand cmd = new SqlCommand("spRetrievEmployeesByUserName", conn))
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#Username", username);
DataTable dt = new DataTable();
conn.Open();
adapter.Fill(dt);
//Convert Data to List
foreach (DataRow row in dt.Rows)
{
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
**DOB = row["DOB"]==DBNull ? DBNull : Convert.ToDateTime(row["DOB"])**
Here I want to check if the field is null then return null otherwise convert it to DateTime. In employee model it is already set to null 'public DateTime? DOB { get; set; }'
});
}
}
return empList;
}
}
I advise you to use entity to get the data from the database. However, to tackle this issue try do something like this
foreach (DataRow row in dt.Rows)
{
if (row["DOB"] != null)
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
**DOB = row["DOB"].Convert.ToDateTime()**
}
else
{
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
DOB = null
}

How to get a CNContact phone number(s) as string in Xamarin.ios?

I am attempting to retrieve the names and phone number(s) of all contacts and show them into tableview in Xamarin.iOS. I have made it this far:
var response = new List<ContactVm>();
try
{
//We can specify the properties that we need to fetch from contacts
var keysToFetch = new[] {
CNContactKey.PhoneNumbers, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses
};
//Get the collections of containers
var containerId = new CNContactStore().DefaultContainerIdentifier;
//Fetch the contacts from containers
using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
{
CNContact[] contactList;
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysToFetch, out
var error);
}
//Assign the contact details to our view model objects
response.AddRange(from item in contactList
where item?.EmailAddresses != null
select new ContactVm
{
PhoneNumbers =item.PhoneNumbers,
GivenName = item.GivenName,
FamilyName = item.FamilyName,
EmailId = item.EmailAddresses.Select(m => m.Value.ToString()).ToList()
});
}
BeginInvokeOnMainThread(() =>
{
tblContact.Source = new CustomContactViewController(response);
tblContact.ReloadData();
});
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
and this is my update cell method
internal void updateCell(ContactVm contact)
{
try
{
lblName.Text = contact.GivenName;
lblContact.Text = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
//var no = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
//NSString a = new NSString("");
// var MobNumVar = ((CNPhoneNumber)contact.PhoneNumbers[0]).ValueForKey(new NSString("digits")).ToString();
var c = (contact.PhoneNumbers[0] as CNPhoneNumber).StringValue;
}
catch(Exception ex)
{
throw ex;
}
}
I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value.
this line of code
lblContact.Text = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
throw a run time exception as specified cast is not valid
Yes, exception is correct. First of all, you don't need any casts at all, contact.PhoneNumbers[0] will return you CNLabeledValue, so you just need to write it in next way
lblContact.Text = contact.PhoneNumbers[0].GetLabeledValue(CNLabelKey.Home).StringValue
//or
lblContact.Text = contact.PhoneNumbers[0].GetLabeledValue(CNLabelPhoneNumberKey.Mobile).StringValue
or you may try, but not sure if it works
contact.PhoneNumbers[0].Value.StringValue
I got solution. Here is my code if any one required.
CNLabeledValue<CNPhoneNumber> numbers =
(Contacts.CNLabeledValue<Contacts.CNPhoneNumber>)contact.PhoneNumbers[0];
CNPhoneNumber number = numbers.Value;
string str = number.StringValue;
lblContact.Text = str;

How to receive response from server in Xamarin.Forms

I have created an HTTP Client that sends data to my server. This data will query my server that will return a JSON object. How can I receive the JSON Object response from my server and insert it into my database?
The code below will send a ContactID to my server and my server will return a JSON Object How can I get the JSON Object from my server? What will I add to my code? I have added
var data = await response.Content.ReadAsStringAsync();
but I don't know how to proceed.
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var sql = "SELECT * FROM tblUser WHERE ContactID = '" + contact + "'";
var getUser = conn.QueryAsync<UserTable>(sql);
var resultCount = getUser.Result.Count;
//Check if the user has been sync
if (resultCount < 1)
{
try
{
syncStatus.Text = "Syncing user to server...";
var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=8qApc8";
string contentType = "application/json";
JObject json = new JObject
{
{ "ContactID", contact }
};
HttpClient client = new HttpClient();
var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
var data = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var userresult = JsonConvert.DeserializeObject<IList<UserData>>(content);
var count = userresult.Count;
for (int i = 0; i < count; i++)
{
try
{
syncStatus.Text = "Syncing user to server...";
var item = userresult[i];
var contactID = item.ContactID;
var userID = item.UserID;
var userPassword = item.UserPassword;
var userType = item.UserType;
var userStatus = item.UserStatus;
var lastSync = item.LastSync;
var serverUpdate = item.ServerUpdate;
var mobileUpdate = item.MobileUpdate;
var user = new UserTable
{
ContactID = Convert.ToInt32(contactID),
UserID = userID,
UserPassword = userPassword,
UserType = userType,
UserStatus = userStatus,
LastSync = lastSync,
ServerUpdate = serverUpdate,
MobileUpdate = mobileUpdate
};
await conn.InsertAsync(user);
}
catch (Exception ex)
{
Console.Write("Syncing user error " + ex.Message);
}
}
}
}
catch (Exception ex)
{
Console.Write("Syncing User Error " + ex.Message);
}
}
My PHP code will query my database with the ContactID received from Xamarin HTTP Client.
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$ContactID = $json_obj->ContactID;
$sql = "SELECT * FROM tblUser WHERE ContactID = '$ContactID'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while ($row = #mysqli_fetch_array($result)) {
$decr = CryptRC4(FromHexDump($row['UserPassword']), $key);
$ar[] = array(
'ContactID' => $row['ContactID'],
'UserID' => $row['UserID'],
'UserPassword' => $decr,
'UserType' => $row['UserType'],
'UserStatus' => $row['UserStatus'],
'LastSync' => $sync,
'ServerUpdate' => $row['ServerUpdate'],
'MobileUpdate' => $row['MobileUpdate']
);
print json_encode($ar);
//Update LastSync DateTime
$sql = "UPDATE tblUser SET LastSync = '$sync' WHERE ContactID = '$ContactID'";
mysqli_query($conn, $sql);
}
}
Last statement in your example above gives list of json objects in string format.
var data = await response.Content.ReadAsStringAsync();
You need to convert that back to list of objects. To let your project know about definition of the object, create a plain class with public properties (Something like below)
public class UserLog
{
public int ContactId { get; set; }
public string Log { get; set; }
public DateTime LogDate { get; set; }
}
Add Newtonsoft.Json (by James Newton-King) Nuget package to your project so that you can work with json.
To convert content of the variable 'data' into list of UserLog objects, write code like
var list = NewtonsoftUtil<IList<UserLog>>.DeserializeObject(data);
(Add using Newtonsoft.Json; at top of the file)
Please let me know if this helps.
The answers above missing one important point -> efficiency.
There is no need to allocate a string in memory, especially if your JSON is big. Streams can do much better then strings:
// Read the response as stream
var stream = await response.Content.ReadAsStreamAsync();
// Use the next method for deserialization
T DeserializeJsonFromStream<T>(Stream stream)
{
if (stream == null || stream.CanRead == false)
return default(T);
using (var sr = new StreamReader(stream))
using (var jtr = new JsonTextReader(sr))
{
var js = new JsonSerializer();
return js.Deserialize<T>(jtr);
}
}
P.S.: Code example is bases on Json.NET.
P.S.S.: There are many good articles on this topic, I could recommend to get familiar with the next one.
Assuming that you have done everything correctly. In other words, You're be able to sent your contactID and get back a json.
Let's say your json structure is something like:
{"firstname" : "Doe",
"lastname" : "foo"
"age" : "27"}
One possible way to retrieve the data is as below:
using Newtonsoft.Json;
//after PostAsync()
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
JObject jContent = (JObject)JsonConvert.DeserializeObject(content);
string firstName = (string)jContent.GetValue("firstname")
string lastName = (string)jContent.GetValue("lastname");
int age = (int)jContent.GetValue("age");
}
Newtonsoft is available on Nuget. you need to install it if you have not done so.
Improved solution
What if your json has many key/values pairs like below:
{ key1 : value1,
key2 : value2,
key3 : value3,
...
key10 : value10}
Then it is not a good idea by doing :
string foo1 = (string)jContent.GetValue("key1");
string foo2 = (string)jContent.GetValue("key2");
//...
string foo10 = (string)jContent.GetValue("key10");
To handle this case, you can create a class:
public class Foo
{
public string Foo1 {get;set;}
public string Foo2 {get;set;}
//...
public string Foo2 {get;set;}
}
Then, you can do as simple as below:
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Foo foo = JsonConvert.DeserializeObject<Foo>(content);
}
The improved solution referecnced from www.newtonsoft.com. Go there and check out other ways of using the library.

using LINQ update particular column in asp.net mvc 3

I have following code for updating user's column
public void UpdateLastModifiedDate(string username)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
dbuser.LastModifiedDate = DateTime.Now;
db.SaveChanges();
}
}
}
I have other's 2 function of almost same of above function for UpdateLastLogOutDate, UpdateLastLoginDate. So, I decided to define single function for all to update Last Date like:
public void UpdateLastDate(string username, string ColumnName);
Here, I can not put ColumnName variable like this:
dbuser.ColumnName = DateTime.Now;
Is there any other way to do this using LINQ
You could define the method like this:
public void Update(string username, Action<User> action)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
action(dbuser);
db.SaveChanges();
}
}
}
And now there could be different usages of this method:
Update("john", user => user.LastModifiedDate = DateTime.Now);
Update("smith", user => user.UpdateLastLogOutDate = DateTime.Now);
Update("admin", user =>
{
user.LastModifiedDate = DateTime.Now;
user.UpdateLastLogOutDate = DateTime.Now;
});
But if the expression is not known at compile time you may take a look at dynamic LINQ.
You could write your code this way also by sending an instance of your entity as parameter:
public void UpdateLastModifiedDate(Entityclassname ent) //[like if table name is item then Entityclassname should be items etc..]
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == ent.username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
dbuser.LastModifiedDate = DateTime.Now;
dbuser.UpdateLastLogOutDate=ent.UpdateLastLogOutDate ;
db.SaveChanges();
}
}
}

Resources