Getting a value from one table to pull up values from another table - asp.net-mvc

I am trying to lookup an employeeid from one table based on the windows login name, and use this employeeid to get values from another table to add them up. So, for Bill, the employeeid is 1 in tblEmployees. I sum all noofhours in tblTimeAvailable where employeeid equals 1 and display this on my webpage. It's not working. I can't figure out how to search the second table by the employeeid found in the first table. (I'm rewriting code because of sql injection.)
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
con.Open()
rve = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
End Using
When I look at value of rve, it's giving me #loginname and not the employeeid. FYI - there will always be only one row in tblEmployees because each Windows login name is unique.
'Get Sick Time
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #employeeid"
Dim command As New SqlCommand(sqls1, con)
con.Open()
rvsa = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#employeeid", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
End Using
' If the sum equals 0, show 0 on webpage. If another value, show value.
If IsDBNull(rvsa) Then
rvsa = 0
TextBoxsa.Text = 0
Else
TextBoxsa.Text = rvsa.ToString
End If
I appreciate any help you can give me!

You are never executing the command. After setting the values of the various parameters, you need to then call one of the execute methods on the SqlCommand object. In this case, since you are just reading a single value from a single row, you can simply use the ExecuteScalar method:
rve = command.ExecuteScalar()

Related

How do I get User's Role within code portion of _LoginPartial?

I am using MVC Entity Framework and I need to get a user's role within the _LoginPartial for some role-specific functionality within the nav bar. What is the best way to get that there?
I've tried using Dim myRoles = Roles.GetRolesForUser(), but that comes up with nothing. Which is wrong, because I use role-specific functionality elsewhere and that works fine.
Following the link in Marco's comment, it mentions using ClaimsIdentity, but for me it says ClaimsIdentity is not declared (Rick left a comment there this past August explaining it's not working for him like something changed in the past 2 years).
I had also tried this, which is similar to code in a controller I have elsewhere which does work:
Dim context As IOwinContext = New OwinContext
Dim manager = New AppUserManager(New UserStore(Of AppUser(context.Get(Of MyAppIdentityDbContext)()))
Dim userInfo = manager.FindById(curUserID)
Dim userRole As String = userInfo.Roles(0).RoleId
myRole = db.Roles.Where(Function(x) x.Id = userRole).FirstOrDefault().Name
But at runtime I get an error on the "Dim manager" line that says
An exception of type 'System.ArgumentNullException' occurred in
Microsoft.AspNet.Identity.EntityFramework.dll but was not handled in
user code Additional information: Value cannot be null.
I have no idea what value it's talking about.
Thanks to Marco's help and the other question he linked, I got it using the following code:
#Imports Microsoft.AspNet.Identity
#Imports System.Security.Claims
#Code
Dim db = New MyAppIdentityDbContext
Dim curUserID = User.Identity.GetUserId()
Dim myFirstName As String = (From users In db.Users Where users.Id = curUserID Select users.FirstName).FirstOrDefault
Dim myRole As String = ""
If curUserID IsNot Nothing AndAlso curUserID <> "" Then
Dim userID = CType(User.Identity, ClaimsIdentity)
Dim claims = userID.Claims
Dim roleType = userID.RoleClaimType
Dim myRoles = claims.Where(Function(c) c.Type = roleType).ToList()
myRole = (myRoles.FirstOrDefault.ToString)
'Here myRole contains whole https string - need to strip it to actual value
Dim lastInd = myRole.LastIndexOf(" ")
myRole = myRole.Substring(lastInd + 1, myRole.Length - (lastInd + 1))
End If
End Code

How to Fill Drop Down List using Model in MVC

Function GetStateName() As List(Of SelectListItem)
Dim ListRoomMaster As List(Of MiscMaster) = New List(Of MiscMaster)
Dim rm As New MiscMaster
Using conn As New SqlConnection(connectionString)
Dim sSql = "Select * From dropdown"
Dim cmd As SqlCommand = New SqlCommand(sSql, conn)
conn.Open()
Dim rst As SqlDataReader = cmd.ExecuteReader
Do While rst.Read
rm.m_ddlId = rst!id
rm.ddlValue = rst!name
ListRoomMaster.Add(rm)
Loop
End Using
Dim Listxyz = (
From p In Enumerable.Range(0, 20)
Select New SelectListItem With {.Text = p.ToString(), .Value = p.ToString()})
Return Listxyz.ToList()
End Function
This is the code for GetStateName() Which I am calling from controller Before Viewing This Displays The Drop Down List With 0 to 19 numbers I know I have Miss Something But Don't Know Where to change as most of code are for Linq
This Is Controller Code
Function Index() As ActionResult
objMisc.StateValue = objMisc.GetStateName()
'objMisc.StateValue = obj
Return View(objMisc)
End Function
What I Exactly Want Is Fetching data from DataBase using query
DataBase Have field like follow
id | Value
1 | xyz
2 | abx
3 | kvd
I want to populate drop down List As xyz,abx,kvd
And when abx is selected I want to store 2 in database
If you are working with MVC then you can also get the Data directly in the Razor View from your Model. Because you are doing a SQL Query manually which isnt the puropse of MVC.
Your should return the Model and then you can simply do this:
#Html.DropDownListFor(m => m.column, Model.dropdown)
Let's make a couple of models:
public NameCode(string name)
{
Name = name;
Code = name;
}
public NameCodeCollection(IEnumerable<NameCodeItem> list) : base(list)
{
}
In razor:
#Html.DropDownListFor(m => m.modelid, new SelectList(Model.modeltext, "Name", "Code"))
Use the namecodecollection to feed your dropdown list & read from it.

Error when trying to use context.entity.include()

I am trying to filter records and return them to put them in a list. My variable "companyId" equals 1. When I run, I get an error. What can I do to fix? Thank you.
The error points to this line:
Dim blogs = db.Blogs.Include(Function(b) b.CompanyId = companyId)
The error:
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path
The whole code:
'
' GET: /ViewBlogs/
Function ViewBlogs() As ViewResult
'Dim blogs = db.Blogs.Include(Function(b) b.Company)
Dim db1 As UserProfileDbContext = New UserProfileDbContext
Dim user = Membership.GetUser()
Dim key As Guid = user.ProviderUserKey
Dim userProfile = db1.UserProfiles.Where(Function(p) p.UserId = key).Single
Dim companyId = userProfile.CompanyId
If (userProfile.IsCompanyOwner) Then
Dim blogs = db.Blogs.Include(Function(b) b.CompanyId = companyId)
Return View(blogs.ToList())
Else
Return View("Home")
End If
End Function
Yes, the solution for me was as simple as this:
Dim blogs = db.Blogs.Where(Function(b) b.CompanyId = companyId)

LINQ concatenate 2 fields to search on

I'm trying to concatenate two fields in LINQ so that I can then filter with a keyword. I found a question posted here that I thought was my answer, but I'm getting 0 records back for some reason. This is supposed to return a JSON result for an autocomplete textbox (it works when I don't concatenate fields).
Here's my code:
Function CostCodeList(ByVal term As String) As ActionResult
Dim results = From c In db.ORG_CHART_V
Let Fullname = CStr(c.COSTCTR_CD & " - " & c.BREADCRUMB)
Where Fullname.ToUpper.Contains(CStr(term).ToUpper)
Order By Fullname
Select New With {.label = Fullname, .id = c.ORG_NODE_ID}
Return Json(results.ToArray, JsonRequestBehavior.AllowGet)
End Function
I'm also getting this error on the Return:
Public member 'ToArray' on type 'DbQuery(Of VB$AnonymousType_3(Of
String,Integer))' not found.
Before trying to concatenate the two fields I was searching on them separately, successfully. But when I concatenate them, it seems like everything I try either gets me an error and/or zero records.
Here is a different function that does work:
Function RoleList(ByVal term As String) As ActionResult
Dim list As New ArrayList
Dim results As IQueryable(Of JOB_ROLE)
If IsNumeric(term) Then
results = From c In db.JOB_ROLE
Where CStr(c.JBROLE_NO).StartsWith(term)
Else
results = From c In db.JOB_ROLE
Where c.JOB_ROLE_NAME.ToUpper.Contains(CStr(term).ToUpper)
End If
results = results.OrderBy(Function(e) e.JOB_ROLE_NAME)
For Each item In results
list.Add(New With {.label = item.JOB_ROLE_NAME, .id = item.JOB_ROLE_ID})
Next
Return Json(list.ToArray, JsonRequestBehavior.AllowGet)
End Function
Here is the new function that works as intended:
Function CostCodeList(ByVal term As String) As ActionResult
Dim list As New ArrayList
Dim results = db.ORG_CHART_V.Where(Function(e) (CStr(e.COSTCTR_CD) + " - " + e.BREADCRUMB).Contains(CStr(term).ToUpper)).OrderBy(Function(o) o.COSTCTR_CD)
For Each item In results
list.Add(New With {.label = item.COSTCTR_CD & " - " & item.BREADCRUMB, .id = item.ORG_NODE_ID})
Next
Return Json(list.ToArray, JsonRequestBehavior.AllowGet)
End Function

Sorting or Ordering values returned in a EF query MVC 3 vb.net app

I am using a where comparer in the below snippet from my function.. I need to order or sort the returned items by one of the columns... I tried using .OrderBy(function(f) f.regDate) but that dont work at all...
The part of the function in question looks like this:
Function ClassFiller() As ActionResult
Dim _courses As List(Of cours) = db.courses.ToList
Dim _registrants As List(Of reg_info) = db.reg_info.ToList
Dim _classSpec As List(Of classrm) = db.classrms.ToList
Dim _CurrRegistrants As List(Of reg_classes) = db.reg_classes.ToList
For Each Course In _courses.Where(Function(a) a.course_day = "Tuesday")
Dim _CurrCourse As cours = Course
Dim _classRoom As classrm = db.classrms.Where(Function(b) b.Course_ID = _CurrCourse.course_ref).FirstOrDefault()
Dim _classmax As Integer = _classRoom.ClassMax - 1
For Each reg In _registrants.Where(Function(d) d.tues_class1 = _CurrCourse.course_ref).OrderBy(Function(f) f.reg_date)
Dim _ClassCount As Integer = db.reg_classes.Where(Function(c) c.tues_class = _CurrCourse.course_ref).Count
I need to have the _registrants ordered or sorted by a value that is in the db.reg_info under the reg_date column... Any ideas??
Where _registrant is declared at I should have used the following instead:
Dim _registrants As List(Of reg_info) = db.reg_info.OrderBy(Function(t) t.reg_date).ToList
then it will already be ordered.. So the orderby is not needed in the For Each reg In _Registrants.

Resources