I want to test a function which is in a web page. Do I have way to use System.Web.UI.Page in a console application and put something in Session and test this way?
I created a test class and to inherit the Page but I could not put Session in it. When I type "myPage." as show below, I do not see anything come out after "."
<TestClass()> Public Class UnitTest2
Inherits System.Web.UI.Page
Dim myPage = New System.Web.UI.Page
myPage.
End Class
Please help!
Update: Below code seemed to pass the compiler
<TestClass()> Public Class UnitTest2
<TestMethod()>
Public Sub TestCheckRules()
Dim myPage As testWebPage = New testWebPage
myPage.testSession()
End Sub
End Class
Public Class testWebPage
Inherits System.Web.UI.Page
Public Sub New()
End Sub
Public Sub testSession()
Dim firstName As String = "John"
Dim lastName As String = "Smith"
Dim city As String = "Seattle"
Session("FirstName") = firstName
Session("LastName") = lastName
Session("City") = city
End Sub
End Class
Then when I ran I got the following error:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
Related
Hi I need to create a class for return the data in WCF service. I followed the web at 5 simple steps to create your first RESTful service. However I get the error for . I searched the web and add the System.Runtime.Serialization.DataContractSerializer, Would someone tell me what should do. I am using VS2015 as the tool to build it. Thanks.
Imports System.Runtime.Serialization
Imports System.Collections.Generic
Imports System.Runtime.Serialization.DataContractSerializer
<DataContract>
Public Class Locations
<DataMember>
Public Property LocationName As String
<DataMember>
Public Property LocationID As Integer
End Class
Could you please share the error details with me?
As you know, we usually use the datacontract to transmit the complex data type which could be recognized by the client-side and server-side. so that the data could be serialized and transmitted normally between different platforms.
For the restful web service in WCF, we need to use the Webhttpbinding build the data channel and add the Webhttpbehavior to the service endpoint.
I have made a demo, wish it is useful to you.
Server-side.
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
Module Module1
Sub Main()
Dim uri As New Uri("http://localhost:900")
Dim binding As New WebHttpBinding()
binding.CrossDomainScriptAccessEnabled = True
binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
Using sh As New ServiceHost(GetType(MyService), uri)
Dim se As ServiceEndpoint = sh.AddServiceEndpoint(GetType(IService), binding, uri)
se.EndpointBehaviors.Add(New WebHttpBehavior())
sh.Open()
Console.WriteLine("Service is ready")
Console.ReadLine()
sh.Close()
End Using
End Sub
<ServiceContract([Namespace]:="mydomain")>
Public Interface IService
<OperationContract>
<WebGet(ResponseFormat:=WebMessageFormat.Json)>
Function SayHello() As List(Of Product)
End Interface
Public Class MyService
Implements IService
Public Function SayHello() As List(Of Product) Implements IService.SayHello
Dim result = New List(Of Product)() From {
New Product With {
.Id = 1,
.Name = "Apple"
},
New Product With {
.Id = 2,
.Name = "Pear"
}
}
Return result
End Function
End Class
<DataContract([Namespace]:="mydomain")>
Public Class Product
<DataMember>
Public Property Id() As Integer
<DataMember>
Public Property Name() As String
End Class
End Module
Client.
$(function(){
$.ajax({
type:"GET",
url:"http://10.157.18.188:900/sayhello",
dataType:"jsonp",
success:function(d){
$.each(d,function(i,o){
console.log(o.Id);
console.log(o.Name);
})
}
})
})
Result.
Here is an official sample
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-a-basic-wcf-web-http-service
I'm using VB in ASP.NET and I've been looking at trying to deserialize the below JSON for about 4 days now with no success.
The problem is the code I have below is returning null values. I would like to get results of the JSON for each class member I've declared including price and shipping values for each product.
Can anyone point me in the right direction with regard to
1.) why I keep getting null values back and
2.) if the classes I declared are valid for the json I am trying to deserialize?
Any help is greatly appreciated!
Here is an example of the JSON I am working with:
{
"kind": "shopping#products",
"items":
[{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/8040/8382012077897342942",
"product": {
"googleId": "8382012077897342942",
"title": "LEGO Star Wars™: Jabba's Palace™ (9516)",
"description": "Rescue Han Solo from Jabba the Hutt's desert palace!",
"inventories": [
{
"price": 119.99,
"shipping": 12.95,
"currency": "USD"
}
]
}
}
]
}
Here is the Code I have currently:
Imports System.Web.Script.Serialization
Imports Newtonsoft.Json.Linq
Public Class inventories
Public Property price As Double
Public Property shipping As Double
End Class
Public Class product
Public Property googleid As String
Public Property title As String
Public Inventories As inventories()
End Class
Public Class Items
Public Property product As product()
Public Property kind As String
Public Property id As String
End Class
Partial Class JSON_Test
Inherits System.Web.UI.Page
Protected Sub getbutton_Click(sender As Object, e As System.EventArgs) Handles getbutton.Click
' 1. Get JSON string from Google
Dim google_json_string As String
google_json_string = json_text.Text
'2. Deserialize JSON - Method 1
Dim jss As New JavaScriptSerializer
Dim ds_results = jss.Deserialize(Of List(Of Items))(google_json_string)
result1.Text = ds_results.Count
result2.Text = ds_results(0).kind
End Sub
End Class
(Update) I've updated the code to include classes that are structured like this (thanks Dan-o):
Public Class g_JSON
Public Property items As List(Of Items)
End Class
Public Class Items
Public Property product As product()
Public Property kind As String
Public Property id As String
End Class
Public Class product
Public Property googleid As String
Public Property title As String
Public Inventories As inventories()
End Class
Public Class inventories
Public Property price As Double
Public Property shipping As Double
End Class
I also updated the code to read as follows:
Partial Class JSON_Test
Inherits System.Web.UI.Page
Protected Sub getbutton_Click(sender As Object, e As System.EventArgs) Handles getbutton.Click
' 1. Get JSON string from Google
Dim google_json_string As String
google_json_string = json_text.Text
'2. Deserialize JSON - Method 1
Dim jss As New JavaScriptSerializer
Dim ds_results = jss.Deserialize(Of g_JSON)(google_json_string)
result1.Text = ds_results.items(0).id
result2.Text = ds_results.items(0).kind
End Sub
End Class
Now, the code will compile without issue but when I kick off the click event I get the following error:
No parameterless constructor defined for type of 'product[]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for type of 'product[]'.
Source Error:
Line 38: Dim ds_results = jss.Deserialize(Of g_JSON)(google_json_string)
What does that mean and how do I create a parameterless constructor for product()?
Thanks for taking a look!
According to jsonlint your json isn't valid (comma after "inventories" array).
You forgot the container.. the class that holds everything...
Class something
Public property kind as string = String.Empty
Public property items as list(of Item) = Nothing
End Class
Then you deserialize to something, not list(of item)
Ok so I have this interesting ASP.NET MVC 4 solution/project structure, which creates pluggable application modules. I created it following this technique:
http://geekswithblogs.net/cokobware/archive/2013/01/15/asp.net-mvc-4-pluggable-application-modules.aspx
As a result, I have a main application with an empty Areas folder in the project. I also have a Plugin project that resides in the Areas folder of the main application on disk, and it also sets its build output folder to the main application \bin folder.
In my pluggable module application, I decided to create an Areas section within it, and created an Area called Test. By default, the ASP.NET MVC 4 view engine doesn't support it as a pluggable module because it tries to look for the View in the incorrect location.
So conceptually, we have:
Main <- Main application folder
Areas <- Main application folder
Plugin <- Plugin module application folder
Areas <- Plugin module application folder
Test <- Plugin module application folder
To fix this, I created a way to interpret the AreaName property in a customized RazorViewEngine class to rewrite the URL the view engine is looking for to find the view files in these pluggable module areas.
First, I use the following convention to define my Area registration class for the Test Area belonging to my pluggable modules:
Namespace Areas.Plugin
Public Class PluginAreaRegistration
Inherits AreaRegistration
Public Overrides ReadOnly Property AreaName() As String
Get
Return "Plugin.Test"
End Get
End Property
Public Overrides Sub RegisterArea(ByVal context As System.Web.Mvc.AreaRegistrationContext)
context.MapRoute( _
"Plugin_default", _
"Plugin/Test/{controller}/{action}/{id}", _
New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional},
{"Plugin.Test.Controllers"}
)
End Sub
End Class
End Namespace
I then inherited the the RazorViewEngine and overrode some methods to parse and generate the views path in the pluggable module's Areas folder:
Public Class MyExtendedRazorViewEngine
Inherits RazorViewEngine
' set the location format strings
Public Sub New()
MyBase.PartialViewLocationFormats = _
{
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml",
"~/Areas/{3}/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{3}/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{1}/Views/Shared/{0}.cshtml",
"~/Areas/{1}/Views/Shared/{0}.vbhtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.cshtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.vbhtml"
}
MyBase.AreaViewLocationFormats = {
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.vbhtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.cshtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.vbhtml"
}
MyBase.AreaMasterLocationFormats = {
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.vbhtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.cshtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.vbhtml"
}
MyBase.AreaPartialViewLocationFormats = {
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.vbhtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.cshtml",
"~/Areas/{2}/Areas/{1}/Views/{0}.vbhtml"
}
MyBase.ViewLocationFormats = {
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml"
}
MyBase.MasterLocationFormats = {
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml"
}
MyBase.PartialViewLocationFormats = {
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml"
}
End Sub
Protected Overrides Function CreatePartialView(controllerContext As ControllerContext, partialPath As String) As IView
Dim area As String = controllerContext.RouteData.DataTokens.Item("Area")
Dim areaname As String()
Dim pp As String = partialPath
If Not area Is Nothing Then
areaname = area.Split(".")
If areaname.Length > 1 Then
pp = pp.Replace(area, areaname(0) & "/Areas/" & areaname(1))
End If
End If
Return MyBase.CreatePartialView(controllerContext, pp)
End Function
Protected Overrides Function CreateView(controllerContext As ControllerContext, viewPath As String, masterPath As String) As IView
Dim area As String = controllerContext.RouteData.DataTokens.Item("Area")
Dim areaname As String()
Dim vp As String = viewPath
Dim mp As String = masterPath
If Not area Is Nothing Then
areaname = area.Split(".")
If areaname.Length > 1 Then
vp = vp.Replace(area, areaname(0) & "/Areas/" & areaname(1))
mp = mp.Replace(area, areaname(0) & "/Areas/" & areaname(1))
End If
End If
Return MyBase.CreateView(controllerContext, vp, mp)
End Function
Protected Overrides Function FileExists(controllerContext As ControllerContext, virtualPath As String) As Boolean
Dim area As String = controllerContext.RouteData.DataTokens.Item("Area")
Dim areaname As String()
Dim vp As String = virtualPath
If Not area Is Nothing Then
areaname = area.Split(".")
If areaname.Length > 1 Then
vp = vp.Replace(area, areaname(0) & "/Areas/" & areaname(1))
End If
End If
Return MyBase.FileExists(controllerContext, vp)
End Function
End Class
I've modified the main application Global.asax file to pick up the new view engine:
Imports System.Web.Http
Imports System.Web.Optimization
Public Class MvcApplication
Inherits System.Web.HttpApplication
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
WebApiConfig.Register(GlobalConfiguration.Configuration)
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
ViewEngines.Engines.Clear()
ViewEngines.Engines.Add(New MyExtendedRazorViewEngine())
End Sub
End Class
After launching the browser and invoking the Home controller for my main application, I see the correct pages and layout render. When I go to the Home controller action for the Index for my Plugin module, again the Index view renders properly with the _Layout.vbhtml being picked up from the main application.
However, when I invoke the Home controller action for the Index view of Plugin's Test Area, I can only see the Index page view render, but the master _Layout.vbhtml isn't being included from the main application.
What am I missing to get the Areas views below the Plugin pluggable module to render the main application's master layout template?
I have a class module in my App_code folder.
Private _connection As MySqlConnection
Private _connStr As String
Public Function Connect(dbName As String) As Boolean
Try
_connStr = "Database=" & dbName & ";" & _
"Data Source=192.16.0.1;" & _
"User Id=user;Password=pass"
_connection = New MySqlConnection(_connStr)
_connection.Open()
_connection.Close()
Return True
Catch ex As Exception
_connection = Nothing
Return False
End Try
Return False
End Function
I usually program in webform apps. Why can't I access this function from my aspx code behind pages? I added the import statement for the class. If i make that function shared I cant have those private variables.
I call the function in my aspx lik so;
If Connect(dbName) then....
That gets me an error "non shared member requires an object reference"
You need to add the keyword "Shared" to the method signature, like so:
Private Shared _connection As MySqlConnection
Private Shared _connStr As String
Public Shared Function Connect(dbName As String) As Boolean
This is because otherwise you have instance class members, not static members. The compiler error message is quite self-explanatory.
if you look at this example works:
Public Shared Function example123(ByVal USER As Integer, ByVal Section As String, ByVal ACTION As String) As Boolean
you assign a function shared so you can see it from outside the class
I hope you work
I'm not sure if this is possible but I would like to associate a class name reference to a shared member method / property / variable. Consider:
Public Class UserParameters
Public Shared Reference As Object
Public Shared Function GetReference() As Object
Return Reference
End Function
End Class
In another part of the program I would like to simply call UserParameters and have it return Reference either by aliasing GetReference or the variable directly.
I am trying to emulate the Application, Request, or Session variable:
Session(0) = Session.Item(0)
Any suggestions would be greatly appreciated.
You can't return an instance member from a static method directly (the static method can't access instance members because it isn't instantiated with the rest of the class, only one copy of a static method exists).
If you need to setup a class in such a way that you can return an instance from a static method you would need to do something similar to the following:
Public Class SampleClass
Private Sub New()
'Do something here
End Sub
Public Shared Function GetSample() As SampleClass
Dim SampleClass As SampleClass
SampleClass = New SampleClass
SampleClass.Sample = "Test"
Return SampleClass
End Function
Private _SampleString As String
Public Property Sample As String
Get
Return _SampleString
End Get
Private Set(ByVal value As String)
_SampleString = value
End Set
End Property
End Class
Public Class SampleClass2
Public Sub New()
'Here you can access the sample class in the manner you expect
Dim Sample As SampleClass = SampleClass.GetSample
'This would output "Test"
Debug.Fail(Sample.Sample)
End Sub
End Class
This method is used in various places in the CLR. Such as the System.Net.WebRequest class. where it is instantiated in this manner in usage:
' Create a request for the URL.
Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/default.html")