LINQ concatenate 2 fields to search on - asp.net-mvc

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

Related

Getting a value from one table to pull up values from another table

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()

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.

Inserting rows into existing Excel worksheet with OleDbConnection

I'm building insert statements based on a list of data and a tab name. I have 4 tabs, the last 2 get data inserted successfully, the first 2 do not.
I commented out inserting into all tabs but one. The size of the excel file increases, but the rows are still blank. Any ideas?
Edit: For some reason, the Excel file I was using as a "blank template" had "empty" values in rows of the first 2 sheets. First one had "empty values" in the first 100K rows, seconds had empty values in the first 700-some rows. The data was being inserted after these rows, which explains why the file size was increasing. Now I'm getting "Operation must use an updateable query" when trying to insert.
Public Sub BuildReport(Of T)(tabName As String, dataList As IEnumerable(Of T))
'// Setup the connectionstring for Excel 2007+ XML format
'// http://www.connectionstrings.com/ace-oledb-12-0/
If ((tabName.EndsWith("$") = True AndAlso m_TabList.Contains(tabName) = False) OrElse m_TabList.Contains(tabName & "$") = False) Then
Throw New Exception(String.Format("The specified tab does not exist in the Excel spreadsheet: {0}", tabName))
End If
Using excelConn As New OleDbConnection(m_ConnectionString)
excelConn.Open()
Dim insertStatementList As IEnumerable(Of String) = BuildInsertStatement(Of T)(tabName, dataList)
Using excelCommand As New OleDbCommand()
excelCommand.CommandType = CommandType.Text
excelCommand.Connection = excelConn
For Each insertStatement In insertStatementList
excelCommand.CommandText = insertStatement
excelCommand.ExecuteNonQuery()
Next
End Using
End Using
End Sub
Private Function BuildInsertStatement(Of T)(tabName As String, dataList As IEnumerable(Of T)) As IEnumerable(Of String)
Dim insertStatementList As New List(Of String)
Dim insertStatement As New StringBuilder()
For Each dataItem As T In dataList
Dim props As PropertyInfo() = GetType(T).GetProperties()
insertStatement.Clear()
insertStatement.AppendFormat("INSERT INTO [{0}$] ", tabName)
Dim nameValueDictionary As New Dictionary(Of String, String)
For Each prop As PropertyInfo In props
Dim excelColumn As ExcelColumnAttribute = CType(prop.GetCustomAttributes(GetType(ExcelColumnAttribute), False).FirstOrDefault(), ExcelColumnAttribute)
If (excelColumn IsNot Nothing) Then
Dim value As Object = prop.GetValue(dataItem, Nothing)
If (value IsNot Nothing AndAlso value.GetType() <> GetType(Integer) _
AndAlso value.GetType() <> GetType(Double) _
AndAlso value.GetType() <> GetType(Decimal) _
AndAlso value.GetType() <> GetType(Boolean)) Then
value = String.Format("""{0}""", value)
ElseIf (value Is Nothing) Then
value = "NULL"
End If
nameValueDictionary.Add(excelColumn.ColumnName, value)
End If
Next
Dim columList As String = String.Join(",", nameValueDictionary.Keys)
Dim valueList As String = String.Join(",", nameValueDictionary.Select(Function(x) x.Value))
insertStatement.AppendFormat("({0}) ", columList)
insertStatement.AppendFormat("VALUES ({0})", valueList)
insertStatementList.Add(insertStatement.ToString())
Next
Return insertStatementList
End Function
For some reason, the Excel file I was using as a "blank template" had "empty" values in rows of the first 2 sheets. First one had "empty values" in the first 100K rows, second one had empty values in the first 700-some rows. The data was being inserted after these rows, which explains why the file size was increasing. Now I'm getting "Operation must use an updateable query" when trying to insert.
I found the answer to the second problem here: Operation must use an updateable query when updating excel sheet
Just needed to remove the "IMEX=1" from the extended properties of the connection string which I added in trying to troubleshoot the issue.

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)

Combining extension methods

I'm trying to write 2 extension methods to handle Enum types. One to use the description attribute to give some better explanation to the enum options and a second method to list the enum options and their description to use in a selectlist or some kind of collection.
You can read my code up to now here:
<Extension()> _
Public Function ToDescriptionString(ByVal en As System.Enum) As String
Dim type As Type = en.GetType
Dim entries() As String = en.ToString().Split(","c)
Dim description(entries.Length) As String
For i = 0 To entries.Length - 1
Dim fieldInfo = type.GetField(entries(i).Trim())
Dim attributes() = DirectCast(fieldInfo.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
description(i) = If(attributes.Length > 0, attributes(0).Description, entries(i).Trim())
Next
Return String.Join(", ", description)
End Function
<Extension()> _
Public Function ToListFirstTry(ByVal en As System.Enum) As IEnumerable
Dim type As Type = en.GetType
Dim items = From item In System.Enum.GetValues(type) _
Select New With {.Value = item, .Text = item.ToDescriptionString}
Return items
End Function
<Extension()> _
Public Function ToListSecondTry(ByVal en As System.Enum) As IEnumerable
Dim list As New Dictionary(Of Integer, String)
Dim enumValues As Array = System.Enum.GetValues(en.GetType)
For Each value In enumValues
list.Add(value, value.ToDescriptionString)
Next
Return list
End Function
So my problem is both extension methods don't work that well together. The methods that converts the enum options to an ienumerable can't use the extension method to get the description.
I found all kind of examples to do one of both but never in combination with each other. What am I doing wrong? I still new to these new .NET 3.5 stuff.
The problem is that Enum.GetValues just returns a weakly typed Array.
Try this:
Public Function ToListFirstTry(ByVal en As System.Enum) As IEnumerable
Dim type As Type = en.GetType
Dim items = From item In System.Enum.GetValues(type).Cast(Of Enum)() _
Select New With {.Value = item, .Text = item.ToDescriptionString}
Return items
End Function
(It looks like explicitly typed range variables in VB queries don't mean the same thing as in C#.)

Resources