about split command in string using vb.net - url

am having url .it contain the querstring value like this.to split the url and store the querystring values in an array .query string values are not passed with in application .
it comes from another application
url
----
http://.....?lead_id=152818&vendor_id=100001&list_id=1001&gmt_offset_now=0.00&phone_code=91&phone_number=9942321400&title=MR&first_name=Hari&middle_initial=Q&last_name=PUBLIC&address1=249+MUNDON+ROAD&address2=MALDON&address3=FL&city=44&state=TN&province=NO_PROVINCE&postal_code=600004&country_code=IN&gender=M&date_of_birth=0000-00-00&alt_phone=9942321400&email=test#test.com&security_phrase=nothing&comments=COMMENTS&user=22222&pass=test&campaign=OUTBOUND&phone_login=22222&original_phone_login=22222&phone_pass=test&fronter=22222&closer=22222&group=OUTBOUND&channel_group=OUTBOUND&SQLdate=2012-08-07+164931&epoch=1344338372&uniqueid=1344338352.12754&customer_zap_channel=&customer_server_ip=&server_ip=10.103.200.177&SIPexten=22222&session_id=8600062&phone=9942321400&parked_by=152818&dispo=N&dialed_number=9942321400&dialed_label=MAIN&source_id=10001&rank=1&owner=Southeast&camp_script=&in_script=&script_width=600&script_height=340&fullname=J.Hariharan&recording_filename=OUTBOUND_20120807-164911_22222_9942321400&recording_id=248601&user_custom_one=&user_custom_two=&user_custom_three=&user_custom_four=&user_custom_five=&preset_number_a=&preset_number_b=&preset_number_c=&preset_number_d=&preset_number_e=&preset_dtmf_a=&preset_dtmf_b=&session_name=1344338181_2222216466857"
my question is i want to store the querystring values in an one dimensional string
array.
my code
-------
Dim strarr() As String
Dim s As String = "http://...../test.aspx?lead_id=152818&vendor_id=100001&list_id=1001&gmt_offset_now=0.00&phone_code=91&phone_number=9942321400&title=MR&first_name=Hari&middle_initial=Q&last_name=PUBLIC&address1=249+MUNDON+ROAD&address2=MALDON&address3=FL&city=44&state=TN&province=NO_PROVINCE&postal_code=600004&country_code=IN&gender=M&date_of_birth=0000-00-00&alt_phone=9942321400&email=test#test.com&security_phrase=nothing&comments=COMMENTS&user=22222&pass=test&campaign=OUTBOUND&phone_login=22222&original_phone_login=22222&phone_pass=test&fronter=22222&closer=22222&group=OUTBOUND&channel_group=OUTBOUND&SQLdate=2012-08-07+164931&epoch=1344338372&uniqueid=1344338352.12754&customer_zap_channel=&customer_server_ip=&server_ip=10.103.200.177&SIPexten=22222&session_id=8600062&phone=9942321400&parked_by=152818&dispo=N&dialed_number=9942321400&dialed_label=MAIN&source_id=10001&rank=1&owner=Southeast&camp_script=&in_script=&script_width=600&script_height=340&fullname=J.Hariharan&recording_filename=OUTBOUND_20120807-164911_22222_9942321400&recording_id=248601&user_custom_one=&user_custom_two=&user_custom_three=&user_custom_four=&user_custom_five=&preset_number_a=&preset_number_b=&preset_number_c=&preset_number_d=&preset_number_e=&preset_dtmf_a=&preset_dtmf_b=&session_name=1344338181_2222216466857"
strarr = s.Split("?")
Dim s1 As String = strarr(1)
Dim constr() As String
constr = s1.Split("&")
but am not get correct result
my result
---------
list_id=1001
gmt_offset_now=0.00
phone_code=91
phone_number=9942321400
expected result
---------------
1001
0.00
91
9942321400

Iterate over your 'constr' and use one more split ( by '=' ). Results can be stored in List(of String).
dim r as new list(of String)
for each c in constr
r.add(c.split("=")(1))
next
(something like this)
To view this you should list all items inside 'r', so you'll need another for.
for each item in r
console.writeline(item)
next
You can do it inside first loop either.

Related

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.

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

Creating a List (of String) giving error" Object reference not set to an instance of an object. "

MVC 3 razor VB.NET project. I have resorted to manual building a list for a drop down box so I can insure certain values are available in the select list and also to control what the first item is in the list. The below is my code snippet for the part that is giving me problems..
Dim _courses1 As Integer = db.courses.ToList.Where(Function(r) r.course_day = "Tuesday").Count
Dim _classes1 As List(Of cours) = db.courses.ToList
Dim classRef1 As List(Of String)
If Not _selectedClass0 = "--" Then
classRef1.Add("--")
Else
classRef1.Add(_selectedClass0)
End If
For i As Integer = 0 To _courses1 - 1
For Each item In _classes1.Where(Function(f) f.course_day = "Tuesday")
Dim _item As cours = item
classRef1.Add(_item.course_ref)
Next
Next
ViewBag.tue1 = classRef1
The _selectedClass0 is just a string that gets set earlier... The error mentioned happens when it gets to the ClassRef1.Add(_selectedClass0) part of the else statement. Which _selectedClass0 string value at the time of error is "--". I have a feeling it is in how the list is being created but I am not certain... Any ideas???
You're not initializing classRef1.
Dim classRef1 As new List(Of String)
Another thing I see is in the first line - I've made the changes I see:
Dim _courses1 As Integer = db.courses.Where(Function(r) r.course_day = "Tuesday").Count()
You don't need ToList at the beginning if all your getting is the count.
You are declaring classRef1 to be a list of strings here:
Dim classRef1 As List(Of String)
But you're never actually creating an instance using New. I'm not sure about the VB syntax, as I'm a C# developer, but I'd guess you should add the following line right after the declaration:
classRef1 = New List(Of String)

Why does the DefaultModelBinder not bind to Char properties with value of " "c

I have a class like
Public Class Task
Property DuplexType As Char
Property Name As String
End Class
In my controller I have an action that looks like
<HttpPost()>
Function Edit(ByVal task As Task) As ActionResult
Dim duplexType = task.DuplexType
Dim valid = ModelState.IsValid
Return RedirectToAction("Index")
End Function
In the view, DuplexType = " " (single space) and Name = "Foo". Why doesn't the property DuplexType have a value? If I assign any other character it works fine.
In the controller name = "foo" but DuplexType = " (empty).
Also ModelState.IsValid = false if DuplexType = " ".
Have a look at the Response object and examine the values being populated by the form Post. You will probably see that values are trimmed and therefore lose the space. If possible try to UrlEncode the values.
Where I have had to preserve trailing spaces in my own projects, I have ended up having to put delimiters on the parameter and then strip them off in the action method.

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