Using Objects in a dictionary in vb.net - asp.net

This is how I Check if my dictionary occurences already contains a key and a value and assign keys and values to it... but I need another value, so how do I use the object here?
Occurences.Add(xRows.Cells(4).Value.ToString(), Object)
Somehow like this:
occurences(xRows.Cells(4).Value.ToString()) = Double.Parse(occurences(xRows.Cells(4).Value.ToString()).ToString()) + <"1st object value here">)
But this is how I currently do it which only has a key and a value but I need something like key, object which has (value, value), something like that:
Actual code:
If (occurences.ContainsKey(xRows.Cells(4).Value.ToString())) Then
occurences(xRows.Cells(4).Value.ToString()) = Double.Parse(occurences(xRows.Cells(4).Value.ToString()).ToString()) + Double.Parse(xRows.Cells(7).Value.ToString())
Else
occurences.Add(xRows.Cells(4).Value.ToString(), Double.Parse(xRows.Cells(7).Value.ToString()))
End If
Next
Then i have another code for insert where i need to use the 2nd value of the object.
Using commm As New MySqlCommand()
With commm
.Parameters.Clear()
.Parameters.AddWithValue("#iBrnchCde", cmbBrnchCode.Text)
.Parameters.AddWithValue("#iFCode", pair.Key)
.Parameters.AddWithValue("#iDesc", <"2nd OBJECT VALUE HERE"> )
.Parameters.AddWithValue("#iQty", pair.Value)
.CommandText = oInsertString
.Connection = _conn
.CommandType = CommandType.Text
End With
commm.ExecuteNonQuery()
End Using

Do the following:
Class CustomRowObject
Public Property Name() As String
Public Property Quantity() As Double
Public Property Description() As String
End Class
If (occurences.ContainsKey(xRows.Cells(4).Value.ToString())) Then
occurences(xRows.Cells(4).Value.ToString()).Quantity = Double.Parse(occurences(xRows.Cells(4).Value.ToString()).ToString()) + Double.Parse(xRows.Cells(7).Value.ToString())
Else
occurences.Add(xRows.Cells(4).Value.ToString(),New CustomRowObject With { .Name = a.Cells("ProductName").Value.ToString(),.Description = .Cells("ProductDesc").Value.ToString(), .Quantity = a.Cells("Quantity").Value.ToString()})
End If
Next
Then reference it via occurences("keynamegoeshere").Quantity for use in your SQL.

I'm not sure I understand your question fully, but if I do I would suggest a different approach:
Why not make a class that holds your values, then add your class to the dictionary - or - create a dictionary of the class type:
Public myClass
Public Code As String
Public Desc as String
....
End Class
Dim myClassInstance as New myClass
'initialize fields
occurences.Add(key, myClassInstance)
To retrieve get the value as an object and use if typeof value is myclass then - if you choose object as type for the dictionary.
If you choose object you can store different classes and types of course, but the cost is the casting. If possible make a dictionary of the type you will use to avoid casting.
Private myDictionary as New Dictionary(Of String, myClass)

Related

How to rename a String variable dynamically using javassist?

I have a class named Sample and I need to rename the variable messageID to NameID, such that the corresponding getter and setter are also updated.
public class Sample{
String messageID;
public String getMessageID() {
return MessageID;
}
public void setMessageID(String messageID) {
MessageID = messageID;
}
}
With Javassist you can change the field name and all the references from old field name to the new one.
ClassPool classpool = ClassPool.getDefault();
CtClass ctClass = classpool.get(Sample.class.getName());
CtField field = ctClass.getField("messageID");
CodeConverter codeConverter = new CodeConverter();
codeConverter.redirectFieldAccess(field, ctClass, "NameID");
ctClass.instrument(codeConverter);
field.setName("NameID");
If you don't know ho to use Javassist you should read this tutorial here
The trick about "rewiring" all field references is done using a CodeConverter that will replace all references to the CtField field for the references to the field named NameID in ctClass. Keep in mind that this needs to be done before renaming the field into NameID.
However you should remember that all the references are updated but the set/get methods names are still getMessageID and setMessageID. You can easily change that using the same reference of ctClass as follow:
CtMethod getter = ctClass.getDeclaredMethod("getMessageID");
getter.setName("getNameId");
CtMethod setter = ctClass.getDeclaredMethod("setMessageID");
setter.setName("setNameId");

Convert a String to Call a Public Class ASP.NET VB

I have looked at this link and I cannot seem to get it to work
Creating a New control of the same type as another control that is already declared
I have also tried this from searches:
Dim ClassToCreate As String = "TestClass1.CountItems"
Dim myInstance = Activator.CreateInstance(Type.GetType(ClassToCreate), True)
Error is:
"Value cannot be null.
Parameter name: type"
Problem:
I have multiple classes and want to change which one is called based on a string.
(example is not correct of course)
Dim strClassToCall = "TestClass1.CountItems"
'then convert the string to the actual class so it can be called like this:
Dim strResult = TestClass1.CountItems(strSomeParameter)
Thanks for your help!
Based on the error message it sounds like your Type is not getting loaded properly as it is null. The method you are using will create the object like you need assuming you get the valid Type to pass to the activator. Is the type coming from an referenced DLL?
Here is one method you could use to get the type if just using the string representation is not working. This uses reflection to find the type:
// Sorry this is c# :)
System.Reflection.Assembly pAssembly = System.Reflection.Assembly.Load(
System.Reflection.Assembly.GetExecutingAssembly().
GetReferencedAssemblies().Single(a => a.Name.Equals("YourNamespace.ClassName")));
yourType = pAssembly.GetTypes().First(c => (c.FullName != null) &&
c.FullName.Equals("YourNamespace.ClassName"));
var yourObject = Activator.CreateInstance(yourType, true);

How to write a contains statement to match a member of a class?

If I have the following structure:
Public Class UserData
Public ID As String
Public Name As String
End Class
How can I select it in a conditional like this?
Dim myUsers As New System.Collections.Generic.List(Of UserData)
If myUsers.Contains(.ID = "1") = True Then
...
I know that myUsers.Contains(.ID = "1") is totally wrong, but I am curious how to do something like that? Is it possible? Is this a job for LINQ?
How about this:
If myUsers.Any(Function(u) u.ID = "1") Then
...
Of course, if you're going to do this more than once, you'll probably be better off creating a set to search in:
Dim myUserSet = New HashSet(Of String)(myUsers.[Select](Function(u) u.ID))
For Each userId In selectedUserIds
If myUserSet.Contains(userId) Then
...
My vb is rusty. Please forgive syntax errors
Here's the VB version:
If myUsers.Any(Function(i) i.ID = "1") Then ...
Why don't you use a Dictionary
var myUserDict = new Dictionary<String, UserData>
if(myUserDict.ContainsKey("1"))..
Makes only sense of course if you are going to do anything with the selected user.

Looks like a query string, but won't act as a query string

I am working with VB in asp.net,
The basic problem is, I want to pair up the elements in a string, exactly like request.QueryString() will do to the elements in the query string of the web page.
However instead of the function looking at the current webpage query string I want it to look at a string (that is in the exact form of a query string) stored as a variable.
So if I define a string such as:
Dim LooksLikeAQueryString As String = "?category1=answer1&category2=answer2"
I want a function that if I input LooksLikeAQueryString and "category1" it outputs "answer1" etc.
Is there anything that can already do this or do I have to build my own function? If I have to build my own, any tips?
I should add that in this case I won't be able to append the string to the url and then run request.QueryString.
You can use the HttpUtility.ParseQueryString method - MSDN link
ParseQueryString will do it for you - something along these lines:
Private Function QueryStringValue(queryString As String, key As String) As String
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(queryString)
For Each s As String In qscoll.AllKeys
If s = key Then Return qscoll(s)
Next
Return Nothing
End Function
Usage:
Dim LooksLikeAQueryString As String = "?category1=answer1&category2=answer2"
Response.Write(QueryStringValue(LooksLikeAQueryString, "category2"))
If you dont want the dependancy of System.Web, of the top of my head
public string GetValue(string fakeQueryString,string key)
{
return fakeQueryString.Replace("?",String.Empty).Split('&')
.FirstOrDefault(item=>item.Split('=')[0] == key);
}

Object returning from Function vb.net

I'm trying to return an object from a function.
E.g. Ive got a function populateDog that returns Dog
So in my aspx class I want to be able to be able to pass in Lassie as the name of the dog(I have a dog class) and have the function return the object with the data it populated.
So that in my aspx class i can go lassie.color, lassie.breed
Main Goal is: lbl.txt = Lassie.Color
Thanks
EDIT
Public Function populateDog(ByVal dName As String) As dog
dbConnection()
Dim ObjDog As New dog(dName)
ObjDog.sBreed = "Collie"
Return ObjDog
End Function
The idea was to have a database and I would eventually pass in an ID to query results and return it. For now though I just wanna get this understanding and move forward.
Public Function populateDog(ByVal dName As String) As dog
dbConnection()
Dim ObjDog As New dog(dName)
ObjDog.sBreed = "Collie"
ObjDog.Color = "White"
Return ObjDog
End Function
and
Dim Lassie as dog
Lassie = populateDog("Lassie")
lbl.Text = Lassie.Color
assuming your dog class is something like
Class dog
Public sBreed As String
Public Color As String
' other properties and functions
End Class

Resources