How to call aspnet_UsersInRoles_IsUserInRole Stored Procedure with Dapper ORM - stored-procedures

I need to call aspnet_UsersInRoles_IsUserInRole from Aspnet Membership.Im making dapper call like this:
public int CheckIfUserIsInRole(IsUserInRole userInRole)
{
using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
{
DynamicParameters param = new DynamicParameters();
param.Add("#UserName", userInRole.UserName);
param.Add("#ApplicationName", userInRole.ApplicationName);
param.Add("#RoleName", userInRole.RoleName);
return connection.Query("aspnet_UsersInRoles_IsUserInRole", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
}
}
And in controller i add:
public int IsUserInRole(IsUserInRole isUserInRole)
{
var model = _userRepository.CheckIfUserIsInRole(new IsUserInRole()
{
UserName = "testuser",
RoleName = "user",
ApplicationName = "USERMANAGEMENT"
});
return model;
}
The user exist and have the correct role but every time returns 0.
Here is the Stored Procedure from AspNet Membership:
ALTER PROCEDURE [dbo].[aspnet_UsersInRoles_IsUserInRole]
#ApplicationName nvarchar(256),
#UserName nvarchar(256),
#RoleName nvarchar(256)
AS
BEGIN
DECLARE #ApplicationId uniqueidentifier
SELECT #ApplicationId = NULL
SELECT #ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(#ApplicationName) = LoweredApplicationName
IF (#ApplicationId IS NULL)
RETURN(2)
DECLARE #UserId uniqueidentifier
SELECT #UserId = NULL
DECLARE #RoleId uniqueidentifier
SELECT #RoleId = NULL
SELECT #UserId = UserId
FROM dbo.aspnet_Users
WHERE LoweredUserName = LOWER(#UserName) AND ApplicationId = #ApplicationId
IF (#UserId IS NULL)
RETURN(2)
SELECT #RoleId = RoleId
FROM dbo.aspnet_Roles
WHERE LoweredRoleName = LOWER(#RoleName) AND ApplicationId = #ApplicationId
IF (#RoleId IS NULL)
RETURN(3)
IF (EXISTS( SELECT * FROM dbo.aspnet_UsersInRoles WHERE UserId = #UserId AND RoleId = #RoleId))
RETURN(1)
ELSE
RETURN(0)
END
Where I'm mistaking?
Any advice how to fix it ?
I need this Stored Procedure to check if the user is in that role so i can use it for [AuthorizeRoles("RoleTest")]

That stored procedure doesn't return any records; it uses the return value instead. This needs to be handled as a parameter:
public int CheckIfUserIsInRole(IsUserInRole userInRole)
{
using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
{
DynamicParameters param = new DynamicParameters();
param.Add("#UserName", userInRole.UserName);
param.Add("#ApplicationName", userInRole.ApplicationName);
param.Add("#RoleName", userInRole.RoleName);
param.Add("#ReturnValue", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
connection.Execute("aspnet_UsersInRoles_IsUserInRole", param, commandType: CommandType.StoredProcedure);
return param.Get<int>("#ReturnValue");
}
}
https://github.com/StackExchange/dapper-dot-net#stored-procedures
(Also posted to your copy of this question on CodeProject.)

Related

am working on updating a single attribute in the User Model which is the balance attribute,

how I can update a single value for an already existing row in the db by only having a parameters that I want to add it to this attribute
here is my code for a trivial way but didnt work
public bool BuyBook(int BookId, int UserId, int BookPrice){
using (var ctx = new OnlineBooksEntities())
{
User updatedCustomer = (from c in ctx.Users
where c.UserId == UserId
select c).FirstOrDefault();
updatedCustomer.Balance = BookPrice;
ctx.SaveChanges();
}
this.DeleteBook(BookId);
return true;
}
Add an sql query to the method solves the update aim
public bool BuyBook(int BookId, int UserId, int BookPrice)
{
try
{
using (var ctx = new OnlineBooksEntities())
{
User user = ctx.Users.Where(x => x.UserId == UserId).FirstOrDefault();
BookPrice = (int)user.Balance + BookPrice;
int noOfRowUpdated =
ctx.Database.ExecuteSqlCommand("Update Users set Balance = "+BookPrice+ " where UserId ="+UserId);
}
Updating basically means changing an existing row's value. Since you mentioned EF, you can do this by retrieving the object, changing its value, and saving it back. Thus you can do something like this:
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookPrice == bookPrice);
if (result != null)
{
result.SomeValue = "Your new value here";
db.SaveChanges();
}
}

Xamarin Android, get contact mobile number by using CursorLoader with selection and selection args

I'm trying to get contact details of a contact that the user picks from the contacts list in Android using Intent as the following code:
Intent Intent = new Intent(Intent.ActionPick, ContactsContract.Contacts.ContentUri);
Intent.SetType(ContactsContract.Contacts.ContentType);
StartActivityForResult(Intent, 3);
Now on the Intent results I run the following code to get specific contact information:
public override void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 3 && resultCode == -1 && data != null) //result code -1 means OK 0 Means cancelled Result.Ok
{
var ContactData = data.Data;
string ID = "";
string name = "";
string address = "";
byte[] picture = new byte[0];
List<string> numbers = new List<string>();
List<string> emails = new List<string>();
string mobile = "";
string email = "";
string selectionString = "id = ?";
string[] columnsNames = new string[] {
ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName,
ContactsContract.Contacts.InterfaceConsts.PhotoUri
};
var loader = new CursorLoader(Statics.mainActivity, ContactData, null, null, null, null);
var cursor = (ICursor)loader.LoadInBackground();
if (cursor.MoveToFirst())
{
ID = cursor.GetString(cursor.GetColumnIndex(columnsNames[0]));
name = cursor.GetString(cursor.GetColumnIndex(columnsNames[1]));
picture = cursor.GetBlob(cursor.GetColumnIndex(columnsNames[2]));
}
//Store Contact ID
string[] selectionStringArgs = new string[] { ID };
//Phone Numbers
string[] columnsNames2 = new string[] {
ContactsContract.CommonDataKinds.Phone.Number
};
var loader2 = new CursorLoader(Statics.mainActivity, ContactsContract.CommonDataKinds.Phone.ContentUri, columnsNames2, selectionString, selectionStringArgs, null);
var cursor2 = (ICursor)loader2.LoadInBackground();
while (cursor2.MoveToNext())
{
numbers.Add(cursor2.GetString(cursor2.GetColumnIndex(columnsNames2[0])));
}
//Email Address
string[] columnsNames3 = new string[] {
ContactsContract.CommonDataKinds.Email.Address
};
var loader3 = new CursorLoader(Statics.mainActivity, ContactsContract.CommonDataKinds.Email.ContentUri, columnsNames3, selectionString, selectionStringArgs, null);
var cursor3 = (ICursor)loader3.LoadInBackground();
while (cursor3.MoveToNext())
{
emails.Add(cursor3.GetString(cursor3.GetColumnIndex(columnsNames3[0])));
}
int TempRecepitntID = 0;
EmployeesViewModel tempRecipent = new EmployeesViewModel();
TempRecepitntID = Statics.mainActivity.currentViewModel.SelectedChat.ReceiverEmployee;
foreach (EmployeesViewModel evm in Statics.mainActivity.currentViewModel.Employees)
{
if (evm.ID == TempRecepitntID)
tempRecipent = evm;
}
new Android.Support.V7.App.AlertDialog.Builder(Statics.mainActivity)
.SetPositiveButton("Yes", (sender1, args) =>
{
Statics.mainActivity.currentViewModel.AddMessage(picture, tempRecipent, Statics.mainActivity.currentViewModel.SelectedChat.ID, "contact", 0, "", name, numbers[0], mobile, email, address);
})
.SetNegativeButton("No", (sender1, args) =>
{
// cancel
})
.SetMessage("Are you shure you want to send?")
.SetTitle("System Message")
.Show();
}
}
The problem is I want to retrieve only the information of the contact that the user selected but what I get is all other contacts data is retrieved so I tried to use the selection and selectionargs parameters of CursorLoader by setting string selectionString = "id = ?"; and selectionArgs to string[] selectionStringArgs = new string[] { ID }; the ID value is retrieved from the following code :
if (cursor.MoveToFirst())
{
ID = cursor.GetString(cursor.GetColumnIndex(columnsNames[0]));
name = cursor.GetString(cursor.GetColumnIndex(columnsNames[1]));
picture = cursor.GetBlob(cursor.GetColumnIndex(columnsNames[2]));
}
//Store Contact ID
string[] selectionStringArgs = new string[] { ID };
//Phone Numbers
string[] columnsNames2 = new string[] {
ContactsContract.CommonDataKinds.Phone.Number
};
But now it returns 0 results, I couldn't find anything on the internet that applies to Xamarin android, Please help.
Thanks,
Finally I found the solution, I used the following string in the selection parameter of the cursorloader method:
string selectionString = ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId + "=" + ID;
and now only the selected contact numbers are retrieved.
I hope this will help someone else.
In additional information of #TMSL, I add the code afer this bloque
if (cursor.MoveToFirst())
{
ID = cursor.GetString(cursor.GetColumnIndex(columnsNames[0]));
name = cursor.GetString(cursor.GetColumnIndex(columnsNames[1]));
picture = cursor.GetBlob(cursor.GetColumnIndex(columnsNames[2]));
}
Here
selectionString = ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId + "=" + ID;
Then I changed the parameters used in the definition of variable Loader2, converting selectionStringArgs in null.
var loader2 = new CursorLoader(this.Activity, ContactsContract.CommonDataKinds.Phone.ContentUri, columnsNames2, selectionString, null,null);
var cursor2 = (ICursor)loader2.LoadInBackground();
I found this documentation from xamarin guides
Uri – The fully qualified name of the ContentProvider.
Projection – Specification of which columns to select for the cursor.
Selection – Similar to a SQL WHERE clause.
SelectionArgs – Parameters to be substituted in the Selection.
SortOrder – Columns to sort by.
So, the variable selectionStringArgs used in the code from #TMSAL cannot use a value like "contact_id = 2700", because the parameter of CursorLoader SelectionArgs is not a filter but not "Parameters to be substituted in the Selection"
I hope this will help someone else too.

Stored procedures with output parameters using SqlQuery in the DbContext API

I coulndt return output parameter from the query,here is the my codes
ETEntities en = new ETEntities();
var prm_TotalRecords = new SqlParameter
{
ParameterName = "totalrow",
SqlDbType=System.Data.SqlDbType.Int
,Direction= ParameterDirection.Output
};
var prm_start = new SqlParameter
{
ParameterName = "page",
Value = start,
SqlDbType=System.Data.SqlDbType.Int
};
var prm_sort= new SqlParameter
{
ParameterName = "msort",
SqlDbType = System.Data.SqlDbType.NVarChar,
Value = sort
};
var prm_limit = new SqlParameter
{
ParameterName = "size",
SqlDbType = System.Data.SqlDbType.Int,
Value = limit
};
string sql = "SP_PRODUCT_GET_PAGING #size,#page,#msort,#totalrow out";
object[] parameters = new object[] { prm_limit,prm_start,prm_sort,prm_TotalRecords};
var data = en.Database.SqlQuery<Urun>(sql,parameters);
// TotalRecords = (int)prm_TotalRecords.Value;//here is the give null error
TotalRecords = 3;
return data;
everrything is work fine if set 3 to TotalRecords manually,but this part gives me null error. TotalRecords = (int)prm_TotalRecords.Value;
how can I return the this value ,thank you

Adding a parameter to GetItems in DotNetNuke sample Module

Below is the code from the DotNetNuke Sample module that gets a collection of items from the database that belong to a particular module. What I want is add a second parameter for it filter by. I'm guessing this has something to do with modifying the scope item.cs class but am not sure how exactly.
public IEnumerable<Item> GetItems(int moduleId)
{
IEnumerable<Item> t;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Item>();
t = rep.Get(moduleId);
}
return t;
}
Any ideas?
Another way to do it in DAL2 is using the .Find() method. This is good if you want to query on an indexed field in your table and you don't care about caching scope:
public IEnumerable<Item> GetItemByName(int moduleId, string itemname)
{
IEnumerable<Item> t;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Item>();
t = rep.Find("WHERE ModuleId = #0 AND ItemName LIKE #1", moduleId, itemname);
}
return t;
}
Here's some sample code from my SignalRChat module that uses DAL2 (http://signalrchat.codeplex.com/SourceControl/changeset/view/71473#1272188)
public IEnumerable<Message> GetRecentMessages(int moduleId, int hoursBackInTime, int maxRecords)
{
var messages = (from a in this.GetMessages(moduleId) where a.MessageDate.Subtract(DateTime.UtcNow).TotalHours <= hoursBackInTime select a).Take(maxRecords).Reverse();
return messages.Any() ? messages : null;
}
That is one approach, you can also use a SQL statement within the controller as well (http://signalrchat.codeplex.com/SourceControl/changeset/view/71473#1272186)
public ConnectionRecord GetConnectionRecordByConnectionId(string connectionId)
{
ConnectionRecord t;
using (IDataContext ctx = DataContext.Instance())
{
var connections = ctx.ExecuteQuery<ConnectionRecord>(CommandType.Text,
string.Format(
"select top 1 * from {0}{1}SignalRChat_ConnectionRecords where ConnectionId = '{2}'",
_databaseOwner,
_objectQualifier,
connectionId)).ToList();
if (connections.Any())
{
t = connections[0];
}
else
return null;
}
return t;
}

Call a method in Linq to EF

In order to create a ViewModel, I tried to call a method GetName() to find the FirstName and LastName for UserID and then add it to the model. But the error tells "Linq to Entities does not recognize the method".
How do I accomplish this in another way?
My code:
public IQueryable<SheetList> GetSheetData()
{
var query = from a in GetSheets()
select new SheetList
{
SheetId = a.ListAllSafetySheets.Id,
SheetTitle = a.ListAllSafetySheets.SafetySheetTitle,
ProductionManagerId = a.ListAllSafetySheets.ProductionManager,
ProductionManagerName = this.GetName(a.ListAllSafetySheets.ProductionManager),
ConstructionManagerId = a.ListAllSafetySheets.ConstructionManager,
Created = a.ListAllSafetySheets.Created,
CreatedBy = a.ListAllSafetySheets.CreatedBy,
UserProfile_UserId = a.ListAllUserProfiles.UserId,
Project_Id = a.ListAllProjects.Id,
ProjectLeaderId = a.ListAllProjects.ProjectLeader,
ConstructionLocation_Id = a.ListAllConstructionLocations.Id,
};
return query;
}
public IQueryable<DataCollection> GetSheets()
{
var query = from vSafety in _db.Sheets
join vUserProfile in _db.UserProfiles
on vSafety.Id
equals vUserProfile.UserId
join vProject in _db.Projects
on vSafety.Id
equals vProject.Id
join vConstructionLocation in _db.ConstructionLocations
on vSafety.Id
equals vConstructionLocation.Id
orderby vSafety.Created descending
select new SafetyAndProjectAndUserAndLocationCollection
{
ListAllSafetySheets = vSafety,
ListAllUserProfiles = vUserProfile,
ListAllProjects = vProject,
ListAllConstructionLocations = vConstructionLocation
};
return query;
}
public string GetName(int? id)
{
string returnValue;
if (id == null)
{
var userModel = _db.UserProfiles.Single(x => x.UserId == id);
string FirstName = userModel.FirstName;
string LastName = userModel.LastName;
returnValue = FirstName + ", " + LastName;
}
else
{
returnValue = "";
}
return returnValue;
}
You'll need to call the method after you build the model. You can try something like this:
public IQueryable<SheetList> GetSheetData()
{
var query = from a in GetSheets()
select new SheetList
{
SheetId = a.ListAllSafetySheets.Id,
SheetTitle = a.ListAllSafetySheets.SafetySheetTitle,
ProductionManagerId = a.ListAllSafetySheets.ProductionManager,
ProductionManagerName = a.ListAllSafetySheets.ProductionManager,
ConstructionManagerId = a.ListAllSafetySheets.ConstructionManager,
Created = a.ListAllSafetySheets.Created,
CreatedBy = a.ListAllSafetySheets.CreatedBy,
UserProfile_UserId = a.ListAllUserProfiles.UserId,
Project_Id = a.ListAllProjects.Id,
ProjectLeaderId = a.ListAllProjects.ProjectLeader,
ConstructionLocation_Id = a.ListAllConstructionLocations.Id,
};
var queryWithNames = query.ToList().ForEach(s => s.ProductionManagerName = this.GetName(s.ProductionManagerName));
return queryWithNames;
}
Since you're having trouble using .ForEach(), you can do this with a regular foreach loop:
foreach(var s in query)
{
s.ProductionManagerName = this.GetName(s.ProductionManagerName);
}
The downside to this is the call to .ToList will enumerate the queryable, executing the query against the database, so if you need to do further filters later outside this method, you may be downloading additional data that you don't need, causing additional overhead.

Resources