ASP.NET Web Service + Module + Public variable = thread safe? - asp.net

In my ASP.NET Web Service I've included a module in which their are Public declared variables. Will they be thread-safe? Will they get mixed up upon simultaneous calls?
Those variables are mostly DatsSet, DataTable and SQLDataAdapter..
Partial code of the module:
Imports System.Data.OleDb
Imports System.Diagnostics
Module modCommon
Public bDoLog As Boolean
Public sCurrentODBC As String
Public cn As SqlConnection
Public Query1ds As DataSet
Public Query1 As DataTable
Public Query1adapter As SqlDataAdapter
#scripni
Thanks, as I'm not familiary with your suggestions, I will move everything locally.
Additionally, will the following variables be thread-safe?:
[ToolboxItem(False)]_
Public Class Service1
Inherits System.Web.Services.WebService
Dim sName As String
Dim sCurrentPath As String
[WebMethod()]_
Public Function Capture(ByVal sPath As String) As String
sName = "Joe"
End Function
End Class

If you're using web services than yes, you will have concurency problems when multiple services will try to access the same resource, and SqlConnection is definetly a resource you don't want shared.
You should make sure that you don't have simultaneous calls to the properties (for ex. by wrapping the fields with getters / setters and implementing locks in those methods) or by moving the code to a class and instantiating that class whenever you need it.

Related

WebRequestHandler not available in class

We are using the webRequestHandler class successfully in an ASHX handler file but I am unable to access it from a new .vb class file I'm trying to create.
I am familiar with this answer but the .dll is already a reference in my project
The type or namespace name "WebRequestHandler" could not be found
'api.vb
Imports System.Net.Http
Public Class api
public function postAPI() as string
dim handler = New WebRequestHandler() 'Type "WebRequestHandler" is not found
[...]
End Function
End Class
The hander is essentially the same but works fine:
'httpHandler.ashx
Imports System.Net.Http
Public Class apiWebHandler
Implements System.Web.IHttpHandler
Private Function getAPI() As String
Dim handler = New WebRequestHandler() 'works like a charm no compiler issues
[...]
End Function
End Class
Any idea why the WebRequestHandler isn't available here? If it isn't available in a class file what would you recommend we do to send certs via web request?

Create a dataContract in separe file problem

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

Bloated Session Struct:

I understand the basic differences between structs and class types. But, in an ASP.NET WebForms application...what is the ideal container type to hold a relatively large data structure in Session in an ASP.NET WebForms application? Should it be a struct or class? For example...
Public Structure SessionData
Public ShipVias As List(Of XXXXX999.sycdefil_sql_VW)
Public ShipTos As List(Of XXXXX999.ABC_Web_ShipTo_VW)
Public Dests As List(Of XXXXX999.ABC_Web_CofA_VW)
Public Owners As List(Of XXXXX999.ABC_Web_CofA_VW)
Public Carts As List(Of XXXXX999.ABC_Web_Cart_VW)
Public Carriers As List(Of XXXXX999.ABC_Carrier_Accounts_VW)
Public Countries As List(Of XXXXX999.usp_get_CountryListResult)
Public States As List(Of XXXXX999.usp_get_StatesListResult)
Public POItems As List(Of XXXXX999.usp_get_cart_infoResult)
Public SearchResults As List(Of SearchResult)
Public Addresses As List(Of AddressResult)
Public CartItems As List(Of itemsdetail)
Public POs As List(Of POResult)
Public SomeCollection As Collection
Public CmpCode As String
Public CmpStatus As String
Public CmpSIPCust As String
Public CurrentSession As String
Public AllowAccess As Boolean
Public QuickAddItems As List(Of QuickAddItem)
End Structure
As you can probably tell, XXXXX999 contains a LINQTOSQL DataContext dbml containing sprocs, functions, views and tables.
Edit point: I just realized I can make a struct(C#) to be nullable...In vb.net Nullable(Of SessionData)...also question mark does the trick like so...
Dim sd As SessionData?
Should I keep this as a Structure or convert it to a Class?
Convert it to a class. Based on this MSDN link a struct should only be used if:
Consider defining a structure instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
Do not define a structure unless the type has all of the following characteristics:
It logically represents a single value, similar to primitive types (integer, double, and so on).
It has an instance size smaller than 16 bytes.
It is immutable.
It will not have to be boxed frequently.
if you are dealing with distinct values I would use a dictionary that hold dictionaries for every type of list

class modules in asp.net file system website

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

User Controls Importing Problem (asp.net)(vb)

I have this class that contains vars for db connection;
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Web.Configuration
Public Class DBVars
Public Shared s As String
Public Shared con As String = WebConfigurationManager.ConnectionStrings("NMMUDevConnectionStr").ToString()
Public Shared c As New SqlConnection(con)
Public Shared x As New SqlCommand(s, c)
Dim r As SqlDataReader
End Class
I import this to my page like this;
Imports DBVars
I'm then able to access these vars from my page.
But if I try to import them into a user control using the same method the variables are not available. Am I making an error or is this expected?
Thanks.
Make sure you're accessing them in your usercontrol like so:
Dim useMe As String = DbVars.con
and not something like
Dim x As DbVars = new DbVars()
dim useMe As String = x.con
You need to do this because you've declared them as Shared (static) and not as Instance variables.

Resources