VB.net "'Me' is valid only within an instance method" inside PageMethods - asp.net

I'm getting "Me' is valid only within an instance method" error when I convert function to a PageMethods.
Private Shared objDT As System.Data.DataTable
Private Shared objDR As System.Data.DataRow
<WebMethod()> Public Shared Function addstn(itemID As String) As String
For Each Me.objDR In objDT.Rows
If objDR("ProductID") = ProductID Then
If objDR("Options") = desc Then
objDR("Quantity") += 1
blnMatch = True
Exit For
End If
End If
Next
End Function
If I remove Me, I get different error.
I got this shopping cart script somewhere online and I'm not sure what to replace "Me.objDR" with something else.
Thank you in advance

The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing.
In a shared context there is no instance. You can reference your variable directly or via ClassName.VariableName.
This could work(i'm not sure wherefrom the other variables are):
For Each objDR In objDT.Rows
If ProductID.Equals(objDR("ProductID")) _
AndAlso desc.Equals(objDR("Options"))Then
Dim q = CInt(objDR("Quantity"))
objDR("Quantity") = q + 1
blnMatch = True
Exit For
End If
Next
http://msdn.microsoft.com/en-us/library/20fy88e0%28v=vs.80%29.aspx

Me cannot be used since its a shared method, shared methods are not accessed through an instance.
What is the other error you receive?

Public Shared Function addstn(...
The "Shared" means it's not an instance method. If you want to use "Me", you can't use "Shared". Use the name of the class/module instead.

Related

Trying to search Active Directory using Ambiguous Name Resolution but it never returns anything

Unable to get it to return any results. Compiles fine and does not error when it is run, but the results are always empty.
I have got this working if I restrict it to something like DisplayName or given name. But would like it to work no matter if the user puts in forename or surname first and that the user is not restricted to adhering to the DisplayName format of "Surname, Forename"
Dim searchterm As String = RouteData.Values("Search")
Dim domain As New PrincipalContext(ContextType.Domain, "Domain")
Dim user As New CustomUserPrincipal(domain)
Dim search As New PrincipalSearcher()
Dim results As PrincipalSearchResult(Of Principal)
jss.MaxJsonLength = Integer.MaxValue
user.Anr = String.Format("*{0}*", searchterm)
search.QueryFilter = user
CType(search.GetUnderlyingSearcher, DirectoryServices.DirectorySearcher).SizeLimit = 25
results = search.FindAll()
<DirectoryObjectClass("user")>
<DirectoryRdnPrefix("CN")>
Public Class CustomUserPrincipal
Inherits UserPrincipal
Public Sub New(context As PrincipalContext)
MyBase.New(context)
End Sub
<DirectoryProperty("anr")>
Public Property Anr As String
Get
Return CStr(ExtensionGet("anr")(0))
End Get
Set(value As String)
ExtensionSet("anr", value)
End Set
End Property
End Class
I am expecting an object that I can enumerate through and pull out individual UserPrincipals to extract details. But I only get an empty object
I think this is your problem:
user.Anr = String.Format("*{0}*", searchterm)
Specifically, that you're putting asterisks around your search term. According to the documentation, it will expand a search term like (anr=Smith) to something like this:
(|(displayName=smith*)(givenName=smith*)(legacyExchangeDN=smith)(physicalDeliveryOfficeName=smith*)(proxyAddresses=smith*)(Name=smith*)(sAMAccountName=smith*)(sn=smith*))
Notice that it already does a "starts with" type search. Putting your own wildcards in there messes it up.
More specifically, it's the asterisk at the beginning. I tested this in our own AD environment. If I search for (anr=*Gabriel*) or (anr=*Gabriel), I get no results. If I search for (anr=Gabriel*) I get results, but it really has no effect on the results (the results are the same as if I had searched for (anr=Gabriel)).
The solution is to change that line to this:
user.Anr = searchterm
It is not exactly equivalent to the "contains" search you seem to want, but putting a wildcard at the beginning of any search really kills performance anyway. It can no longer use any indexes to complete the search, so it's forced to look at every user account in your domain.

Way to encapsulate methods from default.aspx.vb page to another class

This question is about structure :
I have a Default.aspx page which holds references to (XML)services, and handles innerHTML of HTML objects. The ammount of buttons is based on services output.
Since this is an long and complex algorithm, I would like to encapsulate this in another class, to divide it into smaller and more readable chunks of code.
The problem is I do not know what the best option is, should I copy the reference of the used objects(service as well as the HTML items) into the new class ?
Since the ammount and origin of items it does not look to my like an elegant option.
I searched on the internet but could not find anything that suits this(I would think) common situation
This is the function I would like to transfer to another class. Currently it is in Default.aspx
and uses rep(ort)Service,defaultPath,path,selectionScreen and Image2 objects to draw the menu dynamically.
''' <summary>
''' Dynamically builds the square menu where the reports can be selected from.
''' It is based on the number of reports available
''' Show list of available reports on reporting server as HyperLinks
''' </summary>
''' <remarks></remarks>
Private Sub BuildReportSelectionArea(Optional path As String = "")
Dim items As CatalogItem() = repService.ListChildren(path, False)
Dim items2 As CatalogItem() = repService.ListChildren(path, False)
'Ensure that folders are shown first
Dim maxFolder = 0
For i = 0 To items.Count - 1 Step 1
If (items(i)).TypeName = "Folder" Then
items(i) = items2(maxFolder)
items(maxFolder) = items2(i)
maxFolder += 1
End If
' Some other code
End Sub
'TODO :Ensure the alfabetical order is preserved
Next
I would first generally comment on the code:
this means you are 2 times accessing the service, but the second array is later used to "sort" the items catalogItem, it seems a waste of resources to call the service twice
Dim items As CatalogItem() = repService.ListChildren(path, False)
Dim items2 As CatalogItem() = repService.ListChildren(path, False)
Reordering you could simply achieve using
Dim items As New List(Of CatalogItem)(RepService.ListChildren(path, False))
items.Sort(Function(item1 As CatalogItem, item2 As CatalogItem)
If String.Equals(item1.TypeName, item2.TypeName) Then
Return item1.FileName.CompareTo(item2.FileName)
End If
If item1.TypeName = "Folder" Then
Return -1
End If
Return 1
End Function)
which would sort by folders first, then by filename (you might have to update some of your properties to match)
you could further extract by either creating a module or a shared class that accepts the repService as an attribute and the path, and returns your output code
though creating a user control / webpart so you could add this functionality to each page you would like, would be a very good option as well, and the generally accepted way to refactor complex code...

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

Classic ASP getPathName and getName Error

I usually developed website using PHP. But now i have to using ASP Classic because my client already have a website then i have to maintenance the website. i already move all of the website to my new hosting. But there is error on this code :
cPath=getPathName(Server.mappath(Request.ServerVariables("PATH_INFO")))
The error message is :
Microsoft VBScript runtime error '800a000d'
Type mismatch: 'getPathName'
Some error display when call getName code.
Please help me what should i do.
Classic ASP or VBScript do not have equivalent to the PHP getPathName() and getName() functions as far as I can tell.
I wasn't able to understand what's the meaning of getPathName() when it's given a string and actually I don't think it exists, so just have:
cPath = Server.MapPath(Request.ServerVariables("PATH_INFO"))
And the variable will contain the full physical path to the currently executing ASP file.
As for getName() you can write custom function:
Function GetOnlyName(filePath)
Dim slashIndex
slashIndex = InStrRev(filePath, "\")
If slashIndex<1 Then
slashIndex = InStrRev(filePath, "/")
End If
If slashIndex>0 Then
ExtractFileName = Mid(filePath, slashIndex + 1, Len(filePath) - slashIndex + 1)
Else
ExtractFileName = filePath
End If
End Function
Then use it like this:
cName = GetOnlyName(Server.MapPath(Request.ServerVariables("PATH_INFO")))
And the variable will contain only the name of the ASP file.
For the record, to avoid confusing Type Mismatch errors, always put this on top of your scripts:
Option Explicit
Then always declare all your variable using Dim statement, like in the function above. Having this, trying to use getPathName would give "variable undefined" error which is much more meaningful.

sending Json array failed

I am building a JSON/WCF app and need to send an array of objects back to the server. For some reason it is not accepting the array. Using script manager I can get data fine.
var month = $("#ddlStartMonth").val();
var year = $("#ddlStartYear").val();
var items = JSON.stringify(calendarItems);
WebService.SaveCalendar(items, new Date(year, month, 01).toDateString(), new Date(year, month, 01).toDateString(), Submit, onPageError);
I have tried with and without the JSON stringify. The function onPageError is activated and the only error info it produces is "The server method 'SaveCalendar' failed". Yet the breakpoint on the first line of the web method is not activated.
<OperationContract()>
<WebGet(ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)>
<WebMethod(EnableSession:=True)>
Public Function SaveCalendar(ByVal _jsonImages As String()(), ByVal _selectedMonth As String, ByVal _selectedYear As String) As Boolean
Dim _calenderItems As New List(Of CalenderItem)
'_calenderItems = New JavaScriptSerializer().Deserialize(Of List(Of CalenderItem))(_jsonImages)
HttpContext.Current.Session("calenderItems") = _calenderItems
HttpContext.Current.Session("selectedMonth") = New Date(_selectedMonth)
HttpContext.Current.Session("selectedYear") = New Date(_selectedYear)
Return True
End Function
Any Ideas?
I've had similar issues working with MVC. I think .NET's deserializer actually expects that the object it is passed will be a JSON object rather than an array (i.e. it should always start with "{" and end with "}". You could:
Create a POCO class to act as your DTO which simply has a List/Array of CalenderItems inside of it, or
Use a more "lenient" deserializer like Newtonsoft's JSON.NET
Of course this second option would only work if you can somehow convince WCF to run the method in the first place. Looking at your code again, though, I'm wondering if your declaring _jsonImages as a double-array of strings might be causing some difficulty.

Resources