convert stringbuilder to guid - asp.net

Hi I've some guids in stringbuilder and I want to store these values in guid array.
Can some one give me idea to convert this. I'm working with vb.net
Thanks in advance

Assumption: your guids are really simply strings.
Than that might help:
Dim SB as new Stringbuilder = "GUID"
Dim GuidList as New List(Of Guid)
Dim myGUID as Guid
If GUID.tryparse(SB.tostring, myGuid)=true then
Guidlist.add(myguid)
else
'Handle the error here
end if
Wrap this in a loop over your Guids, I don't know how you stored them.
Remarks: You might need to use parsexact, see the documentation: http://msdn.microsoft.com/en-us/library/system.guid.aspx
I have written out of my head, so the code might not compile...

Related

Using ParseQueryString function to get values from QueryString

I needed to get values out of a string in a QueryString format, that is such as: data1=value1&data2=value2...
Someone suggested I used HttpUtility.ParseQueryString to get the value, I've searched and searched but I can't find any documentation or implementation of this and the Microsoft documentation for it doesn't explain how it works, can someone tell me hwat I'm doing wrong, my code is below;
Public Shared Sub ProcessString(ByVal Vstring As String)
Dim var As NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = var.QueryString("VNAME")
End Sub
MSDN has an example.
' Parse the query string variables into a NameValueCollection.
Dim qscoll As System.Collections.Specialized.NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = qscoll("VNAME")
A NameValueCollection represents a collection of associated String keys and String values that can be accessed either with the key or with the index.
I found the problem, I was referencing everything fine but I was doing it in a separate .VB dependency file, once I did it on the actual code behind of the aspx form that solved the problem and it all worked. So now I'm just passing the string from Codebehind as a specialised.NameValue collection in to the function.

dynamically change querystring in asp.net

Our client is asking to encrypt the URL because it is passing values in the query string. We have used encryption and are able to encrypt the URL; however, existing code uses querystring["var"] in so many places and fails because of the encrypted URL. Hence, on page load, we will have to decrypt the URL. If I decrypt and alter the query string using response.redirect, then again query string will be visible in the URL and can be misused.
Please help.
EDIT
I was reading about RESTfull web service. I have not yet understood entire concept. I wonder if I can use this with my application to hide query string. Please let me know if so.
Thanks.
One way to achieve this with little headache is to decrypt the query string as you currently do, then set its values to some object which can be stored in the session. Storing it in a session variable would be useful if you wanted to exclude this information (hide) from the query string - you'd essentially be passing the data around behind the scenes.
Once stored in session, you would then change your code, such that wherever you use querystring["var"], you will instead refer to the object that has been stored in the session.
Edit
Note, though, that this doesn't have to be relegated to a single value. This object can have multiple properties each representing a query string value:
MyQueryStringObject myQueryStringObject = new MyQueryStringObject(SomeUrl);
//MyQueryStringObject decrypts the query string and assigns the values to properties in its constructor
string abc = myQueryStringObject.abc;
string xyz = myQueryStringObject.xyz;
Now, that uses properties to represent each query string value. You may have tons of them. In that case, you can store the values into some sort of Dictionary or a NameValueCollection perhaps.
There are various ways to achieve this which I think is beyond topic, but, note that the key to all of this, the very essence is to simply decrypt the url on the server (during postback) and save the unencrypted data into a session variable should you want to hide it from the URL.
There is a much better way of going about this. I deal with a client with that has the same requirement. This class has soared through security scans as well.
Public Class QueryStringManager
Public Shared Function BuildQueryString(ByVal url As String, ByVal queryStringValues As NameValueCollection) As String
Dim builder As New StringBuilder()
builder.Append(url & "?")
Dim count = queryStringValues.Count
If count > 0 Then
For Each key In queryStringValues.AllKeys
Dim value As String = queryStringValues(key)
Dim param As String = BuildParameter(key, value)
builder.Append(param)
Next
End If
Return builder.ToString()
End Function
Public Shared Function DeconstructQueryString(ByVal Request As HttpRequest) As NameValueCollection
Dim queryStringValues As New NameValueCollection
For Each key In Request.QueryString.AllKeys
Dim value As String = Request.QueryString(key)
value = DeconstructParameter(value)
queryStringValues.Add(key, value)
Next
Return queryStringValues
End Function
Private Shared Function BuildParameter(ByVal key As String, ByVal value As String) As String
Dim builder As New StringBuilder()
builder.Append(key.ToString() & "=")
value = GetSafeHtmlFragment(value)
Dim encrypt As Security = New Security()
value = encrypt.Encrypt(value)
builder.Append(value)
builder.Append("&")
Return builder.ToString()
End Function
Public Shared Function DeconstructParameter(ByVal value As Object) As String
Dim decrypt As New Security()
value = decrypt.Decrypt(value)
value = GetSafeHtmlFragment(value)
End Function
End Class
Use
Dim nvc As NameValueCollection = New NameValueCollection()
nvc.Add("value", 1)
Dim builtUrl As String = QueryStringManager.BuildQueryString(url, nvc)
Response.Redirect(builtUrl, false);
Then when you get to the page you simply write:
Dim decryptedValues As NameValueCollection = QueryStringManager.DeconstructQueryString(Request)
The reason why I use NameValueCollection is because that's the same type as QueryString. You can build on to the class to add an object into the QueryString based on it's properties and their values as well. This keeps all of the complex and tedious logic encapsulated away.

Iterating over SearchResultCollection is Very Slow

I'm running an LDAP query that returns multiple entries and stores them inside a SearchResultCollection. I'm iterating over the SearchResultCollection like so:
// results is my SearchResultCollection object
foreach (SearchResult sr in results)
{
... do things to each SearchResult in here ...
}
This seems like the most logical way to do this, but loop is incredibly slow. When I step through the loop with the debugger, I find that it's the very first step of initializing the foreach loop that takes the time - the actual iterations are instantaneous.
In addition, when I view the contents of the SearchResultCollection while debugging, the watch takes just as long to load the contents of the variable.
I have a theory that the SearchResultCollection doesn't actually contain complete SearchResult objects, but rather references to entries in the Active Directory server that are then individually fetched when I iterate over the SearchResultCollection object. Can anyone confirm this theory? And is there a better (faster) way to fetch a set of LDAP entries?
I suffered from the same problem and the methodology in the post below was much quicker then my own:
http://msdn.microsoft.com/en-us/library/ms180881(v=vs.80).aspx
... to answer you question yes it seems as if you try to process the entries directly while still in the loop by using something like:
If Not UserAccount.GetDirectoryEntry().Properties("sAMAccountName").Value Is Nothing Then sAMAccountName = UserAccount.Properties("sAMAccountName")(0).ToString()
... this has a drastic impact on performance, you can get around this by adding the collection to a Dictionary within the loop and then processing the dictionary:
Dim searchResult As SearchResult
Dim dictLatestLogonDatesTemp As New Dictionary(Of String, Date)
SearchResults1 = mySearcher.FindAll()
For Each searchResult In SearchResults1
Dim propertyKey,sAMAccountName As String
Dim dteLastLogonDate As Date = Nothing
For Each propertyKey In searchResult.Properties.PropertyNames
Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyKey)
For Each propertyValue As Object In valueCollection
If LCase(propertyKey) = LCase("sAMAccountName") Then sAMAccountName = propertyValue
If LCase(propertyKey) = LCase("lastLogon") Then dteLastLogonDate = Date.FromFileTime(propertyValue)
Next propertyValue
Next propertyKey
If sAMAccountName <> Nothing Then dictLatestLogonDatesTemp.Add(sAMAccountName, dteLastLogonDate)
Next searchResult
It is a bit restrictive bacause a dictionary ony has two entries but you can comma seperate other values or use a dictionary of values in the dictionary:
Dim tempDictionary As Dictionary(Of String, Dictionary(Of String, String))
Hope this helps someone!
I would like to submit that adding them to a datatable also works very well and allows for more properties than a dictionary. I went from iterating 2000 users in the searchresultscollection taking almost 2 minutes to less that 1-2 seconds. Hope this helps others.
Private Sub getAllUsers()
Dim r As SearchResultCollection
Dim de As DirectoryEntry = New DirectoryEntry(GetCurrentDomainPath)
Dim ds As New DirectorySearcher(de)
ds.SearchScope = SearchScope.Subtree
ds.PropertiesToLoad.Add("name")
ds.PropertiesToLoad.Add("distinguishedName")
ds.PropertiesToLoad.Add("objectSID")
ds.Filter = "(&(objectCategory=person)(objectClass=user))" '(!userAccountControl:1.2.840.113556.1.4.803:=2) not disabled users
PleaseWait.Status("Loading Users...")
Application.DoEvents()
r = ds.FindAll()
Dim dt As New DataTable
dt.Columns.Add("Name")
dt.Columns.Add("SID")
For Each sr As SearchResult In r
Dim SID As New SecurityIdentifier(CType(sr.Properties("objectSID")(0), Byte()), 0)
dt.Rows.Add(sr.Properties("name")(0).ToString(), SID.ToString)
Next
With lstResults
lstResults.DataSource = dt
.DisplayMember = "name"
.ValueMember = "SID"
.Items.Sort()
End With
End Sub
There may be some ways to decrease the response time:
restrict the scope of the search
use a more restrictive search filter
use a base object closer to the object(s) being retrieved.
see also
LDAP: Mastering Search Filters
LDAP: Programming practices
LDAP: Search Best Practices

Why would Guid.NewGuid() be generating an empty guid?

I have a Guid.NewGuid() call that is creating an Empty Guid.
What would cause such a problem and how can I fix it?
Edit: The code:
<WebMethod()> _
Public Function CreateRow(rowValue As String) as String
Dim rowPointer As Guid = System.Guid.NewGuid()
Dim rowPointerValue As String = rowPointer.ToString()
Try
Dim result as Integer = SqlHelper.ExecuteNonQuery(ConnectionString, "Sproc_Name", rowValue, rowPointer)
Return result
Catch ex as Exception
Throw ex
End Try
End Function
Edit: Turns out that rowPointer was originally being passed to the SqlHelper and not rowPointerValue - This of course is passed as empty, as pointed out in the answers. Changing it to rowPointerValue/rowPointer.ToString() fixed the problem.
This is an old problem in VB.NET. It is only the debug visualizer that is broken.
http://www.thesoftwaredevotional.com/2008/12/guid-visualizer-broken-in-vbnet.html
I had the same thing. Debugging of Guid.NeGuid() was showing that it's empty. Calling .ToString() fixed the situation.
I tested this code in VS2008 and the results are not what I expected. It seems that the new guid is not created until the toString method is called. After stepping through the code rowPointerValue does hold a string representation of the guid.
It seems to be using defferred execution?
I've only experiened this problem in VB.NET and only while debugging. Thanks 48494, for that info.
Try this
Dim g As New Guid();
Dim whereDoYouWantToSeeIt As String = g.ToString();

parsing URL ?a=b params with VB.NET from plain string

I am using a string to store key=value pairs, it has same format as QueryString
How can I easily parse it to array? or can I somehow use interal class QueryString("paramname") to access it?
You could use the System.Web.HttpUtility.ParseQueryString, this will give you a NameValueCollection. You can then access your values easily
Dim keynameValue As String = nameValueCollection.Get("Keyname")
' parse to pairs
Dim resultarray As Array = allresultdata.Split("&")
Dim result1 As String
Dim keyvals2 As Array
For Each result1 In resultarray
keyvals2 = result1.Split()
keyvals.Set(keyvals2(0), keyvals2(1))
Next
or can I somehow use interal class
QueryString("paramname") to access it?
If you need to access querystring from another class other then page code behind, use this :
HttpContext.Current.Request.QueryString("parameterName")
String.Split() probably will work for you....

Resources